我希望将弹出窗口中的JS信息传递给后台标签 这可能吗?
我尝试了几件事,但没有任何效果。
我的清单:
{
"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("!");
});
}
非常感谢任何帮助
答案 0 :(得分:1)
您需要在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..
}
});