Evanss
Evanss

Reputation: 23563

Prevent iFrame being targeted by JavaScript and having inline styles applied?

I'm making a Chrome extension that inserts an iframe into the page and applies my own styling to it:

const iframe = document.createElement('iframe');
iframe.style.background = 'white';
iframe.style.position = 'fixed';
iframe.style.width = '300px;
iframe.style.height = '50%';
iframe.style.top = '0';
iframe.style.zIndex = '999';
iframe.frameBorder = 'none';
document.documentElement.appendChild(iframe);

Most of the time this works fine but there are some sites which target iframes with JavaScript and apply some inline CSS which messes up the Layout. https://exchange.adobe.com/creativecloud.html?zpluginId=12557&mv=product&mv2=accc does this when you resize the browser.

Is there any way around this? I tried setting the inline styles as !important but it has on affect.

Upvotes: 2

Views: 241

Answers (2)

David Bradshaw
David Bradshaw

Reputation: 13077

Have you looked at the sandbox attribute of the iframe? If you set allow-same-origin to false. Then it will cause the iframe to appear like a cross-origin iframe and block the parent page from accessing it.

Upvotes: 1

Gordon Freeman
Gordon Freeman

Reputation: 3421

1. Solution

You could make use of the css property all
In your case it would look like this:

const iframe = document.createElement('iframe');
iframe.style.all = 'unset'; // maybe also add `! important`
// ...
document.documentElement.appendChild(iframe);

2. Solution

If you want to ensure that your style attribute does not get changed. You could get it done with a MutationObserver

const iframe = document.createElement('iframe');
iframe.style.all = 'unset'; // maybe also add `! important`
// ...
document.documentElement.appendChild(iframe);

const observer = new MutationObserver((event) => {
  // check if styles differ from your initial ones
  // fix them if necessary
});

observer.observe(iframe, {
  attributes: true, 
  attributeFilter: ['style'],
  childList: false, 
  characterData: false
});

It's kind of brute force. But will work for sure.

Upvotes: 1

Related Questions