4

我試圖將頁面上選中項目的數量發送到彈出窗口。彈出警報上的add輸入按鈕或向控制檯發送在網頁上選中的複選框數量。Chrome擴展程序:消息傳遞混亂

我的腳本沒有這樣做,我認爲可能會有消息傳遞的工作方式混淆。以下是我有:

清單:

{ 
    "name": "A plugin for...", 
    "version": "1.0", 
    "background_page": "background.html", 
    "permissions": [ 
    "tabs", "http://*/*", "https://", "*" 
    ], 
    "content_scripts": [ 
    { 
     "matches": ["http://*/*","https://*/*"], 
     "js": ["main_content_script", jquery.min.js", "json.js"] 
    } 
    ], 
    "browser_action": { 
     "name": "Plugin", 
     "default_icon": "icon.png", 
     "popup": "popup.html" 
    } 
} 

Popup.html

<html> 
<script src="jquery.min.js"></script> 
<script> 
$(document).ready(function() { 

    $('#add').click(function(){ 
     add(); 
     alert("add clicked"); 
    }); 

    $('#save').click(function(){ 
     alert("save clicked"); 
    }); 

    $('#delete').click(function(){ 
     alert("delete clicked"); 
    }); 
}); 
</script> 

<script> 

    //chrome.tabs.sendRequest(integer tabId, any request, function responseCallback) 
    //chrome.extension.onRequest.addListener(function(any request, MessageSender sender, function sendResponse) {...})); 

    function add(){ 
     chrome.extension.onRequest.addListener(function(request, sender, sendResponse) 
       console.log(request.count); //? nothing in console 
     }); 
</script> 

<form action="http://www.xxxxx.com/xxxxx/xxxx/session.php" method="post" enctype="text/plain"> 
<input type="submit" value="Add" name="add" id="add"/> 
<input type="submit" value="Save" name="save" id="save"/> 
<input type="submit" value="Delete" name="delete" id="delete"/> 
</form> 
</html> 

main_content_script.js

$(document).ready(function() { 

//var location = window.location.href; 
var checked = $('input:checkbox:checked').length; 

    if(checked > 0){ 

     var values = $('input:checkbox:checked').map(function() { 
      //return $(this).parent().next().html(); --> returns the name 
      var strong_tag = $(this).parent().next().html(); 
      var link_tag = $(strong_tag + 'a').html(); 
      return $(link_tag).attr('href'); 
      }).get(); 

    } else { 

     return false; 

    } 

    if(values){ 
    var count = values.length; 
    alert(count + " values selected: " + values); 
     chrome.extension.sendRequest({count:count}, function(response) { 
      console.log('count sent'); 
     }); 

}); 

回答

2

這裏的問題是你的內容腳本正在發送消息,但沒有活動的監聽器。 popup.html頁面的生命週期始於瀏覽器操作被點擊直至消失。除非您發送請求時網頁恰好存在,否則沒有任何內容會聽取您的請求。

要解決此問題,您應該在background page(它在您的擴展的生命週期中保留)中設置偵聽器(chrome.extension.onRequest.addListener)。

3

chrome.extension.onRequest不適用於popup。它將被用於background page

背景頁面

var count=0; //"count" is outside of any function 
chrome.extension.onRequest(function(request, sender, sendResponse){ 
      count=request.count; 
      console.log(request.count); 
}); 

彈出 - 使用chrome.extension.getBackgroundPage()找回變量。

var count = chrome.extension.getBackgroundPage().count; //get it back 
alert("There are "+count+" checkboxes checked."); //Voilà! 
相關問題