在动态页面上使用 javascript 重写链接
我正在编写一个脚本,该脚本应该将页面上的所有链接从 http:// 重写为 https:// - 它必须在客户端完成,它在我无法控制的页面中运行。 >
执行环境:仅限最近的Chrome,因为这是Chrome扩展的注入脚本,所以没有跨浏览器的担忧。注入发生在 document_start
处(即在 DOM 开始加载之前)。
我的第一次尝试是监视 DOMContentLoaded,然后迭代 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:");
}
}
不幸的是,我意识到页面是动态的,因此在触发此事件后会添加更多链接。
因此,问题是:使用动态 DOM 捕获页面中所有新链接和修改链接的最佳方法是什么?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可能想考虑监听 DOMNodeInserted 事件,即使它在 IE 中的支持似乎参差不齐。该问题的其他答案也可能有帮助。
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.