我試圖將頁面上選中項目的數量發送到彈出窗口。彈出警報上的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');
});
});