I've just start out learning how to make extensions for google chrome. I have a very basic understanding so far, so I wanted to try something small.
Right now I am trying to get an image to append to a specific div on a specific page everytime that page loads. The extension loads properly but, the javascript code never seems to run and the image never gets loaded.
This is the manifest.json file I have so far:
{
"manifest_version": 2,
"name": "Icon Creator",
"description": "Creates a custom icon for page",
"version": "1.0",
"content_scripts": [
{
"matches": ["file:///home/tijko/documents/learning/javascript/test_page.html"],
"css": ["sample.css"],
"js":["trial.js"]
}
],
"icons": {"icon": "icon.jpg"},
"web_accessible_resources":["trial.js"]
}
and the javascript:
var test = function() {
custom_icon = document.createElement("img");
target = document.getElementById("location");
custom_icon.src = "icon.png";
target.appendChild(custom_icon);
}
test()
Use the onload event to load your code. Add a script tag as the last element of the page (last thing in the body element). This script will be executed after all other scripts have finished and after the body has been converted to a DOM tree.
Content scripts are files that run in the context of web pages. By using the standard Document Object Model (DOM), they are able to read details of the web pages the browser visits, make changes to them, and pass information to their parent extension.
Are you trying to load your own extension's icon.png
? Right now you are trying to load icon.png
on the domain and path of the local page. Instead, you should do:
custom_icon.src = chrome.runtime.getURL("icon.png");
to refer to your extension's icon.png
.
Also, you must list icon.png
in your web_accessible_resources
. Furthermore, you don't need to list trial.js
in your web_accessible_resources
(except for very specialized use cases).
Finally, you need to approve your extension for access to file://
pages by checking the appropriate box under your extension's listing in chrome://extensions
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With