The goal is to setup a Chrome extension that will, on every page, inject and run your JavaScript (which in this case, will make every page's background red).
- First, setup a directory and create some empty text files named "onLoad.js", "manifest.json", and "script.js".
- The manifest.json file is the configuration for your chrome extension. The following manifest is setup to load your script, "onLoad.js", on all pages. The injected script is "script.js", and it is added to "web_accessible_resources" so that it's allowed to be used. Finally, make sure to use manifest_version 2, which is the latest version (1 is deprecated).This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
{ "name": "MyFirstExtension", "description": "An extension that injects some javascript on every page", "version": "2.0", "permissions": [ ], "content_scripts": [ { "matches": ["<all_urls>"], "js": ["onLoad.js"] } ], "manifest_version": 2, "web_accessible_resources": ["script.js"] } - onLoad.js is loaded on every page, but unfortunately it lives in a separate area than the actual page. We want to actually inject, or embed, script right into web page. That way we can directly access elements and have the injected script behave as if it is a native part of the page. We do this by telling onLoad.js to find and insert our JavaScript file right into the current page on every page load.This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
// Inject script on every page load var script = document.createElement('script'); script.src = chrome.extension.getURL('script.js'); document.body.appendChild(script); - We're almost done, all that's left is to define our script and load the extension into Chrome. For now we'll do something simple; we will change the background of every page to red.This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
document.body.style.backgroundColor="red"; - Finally, lets install and test this extension. Follow the following steps.
- In Chrome, go to Settings->Extensions
- Check the "Developer mode" checkbox
- Click "Load unpacked extension..."
- Select your extension's folder and press OK
- After you are done testing, to disable, either uncheck the "Enabled" checkbox or click the trash can to permanently remove it
- Now that the extension is loaded, go to google.com and see the background change to red. Good job!
No comments:
Post a Comment