谷歌chrome扩展对话之间的弹出窗口和标签

Google chrome extension talking between the popup and the tab

本文关键字:窗口 标签 chrome 扩展 对话 之间 谷歌      更新时间:2023-09-26

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

我试了几种方法,但都不起作用。

My manifest:

{
  "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 -_-')
        });
    });
}

main.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..
    }
});