javascript - 如何在 Firefox 的新选项卡中读取和写入数据?

标签 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.document.write("</html>");
newTab.document.close();

// reading what was wrote
newTab.document.getElementById('hello').addEventListener("click", custom_search_function(), false);

但是现在当我尝试执行这段代码时,Firefox 提示安全错误:

错误:SecurityError:操作不安全。

我在论坛上搜索了一个替代方案,这个可行:

var textOnPage = "<html><head><title>I'm just a tab</title></head><body>";
var newTab = window.open("data:text/html;charset=UTF-8," + encodeURIComponent(textOnPage));
newTab.document.close();

但是我无法通过getElementById访问页面

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

返回:

错误:类型错误:newTab.document.getElementById(...) 为空

如何写入这个新选项卡,然后通过 getElementById 等函数返回读取它?

最佳答案

你犯规了 Single Origin Policy .当您打开一个没有 URL 的新窗口时,根据定义,它不能与原始(开启者)窗口具有相同的域名。

您可以改为让 window.open() 调用打开您网站上的另一个 URL(主要是空白 html)并作为其 body.onload 事件处理程序的一部分(或 jQuery.ready()) 您可以为 message 事件设置一个事件处理程序,如下所示:

$(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");

postMessage API 现在在各种现代浏览器中得到了很好的支持。

您仍然无法直接访问 otherWindow 的内容,但您可以将消息从 otherWindow 发回您的原始窗口以实现同样的效果。 (例如:将您的内容操作代码放在 otherWindow 的内容中,并从您的原始窗口“调用”它)。

关于javascript - 如何在 Firefox 的新选项卡中读取和写入数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18157899/

相关文章:

javascript - 使文本适合 SVG 路径

javascript - jQuery 菜单不起作用,即(文档模式 : Quirks)

javascript - 如何使用 AudioWorklet 获取麦克风音量

Javascript 三元运算符和赋值

javascript - 有什么方法可以从浏览器运行服务器或点对点?

javascript - 通过 JS 模块模式返回 ajax 响应

javascript - WebGL中的高级照明

javascript - 将数据附加到 .each 循环中的 div 元素中

javascript - Vue.js 使用 import { } 时找不到导出错误

javascript - 如何使用 Javascript 分离和收集 HTML 属性列表中的不同值?