检测弹出窗口何时关闭

检测弹出窗口何时关闭

本文介绍了Chrome扩展程序:检测弹出窗口何时关闭的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于我的Chrome扩展程序,我想在browserAction弹出窗口关闭时执行一个操作.我了解发生这种情况时不会触发任何内置事件.我发现了此建议以后台脚本打开连接,然后使用该连接的port.onDisconnect事件来检测到弹出窗口正在关闭.

For my chrome extension, I want to perform an action when the browserAction popup window closes. I understand that there no built-in events are triggered when this happens. I found this suggestion to open a connection with the background script, and then use the connection's port.onDisconnect event to detect that the popup window is closing.

但是,当弹出窗口关闭时,我在开发人员控制台中看到了后台脚本的以下错误:

However, when the popup window closes, I see the following error in the Developer Console for the background script:

(BLESSED_EXTENSION context for glkehflnlfekdijfhacccflbffbjhgbd) extensions::messaging:102: Uncaught TypeError: Cannot read property 'destroy_' of undefined{TypeError: Cannot read property 'destroy_' of undefined
   at PortImpl.destroy_ (extensions::messaging:102:37)
   at dispatchOnDisconnect (extensions::messaging:322:29)}

我使用的脚本在下面详细说明.

The scripts that I use are detailed below.

你能看到我要去哪里了吗?

Can you see where I am going wrong?

manifest.json

manifest.json

{ "manifest_version": 2

, "name": "Detect when popup closes"
, "version": "0.1"

, "browser_action": {
    "default_icon": "popup.png"
  , "default_popup": "popup.html"
  }

, "background": {
    "scripts": [
      "background.js"
    ]
  }
}

popup.html

popup.html

<!DOCTYPE html>
<body>
  <h1>Test</h1>

  <script src="popup.js"></script>
</body>
</html>

popup.js

var port = chrome.runtime.connect()

background.js

background.js

chrome.runtime.onConnect.addListener(function (externalPort) {
  externalPort.onDisconnect = function () {
    try {
      var ignoreError = chrome.runtime.lastError
    } catch (error) {
      console.log("onDisconnect")
    }
  }
)

推荐答案

onDisconnect不是可分配的属性.
该对象提供addListener方法来注册回调:

onDisconnect is not an assignable property.
It's an object that provides addListener method to register a callback:

externalPort.onDisconnect.addListener(function() {
    var ignoreError = chrome.runtime.lastError;
    console.log("onDisconnect");
});

这篇关于Chrome扩展程序:检测弹出窗口何时关闭的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-16 06:13