使用脚本注入打开的窗口

Dae*_*est 7 javascript window

这个问题要求使用一种方法打开一个新窗口window.open,然后用脚本注入它.由于跨域安全问题,这是不可能的.

但是,我的问题是我想做同样的事情,除了从同一个域到同一个域.这可能吗?

请注意,这.write并不能解决此问题,因为它首先从页面中擦除所有html.

小智 10

你可以这样做:

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);
Run Code Online (Sandbox Code Playgroud)

这似乎也有效:

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);
};
Run Code Online (Sandbox Code Playgroud)

如果由于某种原因你想使用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);
};
Run Code Online (Sandbox Code Playgroud)

这是做什么的(第一段代码的解释.所有的例子非常相似):

  • 打开新窗口
  • 获取对新窗口的引用 document
  • 创建一个脚本元素
  • 将您要"注入"的所有代码放入函数中
  • 更改脚本innerHTML以在窗口加载时加载所述函数,并使用该window.onload事件(您也可以使用addEventListener).我toString()方便使用,所以你不必连接一堆字符串.toString基本上将整个injectThis函数作为字符串返回.
  • 将脚本附加到新窗口document.body,它实际上不会将它附加到加载的文档中,它会在加载之前附加它(到空体),这就是你必须使用的原因window.onload,这样你的脚本就可以操作了新文件.

如果你的新页面中已经有一个使用该事件的脚本(它会覆盖注入脚本),那么使用它window.addEventListener('load', injectThis.toString());代替它可能是一个好主意.window.onloadwindow.onload

请注意,您可以在injectThis函数内部执行任何操作:追加DIV,执行DOM查询,添加更多脚本等...

另外请注意,你可以操纵新窗口的DOM的内部theWindow.onload事件,使用this.

  • 适用于FF.铬?没有. (2认同)