IT박스

브라우저 탭 / 창 사이의 자바 스크립트 통신

itboxs 2020. 6. 16. 20:42
반응형

브라우저 탭 / 창 사이의 자바 스크립트 통신


이 질문에는 이미 답변이 있습니다.

Javascript가 동일한 브라우저의 탭 / 창간에 통신하도록하는 가장 안정적인 방법은 무엇입니까? 예를 들어, Tab 2가 오디오 재생을 시작하면 Tab 1은 이에 대해 알고 플레이어를 일시 중지 할 수 있습니다.

뮤직 플레이어로 사이트를 구축하고 있습니다. 현재 사이트에 두 개의 탭을 열면 두 가지 모두에서 음악을 시작할 수 있습니다. 이것은 분명히 나쁘므로 해결책을 찾으려고합니다.

어떤 아이디어? 감사


이것은 오래된 대답이므로 여기에 설명 된 최신 버전을 사용하는 것이 좋습니다.

자바 스크립트; 원점이 동일한 탭 / 창 간 통신


쿠키를 사용하여 브라우저 창과 탭간에 통신 할 수 있습니다.

다음은 발신자와 수신자의 예입니다.

sender.html

<h1>Sender</h1>

<p>Type into the text box below and watch the text 
   appear automatically in the receiver.</p>

<form name="sender">
<input type="text" name="message" size="30" value="">
<input type="reset" value="Clean">
</form>

<script type="text/javascript"><!--
function setCookie(value) {
    document.cookie = "cookie-msg-test=" + value + "; path=/";
    return true;
}
function updateMessage() {
    var t = document.forms['sender'].elements['message'];
    setCookie(t.value);
    setTimeout(updateMessage, 100);
}
updateMessage();
//--></script>

receiver.html :

<h1>Receiver</h1>

<p>Watch the text appear in the text box below as you type it in the sender.</p>

<form name="receiver">
<input type="text" name="message" size="30" value="" readonly disabled>
</form>

<script type="text/javascript"><!--
function getCookie() {
    var cname = "cookie-msg-test=";
    var ca = document.cookie.split(';');
    for (var i=0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(cname) == 0) {
            return c.substring(cname.length, c.length);
        }
    }
    return null;
}
function updateMessage() {
    var text = getCookie();
    document.forms['receiver'].elements['message'].value = text;
    setTimeout(updateMessage, 100);
}
updateMessage();
//--></script>

보다 현대적인 솔루션을 보려면 https://stackoverflow.com/a/12514384/270274를 확인 하십시오.

인용문:

를 사용하여 질문에 언급 된 공유 로컬 데이터 솔루션을 고수하고 localStorage있습니다. 안정성, 성능 및 브라우저 호환성 측면에서 최상의 솔루션 인 것 같습니다.

localStorage 모든 최신 브라우저에서 구현됩니다.

storage이벤트가 발생하면 다른 탭은 변화한다 localStorage. 이것은 의사 소통 목적으로 매우 편리합니다.

참조 :
http://dev.w3.org/html5/webstorage/
http://dev.w3.org/html5/webstorage/#the-storage-event


쿠키가 필요하다고 생각하지 않습니다. 각 문서의 js 코드는 다른 문서 요소에 액세스 할 수 있습니다. 따라서 직접 공유하여 데이터를 공유 할 수 있습니다. 첫 번째 창 w1은 w2를 열고 참조를 저장합니다

var w2 = window.open(...) 

In w2 you can access w1 using the opener property of window.


There is also an experimental technology called Broadcast Channel API that is designed specifically for communication between different browser contexts with same origin. You can post messages to and recieve messages from another browser context without having a reference to it:

var channel = new BroadcastChannel("foo");
channel.onmessage = function( e ) {
  // Process messages from other contexts.
};
// Send message to other listening contexts.
channel.postMessage({ value: 42, type: "bar"});

Obviously this is experiental technology and is not supported accross all browsers yet.


You can do this via local storage API. Note that this works only between 2 tabs. you can't put both sender and receiver on the same page:

On sender page:

localStorage.setItem("someKey", "someValue");

On the receiver page

    $(document).ready(function () {

        window.addEventListener('storage', storageEventHandler, false);

        function storageEventHandler(evt) {
            alert("storage event called key: " + evt.key);
        }
    });

You can communicate between windows (tabbed or not) if they have a child-parent relationship.

Create and update a child window:

<html>
<head>
<title>Cross window test script</title>
<script>
var i = 0;
function open_and_run() {
    var w2 = window.open("", "winCounter"); 
    var myVar=setInterval(function(){myTimer(w2)},1000);
}

function myTimer(w2) {
    i++;
    w2.document.body.innerHTML="<center><h1>" + i + "</h1><p></center>";
}
</script>
</head>
<body>
Click to open a new window 
<button onclick="open_and_run();">Test This!</button>    
</body>
</html>

Child windows can use the parent object to communicate with the parent that spawned it, so you could control the music player from either window.

See it in action here: https://jsbin.com/cokipotajo/edit?html,js,output


Below window(w1) opens another window(w2). Any window can send/receive message to/from another window. So we should ideally verify that the message originated from the window(w2) we opened.

In w1

var w2 = window.open("abc.do");
window.addEventListener("message", function(event){
    console.log(event.data);
});

In w2(abc.do)

window.opener.postMessage("Hi! I'm w2", "*");

Communicating between different JavaScript execution context was supported even before HTML5 if the documents was of the same origin. If not or you have no reference to the other Window object, then you could use the new postMessage API introduced with HTML5. I elaborated a bit on both approaches in this stackoverflow answer.


Found different way using HTML5 localstorage, I've create a library with events like API:

sysend.on('foo', function(message) {
    console.log(message);
});
var input = document.getElementsByTagName('input')[0];
document.getElementsByTagName('button')[0].onclick = function() {
    sysend.broadcast('foo', {message: input.value});
};

it will send messages to all other pages but not for current one.


edit: With Flash you can communicate between any window, ANY browser (yes, from FF to IE at runtime ) ..ANY form of instance of flash (ShockWave/activeX)

참고URL : https://stackoverflow.com/questions/4079280/javascript-communication-between-browser-tabs-windows

반응형