跨标签页通信
1、BroadCast實現跨標簽頁通信
index.html
<!DOCTYPE html> <html lang="en"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title> </head><body><input type="text" id="content"><button id="btn">發送數據</button><script>const content = document.querySelector('#content')const btn = document.querySelector('#btn')const broadCastChannel = new BroadcastChannel('load');btn.onclick=function(){broadCastChannel.postMessage({value:content.value})}</script> </body></html>index2.html
<!DOCTYPE html> <html lang="en"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title> </head><body><script>const broadCastChannel = new BroadcastChannel('load');broadCastChannel.onmessage = function (e) {console.log(e.data);}</script> </body></html>1、Service Worker實現跨標簽頁通信
index.html
<!DOCTYPE html> <html lang="en"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title> </head><body><input type="text" id="content"><button id="btn">發送數據</button><script>const content = document.querySelector('#content')//注冊service workernavigator.serviceWorker.register('sw.js').then(() => {console.log('service worker 注冊成功');})btn.onclick = function () {navigator.serviceWorker.controller.postMessage({value: content.value})}</script> </body></html>index2.html
<!DOCTYPE html> <html lang="en"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title> </head><body><script>navigator.serviceWorker.register('sw.js').then(() => {console.log('service worker 注冊成功');})navigator.serviceWorker.onmessage = function ({ data }) {console.log(data);}</script> </body></html>sw.js
self.addEventListener("message", async event => {//首先獲取到所有注冊了 service worker的客戶端const clients = await self.clients.matchAll();clients.forEach(function(client) {client.postMessage(event.data.value)}); })3、storage實現跨標簽頁通信
index.html
<!DOCTYPE html> <html lang="en"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title> </head><body><script>localStorage.name = "胡";localStorage.age = 20;console.log('信息已經設置');</script> </body></html>index2.html
<!DOCTYPE html> <html lang="en"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title> </head><body><script>window.onstorage = function (e) {console.log("修改的鍵為:", e.key);console.log("之前的值為:", e.oldValue);console.log("修改后的值為:", e.newValue);console.log(e.storageArea);console.log(e.url);}</script> </body></html>4、SharedWorker實現跨標簽頁通信
index.html
<!DOCTYPE html> <html lang="en"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title> </head><body><input type="text" id="content"><button id="btn">發送數據</button><script>const content = document.querySelector('#content')const btn = document.querySelector('#btn')//注冊service workerconst worker=new SharedWorker('worker.js')btn.onclick=function(){worker.port.postMessage(content.value)}</script> </body></html>index2.html
<!DOCTYPE html> <html lang="en"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title> </head><body><script>const worker=new SharedWorker('worker.js')worker.port.start();worker.port.onmessage=function(e){if(e.data){console.log('來自worker的數據',e.data);}}setInterval(function(){worker.port.postMessage('get')})</script> </body></html>worker.js
let data = "" onconnect = function (e) {let port = e.ports[0];port.onmessage = function (e) {if (e.data === 'get') {port.postMessage(data);data = ""} else {data = e.data;}} }5、IndexDB實現跨標簽通信
index.html
<!DOCTYPE html> <html lang="en"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title> </head><body><h1>新增學生</h1><div><span>學生學號:</span><input type="text" name="stuId" id="stuId"></div><div><span>學生姓名:</span><input type="text" name="stuName" id="stuName"></div><div><span>學生年齡:</span><input type="text" name="stuAge" id="stuAge"></div><button id="addBtn">新增學生</button><script src="./db.js"></script><script>let btn = document.querySelector('#addBtn');let stuId = document.querySelector("#stuId");let stuName = document.querySelector("#stuName");let stuAge = document.querySelector("#stuAge");openDB('stuDB', 1).then(db => {btn.onclick = function () {addData(db, "stu", {"stuId":stuId.value,"stuName":stuName.value,"stuAge":stuAge.value})stuId.value=stuAge.value=stuName.value=""}})</script> </body></html>index2.html
<!DOCTYPE html> <html lang="en"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title> </head><body><h1>學生表</h1><table id="tab"></table><script src="./db.js"></script><script>function render(arr) {let tab = document.querySelector("#tab");console.log(tab);tab.innerHTML = `<tr><td>學號</td><td>姓名</td><td>年齡</td></tr>`let str = arr.map(item => {return `<tr><td>${item.stuId}</td><td>${item.stuName}</td><td>${item.stuAge}</td></tr>`}).join("");tab.innerHTML += str;}async function renderTable() {let db = await openDB('stuDB', 1)let stuInfo = await getDataByKey(db, 'stu')render(stuInfo)setInterval(async () => {let stuInfo2 = await getDataByKey(db, 'stu');if (stuInfo2.length !== stuInfo.length) {render(stuInfo2)}}, 1000)}renderTable();</script> </body></html>db.js
/*** * @param {*} dbName 數據庫名稱* @param {*} version 倉庫名稱*/function openDB(dbName, version = 1) {return new Promise((resolve, reject) => {let db;//打開數據庫,若沒有則會創建const request = indexedDB.open(dbName, version);//數據庫打開成功的回調request.onsuccess = function (event) {db = event.target.result;console.log('數據庫打開成功');resolve(db);}//數據庫打開失敗的回調request.onerror = function (event) {console.log('數據庫打開報錯');}數據庫有更新時候的回調request.onupgradeneeded = function (event) {//數據庫創建或升級的時候會觸發console.log('onupgradeneeded');db = event.target.result;let objectStore;//創建存儲庫(表)objectStore = db.createObjectStore('stu', {keyPath: "stuId", //主鍵autoIncrement: true //實現自增})//創建索引,在后面查詢數據的時候可以根據索引查objectStore.createIndex('stuId', "stuId", { unique: true })objectStore.createIndex('stuName', "stuName", { unique: false })objectStore.createIndex('stuAge', "stuAge", { unique: false })}}) } /*** * @param {*} db 數據庫實例* @param {*} storeName 倉庫名稱* @param {*} data 數據*/ function addData(db, storeName, data) {let request = db.transaction([storeName], "readwrite") //事物對象 指定表格名稱和操作模式(”只讀“或”讀寫“ ).objectStore(storeName) //倉庫(表)對象.add(data)request.onsuccess = function (event) {console.log("數據寫入成功");}request.onerror = function (event) {console.log("數據寫入失敗");} } /*** * @param {*} db 數據庫實例* @param {*} storeName 倉庫名稱* @param {*} key 主鍵值*/ function getDataByKey(db, storeName, key) {return new Promise((resolve, reject) => {let transaction = db.transaction([storeName]) //事務let objectStore = transaction.objectStore(storeName) //倉庫對象let request = objectStore.getAll(); //通過主鍵獲取數據request.onerror = function (event) {console.log('事務失敗');}request.onsuccess = function (event) {resolve(request.result);}}) }6、cookie實現跨標簽通信
index.html
<!DOCTYPE html> <html lang="en"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title> </head><body><script>document.cookie = "name='xiejie'"console.log('cookie設置成功');</script> </body></html>index2.html
<!DOCTYPE html> <html lang="en"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title> </head><body><script>let cookie = document.cookie;setInterval(() => {if (document.cookie !== cookie) {console.log(`cookies有更新,最新的值為${document.cookie}`);cookie = document.cookie}}, 1000)</script> </body></html>7、postMessage實現跨標簽頁通信
index.html
<!DOCTYPE html> <html lang="en"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title> </head><body><button id="popBtn">彈出新窗口</button><input type="text" id="content"><button id="btn">發送數據</button><script>let popBtn = document.querySelector("#popBtn");let content = document.querySelector("#content")let btn = document.querySelector('#btn');let opener = null; // 用來保存window.open打開的窗口的的索引popBtn.onclick = function () {opener = window.open('index2.html', "123123", "height=400,width=400,top=20,resizeable=yes");console.log(opener);}btn.onclick = function () {let data = {value: content.value}//data代表是要發送的數據,第二個參數是origin,使用*代表所有域opener.postMessage(data,"*");}</script> </body></html>index2.html
<!DOCTYPE html> <html lang="en"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title> </head><body><p>這是頁面二</p><script>window.addEventListener('message',function(e){console.log(e.data);}) </script> </body></html>8、Websocket實現跨標簽頁通信
記得要先把server服務器打開
index.html
<!DOCTYPE html> <html lang="en"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title> </head><body><input type="text" id="msg"><button id="send">發送消息</button><script>let msg = document.querySelector("#msg");let btn = document.querySelector("#send");//建立websocket鏈接let ws = new WebSocket("ws://localhost:3000");btn.onclick = function () {let value = msg.value.trim();if (value !== "") {ws.send(value)}}window.onbeforeunload = function () {ws.close();}</script> </body></html>index2.html
<!DOCTYPE html> <html lang="en"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title> </head><body><script>//建立websocket鏈接let ws = new WebSocket("ws://localhost:3000");let count = 1;ws.onopen = function () {ws.onmessage = function (event) {let oP = document.createElement('p');oP.innerHTML = `第${count}次接收到的消息為:${event.data}`document.body.appendChild(oP);count++;}}window.onbeforeunload = function () {ws.close();}</script> </body></html>server.js
//首先獲取到一個WebSocketServer類 let WebSocketServer = require('ws').Server //創建WebSocket服務器 let wss = new WebSocketServer({port: 3000 }) //該數組用于保存所有的客戶端連接實例 let clients = [] //當客戶端連接上WebSocket服務器的時候 //就會觸發connection事件,該客戶端的實例就會傳如此回調函數 wss.on('connection', function (client) {//將當前客戶端連接實例保存到數據里面clients.push(client);console.log(`當前有${clients.length}個客戶端在線.....`);client.on('message', function (msg) {console.log('收到的消息為:' + msg);//接下來需要將收到的消息推送給其他所有的客戶端for (const c of clients) {if (c !== client) {c.send(msg.toString())}}})client.on('close', function () {let index = clients.indexOf(this);clients.splice(index, 1);console.log(`當前有${clients.length}個客戶端在線.....`);}) }) console.log('WebSocket服務器已經啟動......');以上只是我的學習筆記,方便以后復習使用。
總結
- 上一篇: 机柜服务器装系统,如何正确的选择服务器机
- 下一篇: WIN7管理员账号删除后无法获取管理员权