user2086454
user2086454

Reputation: 73

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.

Upvotes: 7

Views: 3568

Answers (2)

Hank X
Hank X

Reputation: 2044

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);

Upvotes: 5

Sudarshan
Sudarshan

Reputation: 18534

Add permissions of the URL(S) you target to the manifest file

{
 ---
    "permissions": [
        "https: //www.google.co.in/*"
    ]
 ---
}

Reference

Upvotes: 0

Related Questions