1

有没有办法使用 javascript 中的 replace() 替换页面的 DOM 内部

在我要替换的源代码中:

<div class="topbar">Bookmark Us</div>

<div class="topbar"><span class="larger-font">Bookmark Us</span></div>

当 Google Chrome 扩展程序位于URL 的匹配网站上时,它将执行上述操作。

任何匹配的页面:

http://www.domain.com/support.php

谢谢。

4

2 回答 2

2

不知道 Chrome 是如何触发其扩展的,但我可以告诉你有关页面内容操作的信息。

topbar用纯 JavaScript包装 div 的所有子内容:

var topbars= document.getElementsByClassName('topbar');
for (var i= topbars.length; i-->0;) {
    var span= document.createElement('span');
    span.className= 'larger-font';
    while (topbars[i].firstChild)
        span.appendChild(topbars[i].firstChild);
    topbars[i].appendChild(span);
}

(getElementsByClassName 是一个相对较新的 API,但 Chrome 3 支持它。对于每个匹配的元素,将其所有子元素移动到一个新的 span 元素中,并将该 span 放入 div 中。)

或者使用 jQuery,如果您不介意将一个很棒的大型框架拖入:

$('.topbar').each(function() {
    $(this).contents().wrapAll('<span class="larger-font"></span>');
});

虽然您可以将 HTML 作为字符串进行操作,但可以使用以下内容:

for (var i= topbars.length; i-->0;)
    topbars[i].innerHTML= '<span class="larger-font">'+topbars[i].innerHTML+'</span>';

通常应该避免这种情况,因为您将序列化和重新解析 div 的整个节点内容,在此过程中会破坏任何不可序列化的内容,如 JavaScript 引用、事件侦听器和表单字段值。

于 2010-05-06T20:46:06.170 回答
1

你想要的是一个内容脚本。将其设置为在清单中所需的 URL 上触发,然后使用 Bobince 的代码实际应用操作。

于 2010-05-07T01:52:11.213 回答