防止 iFrame 成为 JavaScript 的目标并应用内联样式?
Prevent iFrame being targeted by JavaScript and having inline styles applied?
我正在制作一个 Chrome 扩展,将 iframe 插入页面并应用我自己的样式:
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);
大多数情况下这工作正常,但有些网站使用 JavaScript 定位 iframe 并应用一些内联 CSS,这会扰乱布局。 https://exchange.adobe.com/creativecloud.html?zpluginId=12557&mv=product&mv2=accc 在调整浏览器大小时执行此操作。
有什么办法解决这个问题吗?我尝试将内联样式设置为 !important
但它有影响。
1。解决方案
您可以利用 css 属性 all
在您的情况下,它看起来像这样:
const iframe = document.createElement('iframe');
iframe.style.all = 'unset'; // maybe also add `! important`
// ...
document.documentElement.appendChild(iframe);
2。解决方案
如果您想确保您的样式属性不被更改。你可以用 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
});
这有点蛮力。但肯定会起作用。
你看过iframe的sandbox属性了吗?如果将 allow-same-origin
设置为 false
。那么就会导致iframe看起来像跨域iframe,阻止父页面访问。
我正在制作一个 Chrome 扩展,将 iframe 插入页面并应用我自己的样式:
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);
大多数情况下这工作正常,但有些网站使用 JavaScript 定位 iframe 并应用一些内联 CSS,这会扰乱布局。 https://exchange.adobe.com/creativecloud.html?zpluginId=12557&mv=product&mv2=accc 在调整浏览器大小时执行此操作。
有什么办法解决这个问题吗?我尝试将内联样式设置为 !important
但它有影响。
1。解决方案
您可以利用 css 属性 all
在您的情况下,它看起来像这样:
const iframe = document.createElement('iframe');
iframe.style.all = 'unset'; // maybe also add `! important`
// ...
document.documentElement.appendChild(iframe);
2。解决方案
如果您想确保您的样式属性不被更改。你可以用 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
});
这有点蛮力。但肯定会起作用。
你看过iframe的sandbox属性了吗?如果将 allow-same-origin
设置为 false
。那么就会导致iframe看起来像跨域iframe,阻止父页面访问。