这个问题要求一种方法来使用打开一个新窗口window.open
,然后将其注入脚本。由于存在跨域安全问题,因此无法实现。
但是,我的问题是我想做完全相同的事情,除了从同一域到同一域。这可能吗?
请注意,.write
这不会解决此问题,因为它会首先擦除页面中的所有html。
您可以执行以下操作:
var theWindow = window.open('http://stackoverflow.com'),
theDoc = theWindow.document,
theScript = document.createElement('script');
function injectThis() {
// The code you want to inject goes here
alert(document.body.innerHTML);
}
theScript.innerHTML = 'window.onload = ' + injectThis.toString() + ';';
theDoc.body.appendChild(theScript);
这似乎也可行:
var theWindow = window.open('http://stackoverflow.com'),
theScript = document.createElement('script');
function injectThis() {
// The code you want to inject goes here
alert(document.body.innerHTML);
}
// Self executing function
theScript.innerHTML = '(' + injectThis.toString() + '());';
theWindow.onload = function () {
// Append the script to the new window's body.
// Only seems to work with `this`
this.document.body.appendChild(theScript);
};
如果由于某种原因您想使用eval:
var theWindow = window.open('http://stackoverflow.com'),
theScript;
function injectThis() {
// The code you want to inject goes here
alert(document.body.innerHTML);
}
// Self executing function
theScript = '(' + injectThis.toString() + '());';
theWindow.onload = function () {
this.eval(theScript);
};
这是做什么的(代码的第一部分的解释。所有示例都非常相似):
document
innerHTML
以在窗口加载时加载带有window.onload
事件的功能(您也可以使用addEventListener
)。我toString()
为方便起见,所以您不必连接一堆字符串。toString
基本上injectThis
以字符串形式返回整个函数。document.body
,它实际上不会将其追加到已加载的文档中,而是会在载入之前将其追加(到一个空的正文中),这就是为什么必须使用window.onload
,以便脚本可以操纵新文件。如果您的新页面中已有使用该事件的脚本(它将覆盖注入脚本),则最好使用window.addEventListener('load', injectThis.toString());
代替,这是个好主意。window.onload
window.onload
请注意,您可以在injectThis
函数内部执行任何操作:追加DIV,执行DOM查询,添加更多脚本等。
另请注意,您可以theWindow.onload
使用在事件内部操纵新窗口的DOM this
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句