Chrome extension getUrl not working in injected file
No you cant, once you inject the script in a page, it cannot access chrome.extension.getURl
. But you can communicate between your injected script
and content script
. One of the methods is using custom events.
mainfest.json
:
{
"name": "Name",
"version": "0.1",
"description": "Name chrome extension",
"background": {
"persistent": false,
"scripts": ["js/background.js"]
},
"permissions": [
"tabs",
"https://*/*"
],
"content_scripts": [
{
"matches": ["https://mail.google.com/*"],
"js": ["js/content.js"],
"run_at": "document_end"
}
],
"web_accessible_resources": [
"js/injected.js",
"html/popup.html"
],
"manifest_version": 2
}
In your injected script
:
console.log("Ok injected file worked");
document.addEventListener('yourCustomEvent', function (e)
{
var url=e.detail;
console.log("received "+url);
});
In your content script
:
var s = document.createElement('script');
s.src = chrome.extension.getURL('js/injected.js');
(document.head || document.documentElement).appendChild(s);
s.onload = function(){
var url=chrome.runtime.getURL("html/popup.html");
var evt=document.createEvent("CustomEvent");
evt.initCustomEvent("yourCustomEvent", true, true, url);
document.dispatchEvent(evt);
};
You have to mention the file_path or file_names in the web_accessible_resources of extension manifest.
EG:
"web_accessible_resources":[
"styles/*",
"yourfilename.js"
]
After that you can have have the file in injected script by calling the method.
"chrome.extension.getURL('yourfilename.js')";