在两个页面/选项卡之间进行交流 [英] Communicate between two pages / tabs
问题描述
我要一个JavaScript文件同时控制两个HTML文件.
I'm wanting a JavaScript file to control two HTML files simultaneously.
<!DOCTYPE html>
<html>
<head>
<title>tryAgainPage1</title>
<meta charset="UTF-8">
</head>
<body>
<div id="page1"></div>
<script src="tryAgain.js"></script>
</body>
</html>
那是第一页.接下来是第二页.
That's page one. Next is page two.
<!DOCTYPE html>
<html>
<head>
<title>tryAgainPage2</title>
<meta charset="UTF-8">
</head>
<body>
<div id="page2"></div>
<script src="tryAgain.js"></script>
</body>
</html>
这是JavaScript:
And here is the JavaScript:
newFunction();
function newFunction() {
document.getElementById("page1").innerHTML = "page one says hello";
document.getElementById("page2").innerHTML = "page two says goodbye";
}
第一页正常工作,第二页无效.我一直在努力使页面彼此对话,但没有成功.我不确定我是否在这种情况下了解如何实现广播频道(如果确实合适的话.)有人可以帮忙吗?
Page one is working, page two isn't. I've been trying for a day to get pages talking to each other, without success. I'm not sure I understand how to implement Broadcast channel in this instance (if indeed that is appropriate.) Can anyone help?
推荐答案
postMessage
如果您正在寻找一种使两个页面或标签进行交流的方法,请查看:
MDN Window. postMessage ,并阅读此 postMessage 文章
或 MDN Broadcast_Channel_API
postMessage
If you're looking for a way to make two pages or tabs communicate you can take a look at:
MDN Window.postMessage, and read this postMessage article
or MDN Broadcast_Channel_API
Using Broadcast Channel API page1 — page2
工作原理:
- pageX 订阅了一个命名的广播频道对象
- pageY 使用
postMessage
广播到相同的频道名称
- pageX 收听
"message"
事件并打印Event.data
- pageX subscribes to a named Broadcast Channel object
- pageY broadcasts to the same Channel name using
postMessage
- pageX listens to
"message"
events and prints theEvent.data
和反之亦然.
page1.html
<h1>PAGE 1</h1>
<p><button data-broadcast="Page 1 talking!">BROADCAST</button></p>
Page 2 says: <div id="page2"></div>
<script src="comm.js"></script>
page2.html
<h1>PAGE 2</h1>
<p><button data-broadcast="Page 2! 'Allo 'Allo!">BROADCAST</button></p>
Page 1 says: <div id="page1"></div>
<script src="comm.js"></script>
comm.js
var bc = new BroadcastChannel('comm');
document.querySelector("[data-broadcast]").addEventListener("click", ev => {
bc.postMessage( ev.target.dataset.broadcast );
});
const targetEl = document.querySelectorAll("#page1, #page2");
bc.addEventListener("message", ev => {
[...targetEl].forEach( el => el.innerHTML = ev.data );
});
localStorage
和storage
事件
如果两个选项卡都在同一个域中,则另一种简单却很酷的方法是使用
Window. localStorage MDN 及其Storage Event
.
localStorage
and the storage
Event
Another simple, yet cool way, if both tabs are on the same domain is by using
Window.localStorageMDN and its Storage Event
.
工作原理:
- pageX 写入
localstorage[pageX]
- pageY 的
window
将触发storage
事件 - pageY 现在可以读取由存储事件发送的
Event.newValue
的localstorage[pageX]
或更好的记录(使它更简单(与 pageN 无关))
- pageX writes to
localstorage[pageX]
- pageY's
window
will trigger astorage
event - pageY can now read
localstorage[pageX]
or better (to make it simpler (and pageN agnostic)) theEvent.newValue
sent by the storage event
和反之亦然.
page1.html
<h1>PAGE 1</h1>
<textarea data-sender="page1" placeholder="Write to page 2"></textarea>
Page 2 says: <div id="page2"></div>
<script src="comm.js"></script>
page2.html
<h1>PAGE 2</h1>
<textarea data-sender="page2" placeholder="Write to page 1"></textarea>
Page 1 says: <div id="page1"></div>
<script src="comm.js"></script>
comm.js
// RECEIVER
window.addEventListener("storage", ev => {
document.getElementById( ev.key ).innerHTML = ev.newValue;
});
// SENDER
[...document.querySelectorAll("[data-sender]")].forEach( el =>
el.addEventListener("input", ev => localStorage[el.dataset.sender] = el.value )
);
Web RTC
您可以使用 Web RTC (网络实时通信). 一项使Web应用程序和网站能够捕获和可选地流音频和/或视频媒体,以及在浏览器之间交换任意数据的技术
Web RTC
You could use Web RTC (Web Real-Time Communications). A technology which enables Web applications and sites to capture and optionally stream audio and/or video media, as well as to exchange arbitrary data between browsers
您的脚本在一页上不起作用...实际上在两者上上,唯一的区别是第1页在实现#page2
元素后找不到,因此破裂了–相反,在另一页上意识到没有"#page1"
元素后立即中断(自第一个开始).
您应该始终使用if ( someElement ) { /*found!*/ }
检查al元素是否存在.
Your script was not working on one page... actually on both, the only difference was that on page 1 broke after realizing #page2
Element could not be found - Inversely on the other page broke immediately after realizing there is no "#page1"
Element (since first in order).
You should always check if al element exists using if ( someElement ) { /*found!*/ }
.
是的,您不能通过这种方式进行交流两页.他们只会共享/包含相同的JS文件.
And yes, you cannot make communicate two pages that way. They will only share / include the same JS file.
这篇关于在两个页面/选项卡之间进行交流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!