javascript - 在没有窗口引用的情况下在选项卡 dom 之间进行通信

标签 javascript html google-chrome service-worker

<分区>

我使用以下命令打开带有一些页面内容的新标签页(在新进程中),

var p = document.getElementById("myElement"); 
var a = document.createElement('a');
a.setAttribute('href',".../mypage.html");
a.setAttribute('rel',"noreferrer");
a.setAttribute('target',"_blank");
p.appendChild(a);
a.click();

http://news.softpedia.com/news/Force-Google-Chrome-to-Open-Links-in-New-Processes-128962.shtml

这是有效的,新标签打开时包含 myPage.html 内容。

假设这是我的页面(仅供示例...)我应该如何访问它?

<!DOCTYPE html>
<html>
<body>

<h1> Heading</h1>
<p> paragraph.</p>
 <button type="button">Click Me!</button>

</body>
</html>

Now Let's go to the tricky/advanced :) part...

当您使用 window.open(我不能使用)时,这非常简单,因为您可以使用各种技术。

 1. using window object
 2. post message
 https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage
 3. cookies 
 4. localStorage

但在这里我打开这个新页面时没有使用 window.open 获得的引用

我的问题是:

How can I access to this new tab dom if I want to change something

最佳答案

父页面 JavaScript:

var lastMessage;
setInterval(function() {
  var message = localStorage.getItem('message-to-parent');
  if (message && message !== lastMessage) {
    lastMessage = message;
    // your code here
    alert('There is a new message for you: ' + message);
  }
}, 100);

子页面 JavaScript:

localStorage.setItem('message-to-parent', 'hello, my parent!');

如果你有很多动画和其他巨大的 JS 代码,我建议增加计时器间隔,或者更好地解决 window 的问题。

关于javascript - 在没有窗口引用的情况下在选项卡 dom 之间进行通信,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40117264/

相关文章:

javascript - NextJS React 应用程序样式组件未正确渲染 : Warning: Prop `className` did not match

javascript - jquery this 与 $(this) 甚至 $this

javascript - 检索通过 POST 方法表单传递的值

html - 如何使背景图像滚动而不平铺在页面上?

google-chrome - 在浏览器中查看格式化 HTML 源代码的工具

javascript - 具有不同端口的浏览器同步服务命令

javascript - Facebook 环绕文字

Javascript - 单击空格时左侧下拉菜单不会消失,但尽管代码相同,但右侧下拉菜单会消失。使困惑

javascript - Chrome 用户脚本是否与 Greasemonkey 脚本一样与全局命名空间分开?

html - 在 Chrome 中的列的随机左侧发现意外边框