找到并替换字符串 [英] find and replace string

查看:96
本文介绍了找到并替换字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以查看页面的源代码,查找某个部分并在页面加载之前用其他内容替换它?我想使用JavaScript完成此操作,以便我可以在Chrome扩展程序中使用它。如下所示:

Is it possible to look at a page's source code, find a certain part and replace it with something else before the page loads? I would like to accomplish this using JavaScript so that I can use it in a Chrome extension. So something like this:

查找google.com

Find the google.com

<script type="text/javascript">
var URLgo = "http://google.com";
</script>

替换为yahoo.com

Replace with yahoo.com

<script type="text/javascript">
var URLgo = "http://yahoo.com";
</script>


推荐答案

<script type="text/javascript">
function replaceScript() {
    var toReplace = 'http://google.com';
    var replaceWith ='http://yahoo.com';
    document.body.innerHTML = document.body.innerHTML.replace(toReplace, replaceWith);
}
</script>

然后在body标签中初始化以在页面加载时执行。

Then initialise in the body tag to do on page load.

<body onload="replaceScript();">

应该可以正常工作并替换html正文代码中的所有实例。

Should work fine and replace all instances in html body code.

如果它位于ID为external_iframe的iframe中,那么您可以将document.body.innerHTML修改为:

If it is in an iframe with id "external_iframe" then you would modify document.body.innerHTML to be:

window.frames['external_iframe'].document.body.innerHTML

虽然我是不相信你可以将它用于外部网站。

Although I'm not convinced you can use it for an external site.

这里似乎是一些信息: Javascript iframe innerHTML

Seems to be some info here: Javascript Iframe innerHTML

这篇关于找到并替换字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆