Chrome扩展程序:检测弹出窗口何时关闭

时间:2016-09-27 17:03:44

标签: google-chrome-extension popup

对于我的chrome扩展,我想在browserAction弹出窗口关闭时执行操作。我知道发生这种情况时不会触发内置事件。我找到this suggestion来打开与后台脚本的连接,然后使用连接的port.onDisconnect事件来检测弹出窗口是否正在关闭。

但是,当弹出窗口关闭时,我在Developer Console中看到后台脚本出现以下错误:

(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)}

我使用的脚本详述如下。

你能看到我出错的地方吗?

的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

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

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

popup.js

var port = chrome.runtime.connect()

background.js

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

2 个答案:

答案 0 :(得分:4)

onDisconnect不是可转让的财产 它是一个提供addListener方法来注册回调的对象:

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

答案 1 :(得分:2)

作为参考,这里是background.js脚本的工作版本:

chrome.runtime.onConnect.addListener(function (externalPort) {
  externalPort.onDisconnect.addListener(function () {
    console.log("onDisconnect")
    // Do stuff that should happen when popup window closes here
  })

  console.log("onConnect")
})