2015-07-19 28 views
1

我正在嘗試使訪問Facebook時激活的擴展功能生效。直到這一部分都是好的,然後它開始無限期地運行我的代碼。只能運行一次的Chrome擴展程序

我想要的只是在第一次訪問Facebook時運行content.js腳本,然後再次運行它。

我目前的做法是這樣的,但它不工作:

background.js

chrome.extension.onRequest.addListener(function(request, sender, sendResponse) { 
    if (request.storage) { 
    if (typeof request.value != 'undefined') { 
     localStorage[request.storage] = request.value; 
    } 
    sendResponse({storage: localStorage[request.storage]}); 
    } else { 
    sendResponse({}); 
    } 
}); 

content.js

var status; 
chrome.extension.sendRequest({storage: 'status'}, function(response) { 
    status = response.storage; 
}); 

if(status != '1') 
{ 
    chrome.extension.sendRequest({storage: 'status', value: '1'}); 
    // do my stuff here but only 1 time 
} 

的manifest.json

"content_scripts": [ { 
     "js": [ "js/jquery.js", "content.js" ], 
     "matches": [ "https://facebook.com/" ] 
    } ], 

基本上我的想法是t o當我訪問Facebook時運行content.js,然後腳本完成後,我添加一個狀態變量,然後下次檢查狀態是否爲1,這意味着代碼已經運行過。

我該如何做到這一點?

謝謝。

+0

P.S.我的答案是重複的,因爲我的其他評論對評論部分來說太大了。 – Xan

回答

1

1)您正在製作the standard async JavaScript mistake

var status; 
chrome.extension.sendRequest({storage: 'status'}, function(response) { 
    status = response.storage; // <--+ 
});       // | This code didn't execute yet 
          // | 
if(status != '1') // --------------+ 
{ 
    chrome.extension.sendRequest({storage: 'status', value: '1'}); 
    // do my stuff here but only 1 time 
} 

2)您使用的是非常old and deprecated版本的Messagingextension.sendRequest/onRequest需要去,替換是runtime.sendMessage/onMessage

3)最好不要在這裏使用消息; chrome.storage API是專門爲此目的而製作的。再一次,也許你正在使用一些非常古老的教程。

+0

我用這個https://gist.github.com/mohamedmansour/803631,我會嘗試修改你的建議,謝謝 – lincher

+0

@lincher我在那裏添加了一條評論。你還記得你是如何得到這個鏈接的嗎? – Xan

+0

我google搜索「鉻擴展集存儲從內容」 – lincher

相關問題