我正在制作此Chrome扩展程序,如果已在另一个标签页中打开,则会突出显示Google搜索中的链接。目前,我可以将已经从background.js打开的选项卡添加到content.js,但是,从谷歌搜索获取链接不能很好地工作。这是我的3个脚本(因为我一直在努力解决问题,所以它们可能会有点滑稽。
的manifest.json
{
"manifest_version": 2,
"name": "Tab Highlighter",
"description": "Highlight links in a Google Search if they are already open in another tab",
"version": "1.0",
"content_scripts":[
{
"matches": [ "http://www.google.com/*", "https://www.google.com/*" ],
"js": [ "content.js" ]
}
],
"background": {
"persistent": false,
"scripts": ["background.js"]
},
"permissions":[ "tabs" ]
}
background.js 我不认为这与此有关
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
if(request.data === "getTabs"){
var fourmTabs = new Array();
chrome.tabs.query({},
function(t) {
var links = document.getElementsByTagName("a");
console.log("There are ", links.length , " links on the page.");
for(var k = 0; k < links.length; k++) {
console.log(links[k].innerHTML);
}
for (var i = 0; i < t.length; i++) {
var temp = t[i].url;
var fin = temp.replace(/.*?:\/\//g, "");
if(fin.substr(-1) == '/') {
fin = fin.substr(0, fin.length - 1);
}
fourmTabs[i] = fin;
}
// Moved code inside the callback handler
for (var i = 0; i < fourmTabs.length; i++) {
if (fourmTabs[i] != null) {
//console.log(fourmTabs[i]);
}
else {
console.log("??" + i);
}
}
if(!fourmTabs) {
console.log("Tabs could not be generated!!");
}
else {
for(i = 0; i < fourmTabs.length; i++) {
console.log("fourmtabs is here: ", fourmTabs[i]);
}
}
//setTimeout(function(){a},4000);
sendResponse({data: fourmTabs});
}
);
//sendResponse({});
return true;
}
});
content.js
window.addEventListener ("load",
function() {
chrome.runtime.sendMessage({data: "getTabs"}, function(response) {
console.log("Scanning page and comparing open tabs.");
var tabs = response.data;
if(!tabs) {
console.log("No Tabs could be found!! Most likely an error.");
}
else {
var links = document.querySelectorAll("a");
if(links.length == 0) {
console.log('query found nothing.');
}
for(var i = 0; i < links.length; i++) {
var link = links[i].href.replace(/.*?:\/\//g, "");
if(link.substr(-1) == '/') {
link = link.substr(0, link.length - 1);
}
console.log("found link: ", link);
var real_href = links[i];
//console.log("real_href: ", real_href);
if(link) {
for(var j = 0; j < tabs.length; j++) {
if(link == tabs[j]) {
console.log("duplicate found: ", link);
console.log("real_href dup: ", real_href);
real_href.style.background = "#00FFFB";
}
}
}
}
console.log("End comparing.");
}
});
});
目前它将获取所有Google锚标记,但不是实际的搜索标记。我已尝试对content.js进行多项更改以尝试获取它们,但成功似乎非常随机。我认为它主要基于页面的加载方式。我认为在开始时使用window.addEventListener
会等到页面的内容完全加载,然后再调用background.js然后获取页面的链接。 **我在清单设置为document_end的content_scripts中确实有ran_at选项,但它没有任何帮助,因此我将其删除,认为window.addEventListener将接管。
大多数所有链接都在<h3>
标记中,如果我查询这些链接结果为空。任何帮助表示赞赏。如果您需要更多信息,请与我们联系。 This is a link上一个我问过的问题得到了回答,但更多的是从background.js向content.js发送消息。
我尝试this answer提出问题,但正如我所说,它似乎没有帮助。