5 種方式:
- localstorage
- webworker
- web-socket
- cookie
- postMessage
localstorage
先看效果:
test3.gif
代碼:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.js"></script>
<style>
#div1 {
width: 200px;
height: 200px;
background-color: red;
}
</style>
<title>Document</title>
</head>
<body>
<button id="button">Click me.</button>
<script>
jQuery("#button").on('click', () => {
window.localStorage.setItem('a', Math.random())
})
window.addEventListener('storage', e => {
console.log(e)
})
</script>
</body>
</html>
webWorker
先看效果:
test1.gif
看代碼:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.js"></script>
<style>
#div1 {
width: 200px;
height: 200px;
background-color: red;
}
</style>
<title>Document</title>
</head>
<body>
<button id="button1">send</button>
<button id="button2">get</button>
<script>
let worker;
if (typeof Worker === "undefined") {
alert('當(dāng)前瀏覽器不支持webworker')
} else {
worker = new SharedWorker('work.js', 'work2');
worker.port.onmessage = function(e) {
console.log(`獲得worker的數(shù)據(jù):${e.data}`)
}
}
jQuery('#button1').on('click', () => {
let data = parseInt(Math.random() * 10)
console.log(`發(fā)送數(shù)據(jù):${data}`)
worker.port.postMessage(data);
})
jQuery('#button2').on('click', () => {
worker.port.postMessage('get');
})
</script>
</body>
</html>
//work.js
let data1 = '';
this.onconnect = function(e) {
console.log('e', e);
let port = e.ports[0];
port.onmessage = function(e) {
if(e.data === 'get') {
port.postMessage(data1)
}else {
data1 = e.data
}
}
}
web-socket
先看效果:
test0.gif
客戶端代碼(web)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.js"></script>
<style>
#div1 {
width: 200px;
height: 200px;
background-color: red;
}
</style>
<title>Document</title>
</head>
<body>
<button id="button1">send</button>
<button id="button2">get</button>
<script>
let ws = new WebSocket("ws://localhost:3009");
ws.onopen = function(e) {
console.log("Connection open ...");
// ws.send("Hello WebSockets!");
};
ws.onmessage = function(e) {
console.log(`收到數(shù)據(jù)${e.data}`);
// ws.close();
};
ws.onclose = function(evt) {
console.log("Connection closed.");
};
jQuery('#button1').on('click', () => {
let data = parseInt(Math.random() * 10);
console.log(`發(fā)送數(shù)據(jù)${data}`);
ws.send(data)
})
</script>
</body>
</html>
服務(wù)端代碼(koa)
const Koa = require('koa');
const serve = require('koa-static')
const path = require('path')
const Router = require('koa-router');
const websocket = require('koa-websocket')
const home = serve(path.resolve(__dirname, './'))
const app = websocket(new Koa());
let ctxs = new Set();//保證websocket唯一性
app.ws.use(function(ctx, next) {
ctxs.add(ctx);
ctx.websocket.on('message', function(message) {
ctxs.forEach((item, index , arr) => {//客戶端每新建一個(gè)websokcet就會(huì)保存到這個(gè)ctx中,每個(gè)ctx中的websokcet是獨(dú)立的
item.websocket.send(message)
})
});
ctx.websocket.on('close', function(message) {
ctxs.delete(ctx)
})
next(ctx)
} )
const router = new Router()
router.get('*', (ctx, next) => {
ctx.body = 'hello world';
})
app.use(home)
app.use(router.routes())
.use(router.allowedMethods());
app.listen(3009, () => {
console.log('server is started at port 3009')
})
cookie
這個(gè)簡(jiǎn)單就不講了
postMessage
這個(gè)其實(shí)有點(diǎn)限制,就是你必須拿到目標(biāo)窗口的引用譬嚣,否則是通信不了的缕减, 先看效果:
test4.gif
先用koa起2個(gè)服務(wù)(端口號(hào)設(shè)置不一樣就行)泪姨,分別放置2個(gè)index.html.
<!--http://localhost:3009/index.html-->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.js"></script>
<style>
#div1 {
width: 200px;
height: 200px;
background-color: red;
}
</style>
<title>Document</title>
</head>
<body>
<button id="button1">send</button>
<button id="button2">get</button>
<script>
const targetWindow = window.open('http://localhost:3008/index.html'); //這步很重要贺嫂,你必須拿到這個(gè)引用才行
jQuery('#button1').on('click', () => {
let data = parseInt(Math.random() * 10);
console.log(`發(fā)送數(shù)據(jù)${data}`);
targetWindow.postMessage(data, "http://localhost:3008")
})
window.addEventListener('message', function(e) {
console.log(`接受到數(shù)據(jù):${e.data}, 數(shù)據(jù)源:${e.origin}`)
}, true)
</script>
</body>
</html>
<!--http://localhost:3008/index.html-->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.js"></script>
<style>
#div1 {
width: 200px;
height: 200px;
background-color: red;
}
body {
background-color: grey;
}
</style>
<title>Document</title>
</head>
<body>
<button id="button1">send</button>
<button id="button2">get</button>
<script>
window.addEventListener('message', function(e) {
jQuery("body").append(`<p>${e.data}</p>`)
}, false)
</script>
</body>
</html>
參考文獻(xiàn)
https://www.cnblogs.com/lovling/p/7440360.html
https://blog.csdn.net/u014465934/article/details/98869766