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

时间:2012-08-23 13:41:43

标签: javascript firefox javascript-events firefox-addon 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");
    });
  }
});

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

self.port.emit('pageView', { visitTime: time });

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

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

我也尝试过听beforeunload,但这也无效。可能是什么问题?

2 个答案:

答案 0 :(得分:2)

内容脚本在Firefox浏览器加载项中访问的window对象是一个代理对象,可能有点气质。使用window.addEventListener即可。

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

答案 1 :(得分:1)

onbeforeUnload事件不是synchronous,因此浏览器垃圾在完成之前收集页面。使用synchronous AJAX request

function Data() 
 {
 var client = new XMLHttpRequest();
 client.open("GET", "/request", false); // third paramater indicates sync xhr
 client.setRequestHeader("Content-Type", "text/plain;charset=UTF-8");
 client.send({ visitTime: time });
 client.onreadystatechange = emitter;
 }

function emitter()
 {
 self.port.emit('pageView', { visitTime: time });
 }

return a string作为替代方案。

相关问题