谷歌chrome扩展对话之间的弹出窗口和标签
Google chrome extension talking between the popup and the tab
我希望将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..
}
});
相关文章:
- 窗口确认在 AJAX 帖子中打印 HTML 标签
- jQuery:添加和删除<br>标签,这取决于窗口宽度以及标签是否已经存在
- window.open 会打开一个新标签页,而不是一个新窗口(在 chrome 中)
- 无法使用 Chrome 扩展程序弹出窗口中的按钮打开新标签页
- 在扩展程序的弹出窗口中显示当前标签网址
- Javascript来跟踪点击是否打开了一个新的标签/窗口
- 如何在新标签/窗口中编写文本文档
- 不要打开新标签页、关闭标签页或关闭浏览器窗口
- .click() 事件,当“在新标签页/窗口中打开”时
- 弹出窗口.js 未在 Chrome 扩展程序中的 Popup 的头部标签中执行.html Popup
- 谷歌扩展:标签事件 - 更改窗口
- 弹出窗口中的槽线图具有重叠的轴标签
- 如何在新标签页或窗口中打开iframe链接
- 当 HTML 中的标签发生更改时,粘贴弹出窗口在 Safari(装有 iOS 8.0.2 的 iPad)中消失
- 窗口位置主题标签语法错误在问号后未读取
- 模式窗口上的标签标签不起作用
- 确认消息仅用于浏览器关闭.不是在窗口标签关闭的时候
- 谷歌新闻框,在新窗口/标签中打开新闻页面
- iPad Chrome -提交表单在新的窗口/标签不工作
- 跨窗口/标签在浏览器中使用JavaScript通知