Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chrome Extension - Simple Content Script for running js on any page

How can I write a simple Chrome Extension content script that will execute JavaScript (for example alert("hello");) on every page load?

So when I navigate to a page or reload a page, the JavaScript should run.

This is my manifest.json file so far:

{     "name": "Highlight some phrases",     "description": "Hightlight some pre defined text from websql database after page loads",     "version": "0.1",     "permissions": [         "tabs","<all_urls>"     ],     "browser_action": {         "default_icon": "icon.png",         "default_popup": "popup.html"     },      "content_scripts": [         {         "matches": [             "http://*/*",             "https://*/*"         ],         "js": ["content.js"]         }     ],      "background": {         "page": "background.html"      },      "manifest_version": 2 } 
like image 742
user2876479 Avatar asked Oct 13 '13 16:10

user2876479


1 Answers

If all you need is to alert hello on every page load or reload, below is a simple demo: Manifest.json:

{     "name": "Highlight some phrases",     "description": "Hightlight some pre defined text after page loads",     "version": "0.1",     "permissions": [         "tabs","<all_urls>"     ],     "browser_action": {         "default_icon": "icon.png"     },     "content_scripts": [         {         "matches": [             "http://*/*",             "https://*/*"             ],         "js": ["content.js"],         "run_at": "document_end"    // Pay attention to this line         }     ],      "manifest_version": 2 } 

and content.js:

// alert("hello"); document.body.style.background = 'yellow'; 

Yes, that's enough.
And of course, don't forget to add an icon named icon.png at the same directory with these two files, then test it in Google Chrome.

like image 156
yakiang Avatar answered Oct 17 '22 20:10

yakiang