gpt4 book ai didi

javascript - Google Chrome 扩展程序在弹出窗口和选项卡之间进行对话

转载 作者:行者123 更新时间:2023-12-03 12:18:22 25 4
gpt4 key购买 nike

我希望将 JS 信息从弹出窗口传递到后台选项卡。
这可能吗?

我尝试了几种方法,但没有任何效果。

我的 list :

{
"name": "Test",
"description": "Make the current page red",
"version": "2.0",
"permissions": [
"activeTab"
],
"background": {
"persistent": false
},
"browser_action": {
"default_title": "Make this page red",
"default_popup": "popup.html",
},
"manifest_version": 2
,
"content_scripts": [ {
"js": [ "jquery.min.js" ],
"matches": [ "http://*/*", "https://*/*"]
}]
}

我的弹出窗口:

<head>
<title>Options for Color Chooser</title>
<script type="text/javascript" src="popup.js"></script>
</head>
<body style="width:300px; height:250px; text-align:center;">
<input id="gobtn" type="button" value="Start" />
</body>
</html>

还有我的 JS:

function() {

var btncolor = "red";

chrome.extension.onRequest.addListener(function() {
$("body").css("background",btncolor);
alert("!");
});

}

任何帮助将不胜感激

最佳答案

您需要在 popup.js 中创建一个请求函数,然后在主 JS 文件中监听它。试试这个:

popup.js

var btn = document.getElementById('gobtn');
btn.addEventListener('click', setPageColor);

function setPageColor( newColor ) {

newColor = newColor || 'red';

// This is the syntax for "talking" to our current tab
chrome.tabs.getSelected(null, function(tab) {
chrome.tabs.sendRequest(tab.id, {action: "setColor", color: newColor}, function(response) {

// You can do whatever you want with the response :)
if (response.msg === 'SUCCESS') console.log('It worked!')
if (response.msg === 'FAIL') console.error('Fail -_-')

});
});
}

ma​​in.js

...

// This is the "receiving end", which has full DOM/window access on the tab
chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
// request.action provides a nice pattern for re-using this listener
if (request.action == "setColor") {
color = request.color;
document.body.setAttribute('style', 'color:' + color)
sendResponse({ msg: 'SUCCESS' });
}
else {
sendResponse({ msg: 'FAIL' }); // Send nothing..
}
});

关于javascript - Google Chrome 扩展程序在弹出窗口和选项卡之间进行对话,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24568731/

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