Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use Chrome Extension to Modify Google Search Result Page

I wanna make a Chrome extension to modify Google search result page. I know I can use content script to do this because it has the ability to do this. But unfortunately it fails. I wrote the code

$('h3.r').append('<b>a</b>')

or something else related to DOM operations they all failed. But if I just wrote

alert('aa')

or

document.body.style.backgroundColor='green'

, it works. Why? By the way, I want to have a debug but when I open the development tools I can not find my extension content script. I can see other extensions' content scripts.

like image 604
user2086454 Avatar asked Mar 01 '13 02:03

user2086454


1 Answers

Did you add jQuery to your content_scripts in manifest?

If you use jQuery, you must write manifest.json like this:

 "content_scripts":[
        {
            "matches":["http://www.google.com/*"],
            "js":["jquery-1.9.1.min.js", "contentscripts.js"]
        }
]

OK, after reading the page source of Google search result page I think I know what the problem is:

Google loads search result with AJAX, so, when you change query words and search again, the page DOES NOT refresh, that's why you can not get any DOM elements in the search results.

That means you have to add an event listener for DOMNodeInserted.

Code is like this:

function findH3(){
  $('h3.r').append('<b>a</b>')

}

searchResultArea.addEventListener('DOMNodeInserted', findH3);
like image 169
Hank X Avatar answered Oct 02 '22 03:10

Hank X