【发布时间】:2015-12-24 04:30:13
【问题描述】:
您好,我正在编写一个简单的 chrome 扩展程序,用于:
1.打开新网页
2. 根据粘贴的字符串数组填写时间表表单
3. 提交时间表(只需点击表格中的“确定”按钮)
4. 打开新网页
为此,我的扩展程序需要包含:
1. popup.html 浏览器操作弹出窗口,input textfield 为字符串数组,提交按钮。
2. timesheet.js - 向 popup.html
添加逻辑的 javascript 文件
3. background.js - 点击提交按钮
后填写表单的后台页面
4. content_script.js - 访问新打开的网页DOM,填写表单。
现在,我做了一个简化版,应该是:
1. 在新标签页中打开 www.google.com
2.等待几秒钟(可选,等待或页面完成加载)
3.改变背景颜色
一切似乎都很好,除了 content_script.js 侦听器对 background.js
发送的消息没有反应代码如下:
manifest.json:
{
"manifest_version": 2,
"name": "Timesheet Filler",
"description": "Description.",
"version": "1.0",
"background": {
"persistent": false,
"scripts": ["background.js"]
},
"content_scripts": [{
"matches": ["http://www.google.com/*"],
"js": ["content_script.js"]
}],
"browser_action": {
"default_title": "Timesheet Filler",
"default_popup": "popup.html"
},
"permissions": [
"tabs",
"activeTab",
"http://www.google.com/*"
]
}
popup.html:
<!DOCTYPE html>
<html>
<body>
<button id="btn" >Click Me!</button>
<script src="timesheet.js"></script>
</body>
</html>
timesheet.js:
document.addEventListener('DOMContentLoaded', function(){
init();
});
function init(){
var btn = document.getElementById('btn');
btn.onclick = function() { onBtnClick(); }
}
function onBtnClick(){
chrome.runtime.sendMessage({action:"btnClick"}, btnClickCallback);
}
function btnClickCallback(any){
alert(any);
}
background.js
chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) {
if(message.action == "btnClick"){
chrome.tabs.create({url: "http://www.google.com", active:true});
setTimeout(function(){ delayed(); }, 3000);
}
});
function delayed(){
chrome.tabs.query({active:true}, queryCallback);
}
function queryCallback(arr){
var tabId = arr[0].id;
console.log("message shown 3 second after clicking button") // THIS IS WORKING
chrome.tabs.sendMessage(tabId, {action:"doSomething"}); // CONTENT SCRIPT DOESNT REACT TO THIS
}
function contentScriptCallback(any){
alert(any);
}
content_script.js:
chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) {
if( message.action == "doSomething"){
document.body.style.backgroundColor='#000000';
alert("do something");
}
});
Download all files in one ZIP here
如何让content_script.js响应消息并改变网页背景颜色?
【问题讨论】:
-
您是否在控制台中看到任何错误?
-
Google 页面使用
https安全协议,而不是您指定的http。 -
@wOxxOm 感谢您注意到我的错误!确实在我的 manifest.json 中更改 content_script 和 permisions URL 解决了这个问题!我已经用解决方案更新了问题。
-
@deshu,nonono,这在 stack* 网站上是错误的。请回滚编辑并将其作为答案发布,然后接受。
-
@wOxxOm 好的,对不起,我是新来的。我刚刚修好了。我会尽快将其标记为解决方案(两天后)。
标签: javascript google-chrome google-chrome-extension content-script