I've researched this topic a ton but something isn't clicking. I'm trying to make a simple Chrome extension. The details aren't important, but basically when the user clicks on a certain button on a certain website, the page is redirected to a different URL. I've put in dummy URLs just for illustration. Here is my code:
manifest.json
{
"manifest_version": 2,
"name": "Blah",
"version": "1.0",
"description": "Blah blah",
"icons": { "16": "icon16.png",
"48": "icon48.png",
"128": "icon128.png" },
"content_scripts": [
{
"matches": ["*://url1.com/*"],
"js": ["contentscript.js"]
}
],
"web_accessible_resources": ["script.js"]
}
contentscript.js (found this on another Stack Overflow question, not totally sure how it works)
var s = document.createElement("script");
s.src = chrome.extension.getURL("script.js");
s.onload = function() {
this.remove();
};
(document.head || document.documentElement).appendChild(s);
script.js
document.getElementById("id1").addEventListener("click", redirect);
function redirect() {
console.log("Testing!"); // This works!
window.location.replace("url2.org");
}
The text is logged to the console when I click the appropriate button, so I know I'm doing something right. However, I'm guessing I'm not actually injecting the script into the page, and that's why my page isn't redirecting. Any help would be appreciated!
Here is an example:
script.js
// wait that page finished loading
window.addEventListener("load", function load(event){
// for the current tab, inject the "inject.js" file & execute it
chrome.tabs.executeScript(tab.ib, {
file: 'inject.js'
});
},false);
inject.js
// this is the code which will be injected into a given page...
document.getElementById("id1").addEventListener("click", redirect);
function redirect() {
console.log("Testing!"); // This works!
window.location.replace("url2.org");
}
Manifest.json
{
"name": "Inject",
"version": "0.0.1",
"manifest_version": 2,
"description": "Injecting stuff",
"content_scripts": [{
"matches": ["http://example.com/*"],
"js": ["script.js"]
}],
"permissions": [
"http://example.com/*",
"tabs"
]
}
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