Ashar Rai Mujeeb
Ashar Rai Mujeeb

Reputation: 41

Injecting Redirect JS in Chrome extension. Fail! :(

I'm trying to generate an extension that keeps my brother of facebook. So I decided i'll redirect all facebook links to google for starters.

This is how i went about it.

My manifest.json file :

{   

  "name": "FBRehab"    
  "version": "1.0",    
  "description": "Redirect FB",    
  "permissions": [    
   "tabs", "http://www.facebook.com/*", "https://www.facebook.com/*"    
],     
  "browser_action": {    
   "default_icon": "icon.png",    
"background_page": "background.html"    
      },
  ]
}

My background.html :

<html>
<head>
<script>
  chrome.tabs.executeScript(null, { file: "jquery.js" }, function() {
   chrome.tabs.executeScript(null, { file: "try.js" });
});
</script>
</head>

and try.js

<head>
<script language="JavaScript">
var time = null
function move() {
window.location = 'www.google.com'
}
</script>
</head>

Yet, it does not redirect. I've tried directly injecting the try.js using content scripts too.

Please help me.

Thanking you.

Ashar :)

Upvotes: 1

Views: 744

Answers (3)

Mohamed Mansour
Mohamed Mansour

Reputation: 40199

Remember a Background Page runs exactly once in Chrome, it is a single long running script that runs exactly once.

Basically what your code does now is that once your browser loads, it will inject jquery and try Content Scripts to the current tab. You have no tabs that are currently loaded (which it will fail unless you have it auto load a tab). Then it will not do anything anymore because the Background Page runs exactly once!

What you need to do instead is use a Content Script which should be defined as follows:

// Only execute in the top window, we don't want to inject the iframes.
if (window == top) {
  window.location = 'www.google.com'
}

In your manifest, you will have the following:

{
  "name": "No more Facebook extension",
  ...
  "content_scripts": [
    {
      "matches": ["http://*/*", "https://*/*"],
      "js": ["redirect.js"]
    }
  ],
  ...
}

Upvotes: 2

Andrew M
Andrew M

Reputation: 4288

Do you ever call move()? Doesn't look like it to me, but I've never developed a Chrome extension before... so I'm not sure if it is ever called automatically.

Upvotes: 0

Roman Nurik
Roman Nurik

Reputation: 29745

I think you want to use a content script instead of a background page. You can specify that your content script should only run on specific web pages.

Upvotes: 1

Related Questions