Reputation: 2342
I wish to pass JS info from the popup to the background tab.
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:
function() {
var btncolor = "red";
chrome.extension.onRequest.addListener(function() {
$("body").css("background",btncolor);
alert("!");
});
}
Any help would be very much appreciated
Upvotes: 0
Views: 147
Reputation: 826
You'll need to make a request function in your popup.js
, and then listen for it in your main JS file. Try this:
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..
}
});
Upvotes: 1