开发者

Chrome Extension Timed Redirection

开发者 https://www.devze.com 2023-03-10 18:58 出处:网络
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

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.


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);
});


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"],
  ...
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号