简体   繁体   中英

Redirecting on page load with a Chrome extension

I have a Chrome extension that I'm working on that redirects users of a non-HTTPS site to the HTTPS version automatically.

However, the current problem with this is that the user must activate this redirection manually.

This would be an easy feat to accomplish using content_scripts in manifest.json, however, according to the Chrome documentation, content scripts "Cannot...Use chrome.* APIs (except for parts of chrome.extension)".

So, here's the manifest file for my extension:

{
  "name": "SSL Redirect",
  "version": "1.0",
  "manifest_version": 2,
  "description": "Redirects plain HTTP domain.com to the encrypted, HTTPS secured version.",

  "permissions": [ "tabs", "http://*/*", "https://*/*" ],

  "background" : {
  "page": "body.html"
  },

"browser_action": {
          "default_icon": "icon.png"
},
  "content_scripts": [
    {
      "matches": ["http://www.domain.com/*"],
      "js": ["redirect.js"]
    }
  ]
}

And here's the js:

var domain = /domain.com\//;
var ssldomain = "ssl.domain.com\/";

function updateUrl(tab){

  if(tab.url.match(ssldomain)) {
    alert("You're already using the SSL site. :)")
    throw { name: 'Error', message: 'Stopped running, already in SSL mode.' };
  }

  if(tab.url.match(domain)) {
    var newurl = tab.url.replace(domain, ssldomain);
    newurl = newurl.replace(/^http:/, 'https:');
    newurl = newurl.replace("www.", "");
    chrome.tabs.update(tab.id, {url: newurl});
  }

  if(!(tab.url.match(domain))) {
    alert("This extension only works on domain.com.")
    throw { name: 'Error', message: 'Stopped running, not on domain.com.' };
  }


  }

chrome.browserAction.onClicked.addListener(function(tab) {updateUrl(tab);});

My ultimate goal is to get this to run automatically on any page matching domain.com, without user interaction.

I'm a little stuck. Any ideas?

1) From within the content script, you can use standard methods of changing URL, since you are running in the context of the page. Ie:

var oldUrl = location.href;
/* construct newUrl */
if(newUrl != oldUrl) location.replace(newUrl);

2) Scrap what you've written already and read about chrome.webRequest API . This will achieve what you need without a content script or tab manipulation.

Example:

 chrome.webRequest.onBeforeRequest.addListener(
   function(details) {
     var url = details.url.replace(/^http/, "https");
     return {redirectUrl: url};
   },
   {urls: ["http://domain.com/*"]},
   ["blocking"]
 );

Note: you need host permissions for "*://domain.com/*"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM