I have code background js:
chrome.contextMenus.onClicked.addListener(function(tab) {
chrome.tabs.executeScript(null, {
code: "setInterval(function(){alert('test')}, 2000)"
});
});
var id = chrome.contextMenus.create({
"title": "Auto Refresh",
"contexts": ["page"]
});
It works, each 2 seconds it have a alert box “test”;
But I replace alert(‘test’) by location.reload:
chrome.contextMenus.onClicked.addListener(function(tab) {
chrome.tabs.executeScript(null, {
code: "setInterval(function(){location.reload()}, 2000)"
});
});
var id = chrome.contextMenus.create({
"title": "Auto Refresh",
"contexts": ["page"]
});
It only have 1 refresh for the first time and don’t continue to refresh. Please help me, thanks
When a page is refreshed, the
setIntervalhandle will be gone, so it will not work as you expected.A solution is to do
setIntervalinside your extension:As I acknowledge that you want to refresh only the current page, I added
tab.indexas the first parameter tochrome.tabs.executeScriptso that only the current page is being refreshed.Beware that the user may choose the option more than once, so you may need to check if it is the case or remove the context menu item. Also when the tab is closed you will need to call
clearInterval, or else you will cause a lot of problems. These are left for you to practice.