我正在制作一个 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
});
这是一种蛮力。但肯定会起作用。
关于css - 防止 iFrame 成为 JavaScript 的目标并应用内联样式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66907960/