Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to modify all links on page with chrome extension?

I'm teaching myself how to write Chrome extensions, but I'm having trouble getting even the basic functionality up and running.

I'm trying to write an extension that modifies all links on a given page. As a proof of concept, I'm trying to fix it so that all the links on a google.ca results page point instead to www.gooogle.cn

Here's my manifest.json:

"name": "Google Link Fixer",
  "version": "0.1",
  "permissions": ["*://www.google.*/*"],

  "content_scripts": [
    {
      "matches": ["*://www.google.*/*"],
      "js": ["jquery.js", "content_script.js"]
    }
  ],
  "manifest_version": 2
}

Here's the javascript in content_script.js (note that jquery.js is in the same directory):

$(document).ready(function(){
$("a[href^='https://www.google.ca']")
   .each(function()
   { 
      this.href = this.href.replace(/^https:\/\/www\.google\.ca/, 
         "https://www.google.cn");
   });
});

And ... nothing. I can see in the developer tools that the extension is being loaded, and the code is there under Content Scripts, but I'm not seeing the expected results. Any help is appreciated.

like image 491
Merjit Avatar asked Dec 30 '25 21:12

Merjit


1 Answers

I wish I could mark the answer that @charlietfl gave as the correct one. It got me on the right track.

There were two problems with my script:

  1. The Google search result page I was using as a proof of concept used relative links, not absolute ones, so my replace function was (correctly) not finding the regex pattern /^https:\/\/www\.google\.ca/. Lesson: don't expect a 'simple' page served by Google to have simple HTML.

  2. From what I can tell, Google creates at least some of its links dynamically — and this pattern is a common one on other sites as well. I rewrote the script inside a dedicated click handler, and that's what got me on the right track. Lesson: think carefully about what you're trying to accomplish. I wasn't trying to change all the links on the page; I wanted to redirect where certain links pointed. Making kind of behavior modification was more more efficient -- and much easier to accomplish -- on a link-click level then on an all-page level.

The code I used was:

$(document).on("click", "a", function(){
    var link_target = $(this).attr('href');
    var converted_url = link_target.replace(/SOME_REGEX/, REPLACEMENT_TEXT);
    $(this).attr('href', converted_url);
});
like image 99
Merjit Avatar answered Jan 01 '26 11:01

Merjit



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!