【发布时间】:2015-04-28 03:46:12
【问题描述】:
This question 要求使用window.open 打开一个新窗口,然后用脚本注入它。由于跨域安全问题,这是不可能的。
但是,我的问题是我想做完全相同的事情,除了从同一个域到同一个域。这可能吗?
请注意,.write 并不能解决这个问题,因为它会先擦除页面中的所有 html。
【问题讨论】:
标签: javascript window
This question 要求使用window.open 打开一个新窗口,然后用脚本注入它。由于跨域安全问题,这是不可能的。
但是,我的问题是我想做完全相同的事情,除了从同一个域到同一个域。这可能吗?
请注意,.write 并不能解决这个问题,因为它会先擦除页面中的所有 html。
【问题讨论】:
标签: javascript window
你可以这样做:
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,它实际上不会将其附加到已加载的文档中,它会在加载之前将其附加(到空正文),这就是您必须使用@987654334的原因@,以便您的脚本可以操作新文档。使用window.addEventListener('load', injectThis.toString()); 而不是window.onload 可能是个好主意,以防您的新页面中已经有一个使用window.onload 事件的脚本(它会覆盖注入脚本)。
请注意,您可以在 injectThis 函数内执行任何操作:附加 DIV、执行 DOM 查询、添加更多脚本等...
还请注意,您可以使用 this 在 theWindow.onload 事件中操作新窗口的 DOM。
【讨论】:
是的……
var w = window.open(<your local url>);
w.document.write('<html><head>...</head><body>...</body></html>');
【讨论】:
.write 时,它都会首先清除您目的地的所有内容。不管你在做什么——这行不通。
这是我使用的一个技巧,它使用查询字符串,并且是客户端。不完美但有效:
在发送页面上,执行:
var javascriptToSend = encodeURIComponent("alert('Hi!');");
window.open('mypage.html?javascript=' + javascriptToSend);
将mypage.html 替换为您的页面。现在在接收页面上,添加:
(location.href.match(/(?:javascript)=([^&]+)/)[1])&&eval(decodeURIComponent(location.href.match(/(?:javascript)=([^&]+)/)[1]));
您必须来回做一些工作以确保它有效。
eval(decodeURIComponent(<?=$_GET['javascript'] ?>));
【讨论】:
window.open("")上完成此操作?