gpt4 book ai didi

javascript - Chrome 扩展 : Message passing confusion

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:38:02 24 4
gpt4 key购买 nike

我正在尝试将页面上选中的项目数发送到弹出窗口。弹出窗口上的 add 输入按钮会提醒或向控制台发送网页上选中的复选框数量。

我的脚本没有这样做,我认为消息传递的工作方式可能存在混淆。这是我所拥有的:

list :

{
"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>

ma​​in_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');
});

});

最佳答案

chrome.extension.onRequest不能在 popup 中使用。它将在后台页面中使用。

背景页

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

Popup - 使用 chrome.extension.getBackgroundPage()取回变量。

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

关于javascript - Chrome 扩展 : Message passing confusion,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7535997/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com