2016-08-11 95 views
0

我創建了一個Chrome擴展,並把我的內容腳本中下面的代碼刪除一些在谷歌搜索頁面的內容:如何在內容腳本中修改Google搜索結果頁面?

window.onload = function() { 
    $('.g').remove(); // This is the container for the search results in Google 
} 

即使我看到它的開發工作它不工作當我手動執行它的控制檯。

+0

你的'manifest.json'是什麼樣的?你有沒有注入jQuery? 「除非我打開了Chrome開發者控制檯」,你的意思是在F12工具中執行上面的代碼嗎?請提供更多細節。 –

回答

2

Google頁面會動態加載內容,因此您必須使用MutationObserver或setTimer回調來監視元素,或者 - 優選地,查找頁面用來發送其更新的事件。許多網站使用message事件,所以讓我們來鉤住它。

content.js:

// process current DOM, most probably nothing useful at this point 
onGoogleSearchUpdated(); 

// listen to "sr" signal emitted by Google search page 
window.addEventListener('message', function(e) { 
    console.log(e.data, e); 
    if (typeof e.data === 'object' && e.data.type === 'sr') { 
     onGoogleSearchUpdated(); 
    } 
}); 

function onGoogleSearchUpdated() { 
    console.log('Removed:', $('.g').remove()); 
} 

爲了檢測動態加載網頁的確切信號名稱,打開devtools(F12)控制檯並運行window.addEventListener('message', console.log),然後在查詢輸入框執行搜索,看看控制檯中出現的事件,並嘗試找到哪些對你有用。