Rewriting links with javascript on a dynamic page
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?
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.
精彩评论