6

我有一個內容腳本,用戶瀏覽頁面的時間長短。爲此,我在每個頁面中插入一個內容腳本,啓動一個計時器,然後在觸發事件時向附加組件發回消息。從內容腳本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過,那也不行:當我這樣做,這是從來沒有收到該消息。可能是什麼問題呢?

+0

您是否在文檔準備好後綁定'onbeforeunload'?其次,你是否嘗試直接附加事件? 'window.onbeforeunload = function(e){self.port.emit('pageView',{visitTime:time}); //這應該會阻止用戶看到對話框。 return undefined; };'在jsfiddle綁定的'onbeforeunload'與jQuery不起作用,直接的方式確實工作 –

+0

我很確定我嘗試了直接的方式(前幾天提出問題),但我會再試一次,儘快給您回覆。綁定發生在jQuery準備就緒後,應該沒問題。 –

+0

[試試這個小提琴](http://jsfiddle.net/CD6DV/1/)並把jquery和javascript按不同順序排列。如果我在jquery中加入'onbeforeunload',我會看到100%的JavaScript處理和jQuery沒有處理。如果在jQuery中使用'beforeunload',我會看到間歇性行爲。所以我認爲JavaScript是最穩定的。你可能會遇到的另一件事情:並不是所有的代碼似乎都被執行了。嘗試在代碼中添加alert(「something」);並且不會看到它正在執行。如果你用一個字符串替換'return undefined',至少你應該看到一個對話框來確認離開頁面 –

回答

2

內容腳本在Firefox瀏覽器加載項中訪問的window對象是一個代理對象,可能有點令人費解。使用window.addEventListener將工作。

window.addEventListener('beforeunload', function(e) { 
    # Do stuff then return undefined so no dialog pops up. 
    return undefined 
}); 
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作爲替代。

相關問題