我正在尝试修改我有限制访问权限的网站上的一些CSS。我被允许在服务器上创建页面,但不能修改网站上其他PHP生成的页面。
我正在研究在iframe中注入CSS。我首先隐藏iframe,然后在进行更改后显示它。
不幸的是,我唯一知道我可以访问iframe.contentWindow.document的时间是在iframe.onload()事件触发之后。页面的大部分是异步加载的,所以原本需要等待3秒才能看到屏幕上的内容,现在却要等待7-10秒,而所有的外部内容都被加载了,包括社交媒体内容。
有没有在onload()之前触发的事件,让我知道我有权访问新文档?我只想在头上注射一个stylesheet,我不管90%的DOM是否“准备好”了。
发布于 2017-06-19 14:11:07
我不确定这是否是你想要的东西--但它可能会有所帮助
注意:我一般不喜欢这种类型的代码,我最初认为我会使用MutationObserver -然而,我发现我不得不做类似上面的事情,同时等待iframe的contentDocument指示内容已经开始加载,然后我可以附加突变观察器-然后我会错过一半的时间附加的head元素!
Firefox在iframe上有一个mozbrowserloadstart事件--但那只是firefox,所以在其他地方一点用处都没有
function limitedRetryWithDelay(count, delay, tester, cb) {
var res = tester();
if(res) {
cb(res);
} else {
if (count > 0) {
setTimeout(function() {
limitedRetryWithDelay(count - 1, delay, tester, cb);
}, delay);
}
}
}
// next 3 lines is just how I tested it - you'll need a reference to the iframe node instead for "tgt"
var tgt = document.createElement('iframe');
document.body.appendChild(tgt);
tgt.src = '/index.html?_=' + Math.random() + '_' + Math.random();
// end testing code
// try every 10ms for 5 seconds because (500 * 10 = 5000ms)
limitedRetryWithDelay(500, 10, function (e) {
return tgt.contentDocument && tgt.contentDocument.location != 'about:blank' && tgt.contentDocument.head;
}, function(head) {
console.log('head is', head);
});顺便说一下,在对文档执行某些操作之前,您可能不需要等待head出现,您很可能只需要等待contentDocument
limitedRetryWithDelay(500, 10, function (e) {
return tgt.contentDocument && tgt.contentDocument.location != 'about:blank' && tgt.contentDocument;
}, function(doc) {
console.log('document is', doc);
});https://stackoverflow.com/questions/44622686
复制相似问题