简体   繁体   English

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

[英]Google chrome extension talking between the popup and the tab

I wish to pass JS info from the popup to the background tab. 我希望将JS信息从弹出窗口传递到背景选项卡。
Is this possible? 这可能吗?

I tried several things but nothing worked. 我尝试了几件事,但没有任何效果。

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://*/*"]
  }]
}

My popup: 我的弹出窗口:

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

And my JS: 而我的JS:

function() {

var btncolor = "red";

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

}

Any help would be very much appreciated 任何帮助将不胜感激

You'll need to make a request function in your popup.js , and then listen for it in your main JS file. 您需要在popup.js创建一个request函数,然后在主JS文件中侦听它。 Try this: 尝试这个:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM