Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/368.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript removeEventListener(“beforeunload”之前)不工作_Javascript_Event Handling_Dom Events_Onbeforeunload - Fatal编程技术网

Javascript removeEventListener(“beforeunload”之前)不工作

Javascript removeEventListener(“beforeunload”之前)不工作,javascript,event-handling,dom-events,onbeforeunload,Javascript,Event Handling,Dom Events,Onbeforeunload,我有一个网络工作者向主页发送消息 我为Web Worker的消息事件添加了一个侦听器: 当消息的内容为0时,我将为beforeunload事件向窗口对象添加一个侦听器 当消息的内容为1时,我将删除beforeunload事件的前一个侦听器 这是主页:(main.html) 控制台的内容: "event added" "event removed" 由于在添加或删除时使用了相同的事件(beforeunload)、相同的函数(unloadPage)和相同的第三个参数(false),因此我希望正

我有一个网络工作者向主页发送消息

我为Web Worker的消息事件添加了一个侦听器:

  • 当消息的内容为0时,我将为beforeunload事件向窗口对象添加一个侦听器

  • 当消息的内容为1时,我将删除beforeunload事件的前一个侦听器

这是主页:(main.html)

控制台的内容:

"event added"
"event removed"
由于在添加或删除时使用了相同的事件(beforeunload)、相同的函数(unloadPage)和相同的第三个参数(false),因此我希望正确删除该事件

但是当我刷新页面时,会调用unloadPage()函数。

如果我在全局范围内声明unloadPage,则事件将被正确删除。但我不想那样做

我觉得addEventListener中的unloadPage与removeEventListener中的unloadPage不一样,但我不明白为什么,因为它是同一个函数


我在Firefox 45.0和47.0上进行了测试。

你说得对
unloadPage
始终是每次邮件到达时的新功能。谢谢!我认为
unloadPage
始终是同一个函数,因为它不是匿名函数。我想我必须在消息侦听器函数之外声明
unloadPage
postMessage(0);
postMessage(1); 
"event added"
"event removed"