Chrome Extension Timed Redirection

三世轮回 提交于 2019-12-12 02:46:49

问题


What I'm trying to achieve is make a chrome extension run in the background, and every minute it'll redirect to google.com and then a minute later redirect to stackoverflow.com and so on continuously until the icon is clicked by the wrench icon where most of the extensions are.

However I only know on how to redirect a page using window.location.replace("http://google.com");

I'm still learning on how to develop chrome extensions, and just making some simple stuff for a learning process. I started learning from this tutorial, and tried a couple things out, and now I wanna figure out how to get something like this to work with it running in the background.


回答1:


You could also just write a content script that you would inject, but it's easy enough that I just stored it in a variable. I would recommend looking at the chrome.tab API, as Google does a very good job of documenting their API for developers.

In your background page:

var REDIRECTION_SCRIPT_A = "window.location.href='http://www.google.com'";
var REDIRECTION_SCRIPT_B = "window.location.href='http://bit.ly/m2TXqC'";
var toGoogle = true;
var intervalId;

chrome.browserAction.onClicked.addListener(function() {
  clearInterval(intervalId);
});

// Execute redirection script on current page
// Note that you can select any tab based on its ID by replacing
// null below
function annoyUser() {
  console.log("test");
  chrome.tabs.executeScript(null, {code:
    (toGoogle ? REDIRECTION_SCRIPT_A : REDIRECTION_SCRIPT_B) });
  toGoogle = !toGoogle;
}

// Do once a minute ad infinitum
intervalId = setInterval(annoyUser, 5000);

In your manifest.json:

{
  ...
  "permissions": ["http://*/*", "tabs"],
  ...
}



回答2:


Alternate solution (I am leaving url selection part out).

background.html:

var timer = setInterval(function() {
    chrome.tabs.getSelected(null, function(tab) {
        chrome.tabs.update(tab.id, {url: "http://google.com"});
    });
}, 60000);

//stop
chrome.browserAction.onClicked.addListener(function(){
    clearInterval(timer);
});


来源:https://stackoverflow.com/questions/6244740/chrome-extension-timed-redirection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!