2010-05-06 612 views
1

有沒有一種方法來使用JavaScript的谷歌Chrome擴展

在源代碼中的替換()我要替換頁面的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 

感謝。

回答

2

不知道Chrome如何觸發其擴展程序,但我可以告訴您有關頁面內容操作的信息。

包裝一個topbar div的所有子內容在普通的JavaScript:

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元素,並把跨越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引用,事件偵聽器和表單字段值等任何不可序列化的內容。

+0

+1是正確的答案,並且是for循環中的'i - > 0'位。這顯然很簡單,並且它的建議「我」達到了'0',但我從來沒有見過或想過以這種方式使用'for'條件子句。 – 2010-05-07 01:51:54

1

你想要的是一個content script。將其設置爲在清單中所需的URL上觸發,然後使用Bobince的代碼實際應用操作。