10. How to realize the communication between multiple tabs in the browser?

How to implement communication between multiple tabs within the browser? (Ali)

WebSocket的,SharedWorker;

You can also call local storage methods such as localstorge, cookies, etc.;

When localstorge is added, modified or deleted in another browsing context, it will fire an event

We communicate page information by listening to events and controlling their values;

Note on quirks: Safari throws a QuotaExceededError exception when setting the localstorge value in incognito mode;


  • using localStorage

use localStorage.setItem(key, value); add content

Use storage events to monitor add, modify, delete actions

window.addEventListener("storage",function(event){  
        $("#name").val(event.key+”=”+event.newValue);  
}); 
  • used cookie + setInterval

Html

<inputidinputid="name"><input type="button" id="btnOK"value="发送">  

页面1:js

$(function(){  
  $("#btnOK").click(function(){  
    varname=$("#name").val();  
    document.cookie="name="+name;  
  });  
});  

页面2:js

//获取Cookie天的内容  
function getKey(key) {  
    return JSON.parse("{\""+ document.cookie.replace(/;\s+/gim,"\",\"").replace(/=/gim, "\":\"") +"\"}")[key];  
}  
//每隔1秒获取Cookie的内容  
setInterval(function(){  
    console.log(getKey("name"));  
 },1000);  

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325808694&siteId=291194637