从内容脚本onbeforeunload向附加组件发送消息?

Dav*_*ite 6 javascript firefox firefox-addon dom-events firefox-addon-sdk

我有一个内容脚本,用于计算用户查看页面的时间.为此,我将内容脚本注入每个页面,启动计时器,然后在onbeforeunload触发事件时将消息发送回加载项.

但是,消息似乎永远不会传递给后台脚本.

鉴于我main.js看起来像这样:

var pageMod = require('page-mod'),
    self = require("self");

pageMod.PageMod({
  include: "http://*",
  contentScriptFile: [self.data.url('jquery.min.js'),
                      self.data.url('content.js')],
  onAttach: function(worker) {
    worker.port.on('pageView', function(request) {
      console.log("Request received");
    });
  }
});
Run Code Online (Sandbox Code Playgroud)

我可以main.js使用以下代码发送消息没问题.

self.port.emit('pageView', { visitTime: time });
Run Code Online (Sandbox Code Playgroud)

当我尝试按用户离开页面时遇到问题.当我这样做时,从未收到该消息:

$(window).bind('onbeforeunload', function(e) {
  self.port.emit('pageView', { visitTime: time });
  // This should prevent the user from seeing a dialog.
  return undefined;
});
Run Code Online (Sandbox Code Playgroud)

我也试过听beforeunload,但这也行不通.可能是什么问题呢?

Dav*_*ite 3

内容脚本window在 Firefox 浏览器插件中访问的对象是代理对象,可能有点不稳定。使用window.addEventListener就会起作用。

window.addEventListener('beforeunload', function(e) {
  # Do stuff then return undefined so no dialog pops up.
  return undefined
});
Run Code Online (Sandbox Code Playgroud)