-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbroadcast.js
More file actions
70 lines (69 loc) · 1.46 KB
/
broadcast.js
File metadata and controls
70 lines (69 loc) · 1.46 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
(function(){
let listeners={};
let myWorker;
let on=function()
{
//console.log(arguments);
if(arguments.length<2)
{
throw new Error("参数必须至少两个");
}
let callback=arguments[arguments.length-1];
if(typeof(callback)!="function")
{
throw new Error("最后一个参数必须为处理方法");
}
for(let i=0;i<arguments.length-1;i++)
{
let type=arguments[i];
listeners[type]=callback;
}
//console.log(listeners);
};
let send=function(type,data)
{
if(type==null)
{
throw new Error("type不能为null");
}
if(type=="ondisconnect")
{
throw new Error("ondisconnect为内部使用");
}
if(myWorker!=null)
{
myWorker.port.postMessage({type,data});//发送消息
}else
{
console.warn("SharedWorker未初始化");
}
};
window.broadcast={on,send};
window.addEventListener( "load", function(evt)
{
myWorker = new SharedWorker('worker.js');
myWorker.onerror = function(e)
{
console.log("worker异常",e);
};
//接收消息
myWorker.port.onmessage = function(e)
{
console.log("worker 消息",e);
let callback=listeners[e.data.type];
if(callback!=null)
{
callback(e.data,e.data.data);
}
};
//开启worker
myWorker.port.start();
});
window.addEventListener('beforeunload', function(evt)
{
if(myWorker!=null)
{
myWorker.port.postMessage({type:"ondisconnect"});//发送消息
}
});
})();