【发布时间】:2018-09-04 08:57:59
【问题描述】:
谷歌浏览器扩展开发的新手。我希望写一个小扩展,根据页面内容自动刷新页面。
我遇到了无法将消息传回的问题
这是我的全部代码:
background.js
var started = false;
var tabs = new Array();
chrome.tabs.onRemoved.addListener(function(tabID, removeInfo) {
for (var i = 0; i < tabs.length; i++) {
if (tabs[i].tabId == tabID) {
tabs[i].started = false;
clearTimeout(tabs[i].timer);
tabs.splice(i)
break;
}
}})
chrome.browserAction.onClicked.addListener(function(tab) {
var t = new Object();
chrome.tabs.create({
'url': 'http://localhost/test'
}, function(tab) {
t.tabId = tab.id
t.started = true;
reload(t.tabId)
})
tabs.push(t)
});
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
if (request.type == "reload") {
for (var i = 0; i < tabs.length; i++) {
if (tabs[i].tabId == sender.tab.id) {
reload(tabs[i].tabId)
break;
}
}
} else if (request.type == "ready") {
for (var i = 0; i < tabs.length; i++) {
if (tabs[i].tabId == sender.tab.id) {
tabs[i].started = false;
clearTimeout(tabs[i].timer)
break;
}
}
}
});
function sleep(mseconds) {
var timer = new Date();
var time = timer.getTime();
do
timer = new Date();
while ((timer.getTime() - time) < (mseconds));
}
var CTimer;
function timer(tabid) {
for (var i = 0; i < tabs.length; i++) {
if (tabs[i].tabId == tabid) {
if (tabs[i].started) {
if (tabs[i].timer != undefined) {
clearTimeout(tabs[i].timer);
}
tabs[i].timer = setTimeout(function() {
reload(tabid)
console.log("Delay detected : Timer reload")
}, 5000);
}
break;
}
}
}
function reload(tabid) {
try {
chrome.tabs.update(tabid, {
'url': 'http://localhost/test'
}, function() {
sleep(750)
chrome.tabs.executeScript(tabid, {
file: "reload.js"
});
})
timer(tabid)
} catch (e) {
reload()
}
}
这里是reload.js
$(function () {
if (location.href.match("http://localhost/test")) {
if ($("body").html().match("Server Busy")) {
chrome.tabs.query({
active: true,
currentWindow: true
}, function (tabs) {
chrome.tabs.sendMessage(tabs[0].id, {
type: "reload"
}, function (response) {
// console.log(response.farewell);
});
});
} else {
chrome.tabs.query({
active: true,
currentWindow: true
}, function (tabs) {
chrome.tabs.sendMessage(tabs[0].id, {
type: "ready"
}, function (response) {
// console.log(response.farewell);
});
});
}
}
});
这里是manifest.json(更新)
{
"background": {
"scripts": [ "background.js" ]
},
"browser_action": {
"default_icon": "icon.png"
},
"content_scripts": [ {
"js": [ "jquery-1.8.2.min.js","reload.js" ],
"matches": [ "http://localhost/" ]
} ],
"description": "Avoid Server Busy.",
"icons": {
"128": "icon.png",
"16": "icon.png",
"48": "icon.png"
},
"manifest_version": 2,
"name": "Reload",
"permissions": [ "tabs", "http://localhost/", "background" ],
}
当我执行一些调试时,似乎无法将任何消息传递给onRuntime.addListener。
我的目的是继续重新加载网页,直到页面不忙,但脚本现在继续加载页面并且不会停止。
我的代码有什么问题吗?
【问题讨论】:
-
你能添加你的清单,特别是权限和(如果有的话)内容脚本吗?
-
我只是用完整的编码更新我的帖子
-
"http://localhost/test"不是有效权限;我怀疑这是问题所在。您必须删除路径:"http://localhost/" -
@Xan,不走运,脚本仍在不断刷新页面。
标签: javascript google-chrome google-chrome-extension google-chrome-app