Javascript 我如何阅读&;将数据写入Firefox中的新选项卡?

Javascript 我如何阅读&;将数据写入Firefox中的新选项卡?,javascript,Javascript,在过去,这种方法曾经奏效: // writing var newTab = window.open(); newTab.document.write("<html><head><title>I'm just a tab</title></head>"); newTab.document.write("<body id='hello'>With some text on it</body>"); newTab.do

在过去,这种方法曾经奏效:

// writing
var newTab = window.open();
newTab.document.write("<html><head><title>I'm just a tab</title></head>");
newTab.document.write("<body id='hello'>With some text on it</body>");
newTab.document.write("</html>");
newTab.document.close();

// reading what was wrote
newTab.document.getElementById('hello').addEventListener("click", custom_search_function(), false);
但是我无法通过
getElementById

newTab.document.getElementById('hello').addEventListener("click", custom_search_function(), false);
返回:

Error:TypeError:newTab.document.getElementById(…)为空


如何写入此新选项卡,然后通过函数(如
getElementById
)返回读取它?

您正在违反。当您打开一个没有URL的新窗口时,根据定义,它不能与原始(打开器)窗口具有相同的域名

您可以让
窗口.open()
调用打开站点上的另一个URL(大部分为空白html),并将其作为
正文的一部分.onload
事件处理程序(或
jQuery.ready()
)您可以为
消息
事件设置事件处理程序,如下所示:

$(document).ready(function(){
   window.addEventListener("message", receiveMessage, false);
});

function receiveMessage(evt)
{
  if (evt.origin !== "https://your-domain.here")
    return;

  // do something with evt.data
  $(document.body).append(""+evt.data);
}
在原始窗口中,您可以调用:

otherWindow.postMessage(message, "https://your-domain.here");
该API现在在各种现代浏览器中都得到了很好的支持


您仍然无法直接进入以手动上传
其他窗口
的内容,但您可以将消息从
其他窗口
发回原始窗口以实现相同的效果。(例如:将您的内容操作代码放入
其他窗口的内容中,然后从您的原始窗口“调用”它)。

这在很长一段时间内都适用于各种浏览器(在我过去作为web开发人员的生活中,我实际上在web应用程序中利用了这种技术)。过去,window.open页面被视为与父页面来自同一个域(尽管行为总是有点奇怪,url栏中的url通常为:空白)

现在的标准是打开url来源为:blank的页面,虽然我能理解为什么简化事情是有意义的,我也能理解这打破了以前行为的原因,但这里的问题是:blank不是真正的url,所以标准的跨来源规则应该不同,至少在window.open调用的情况下


允许windows对其打开的页面进行写操作是否存在真正的安全威胁?我不这样认为,但这是可能的。最后,我不再是一名web开发人员,也不太关心这些事情,但如果其他人的应用程序也坏了,我也不会感到惊讶。

可能重复@nneonneo,这是当今一种非常古老的方法。现在首选
postMessage
API。
otherWindow.postMessage(message, "https://your-domain.here");