Skip to content Skip to sidebar Skip to footer

Delayed Registration Of Event Listeners In A Vue 3 Instance Inside An Iframe

For a very specific reason*, I need a Vue instance to run inside an iframe. I managed to do that following this thread on Vue forum, and tweaking the code to support Vue 3 and remo

Solution 1:

Answering my own question, since no one has shed any light on this. This does not, hovewer, answer the original question, but I figured that should anyone stumble upon this problem, they should know how I managed to solve it.

In the end, I ditched the idea of an iFrame and used the concept of Shadow DOM to isolate the page's CSS and the injected extension's CSS from each other.

Although this approach comes with its own caveats*, it is IMHO superior to using iframes.

*like the need to manually inject custom styles into the shadow-root. And also the need to store the shadow-root element somewhere that all parts of your application can access (NOT Vuex, the element itself cannot be stored there) in order to make things like work.

Here is a snippet of code I used to inject the sidebar into the page:

// append a new node to the document bodylet shadowHost = document.createElement("div");
document.body.appendChild(shadowHost);
    
// make it the root of our shadow DOMlet shadow = shadowHost.attachShadow({ mode: 'open'})

// create a new node for the sidebarlet sidebar = document.createElement("div");
sidebar.id = "my-sidebar";

// and also a style node into which we put all our custom cssconst style = document.createElement('style');
// getPackedCss is my function that returns all the custom css as a string
style.textContent = getPackedCss();

// and append those to the shadow DOM
shadow.appendChild(style);
shadow.appendChild(sidebar);
    
// store the shadow root somewhere that we can access// globally in order to select elements from it
staticStore.shadowRoot = shadow;

// create our vue app and mount it to the shadow DOMconst app = createApp(MyApp);
app.mount(sidebar);

If you reeeally need Vue 3 and an iframe to like each other, I guess you are on your own here.

Post a Comment for "Delayed Registration Of Event Listeners In A Vue 3 Instance Inside An Iframe"