1

I'm writing a script that should rewrite all links on a page from http:// to https:// - it must be done client-side, it's run in a page I don't control.

Execution environment: recent Chrome only, as this is a Chrome extension's injected script, so no cross-browser worries. Injection happens at document_start (i.e. before DOM starts loading).

My first try was to watch for DOMContentLoaded and then iterate over document.links:

document.addEventListener("DOMContentLoaded", rewriteHTTPS, false);

function rewriteHTTPS() {
    var links = document.links;
    for(var i in links){
        links[i].href = links[i].href.replace(/http:/, "https:");
    }
}

Unfortunately, I realized that the page is dynamic, so more links are added after this event is fired.

So, the question is: What's the best way to capture all new and modified links in a page with dynamic DOM?

Xan
  • 74,770
  • 16
  • 179
  • 206
  • Is there a *really* good reason as to why this isn't being done on the server side? What if your user just turns off Javascript? – Demian Brecht Sep 08 '11 at 07:28
  • I'm writing a browser extension to interact with a foreign site. Obviously, if my users use it, they have javascript enabled. – Xan Sep 08 '11 at 07:31

1 Answers1

0

You might want to look into listening for the DOMNodeInserted event, even thought its support in IE seems to be spotty. The other answers to that question may also be helpful.

Community
  • 1
  • 1
David Wolever
  • 148,955
  • 89
  • 346
  • 502
  • 1
    IE is not an issue; it's a Chrome-only question and it states so. As for DOMNodeInserted: it's not triggered for ALL new DOM nodes, it seems like it fires once for each subtree insertion. Looks like I have to iterate over each such subtree.. – Xan Sep 08 '11 at 07:56
  • Yes, iterating over `event.target.getElementsByTagName('a')` for `DOMNodeInserted` did the trick for me. Thanks. – Xan Sep 08 '11 at 08:13