因此,我的主内容脚本在我刷新页面时运行,但是当我单击网页的新页面时,它不会再次运行;只在我刷新页面时运行一次。我希望它在每次页面更改或url更改时重新运行。主内容脚本中的主函数称为"runExtension()“
这是我的background.js
chrome.tabs.onUpdated.addListener( function (tabId, changeInfo, tab) {
if (changeInfo.status == 'complete') {
alert("LOADED");
setTimeout(runExtension, 1000);
}
})
这是我的manifest.json
{
"manifest_version": 2,
"name": "RateMyBull",
"description": "View professor ratings from RateMyProfessor when signing up for classes on the USF schedule planner",
"version": "1.0",
"permissions": ["https://usf.collegescheduler.com/*"],
"background": {
"scripts": ["background.js"]
},
"content_scripts": [
{
"matches": ["https://usf.collegescheduler.com/*"],
"js": ["RateMyBull.js", "jquery-3.3.1.min.js", "jquery-3.3.1.js"],
"run_at": "document_idle",
}
]
}
下面是主脚本
setTimeout(runExtension, 1000);
function runExtension(){
var tableElementNode = document.querySelectorAll(".section-detail-grid.table-bordered-wrap>tbody>tr>td>div");
console.log(tableElementNode);
for (var i = 0; i < tableElementNode.length; i++) {
if(tableElementNode[i].children.length < 1 && tableElementNode[i].innerText != "Not Assigned") {
tableElementNode[i].className = "professor";
}
}
var professorsArray = [];
var professorElementNode = document.querySelectorAll(".professor");
for (var i = 0; i < professorElementNode.length; i++) {
professorElementNode[i].id = i;
var professorName = professorElementNode[i].innerText;
professorName = professorName.trim();
professorName = professorName.replace(/,/g, "");
professorName = professorName.split([' ']);
var firstName = professorName[1];
var lastName = professorName[0];
var professorObj = {
first: firstName,
last: lastName,
ID: i
};
professorsArray[i] = professorObj;
console.log(professorsArray[i].first);
}
alert("this just ran");
}
chrome.runtime.onMessage.addListener(function(msg, sender, sendResponse) {
if (msg === 'url-update') {
alert("TEST");
}
});
发布于 2018-08-15 06:50:37
像RateMyBull.js
这样的Content scripts
在一个完全独立于后台页面的环境中运行(在but somewhat isolated from上,一个网页)。
如果希望背景页使内容脚本中的代码运行,请使用message passing。
在您的情况下,尝试将background.js
更改为:
chrome.tabs.onUpdated.addListener( function (tabId, changeInfo, tab) {
if (changeInfo.status == 'complete') {
chrome.tabs.sendMessage(tab.id, {type: "runExtension"});
}
})
并将监听程序添加到RateMyBull.js
内容脚本:
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
if (request.type === "runExtension")
runExtension();
});
当然,网页有很多“改变”的方式。有关检测各种类型的更改的更多信息,请参阅评论中引用的the question和相关答案wOxxOm。
https://stackoverflow.com/questions/51846769
复制相似问题