I am building a Chrome Extension and I have a requirement to overlay a blob of html on top of a few websites. At the moment I am using a JQuery .Get
to pull the html from my server. In order to improve performance I am wondering if it is possible to include the html as a file in the extension directory and access the source directly from there? Does anyone know if this is possible?
UPDATE
Rob's suggestion does the job (see accepted answer). The only additional step is to register the file in the manifest under web_accessible_resources.
{ ... "web_accessible_resources": [ "myimportfile1.html", "myimportfile2.html" ], ... }
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.
This extension allows you to write, save, and execute javascript into web pages. You can save scripts to be run globally (on any page), on a specific domain, on a specific page, or via a "URL contains" string.
Yes, that's possible. Use chrome.runtime.getURL
to get an absolute URL for the resource. For example:
Step 1 (standard JavaScript):
fetch(chrome.runtime.getURL('/template.html')).then(r => r.text()).then(html => { document.body.insertAdjacentHTML('beforeend', html); // not using innerHTML as it would break js event listeners of the page });
Step 1 (jQuery):
$.get(chrome.runtime.getURL('/template.html'), function(data) { $(data).appendTo('body'); // Or if you're using jQuery 1.8+: // $($.parseHTML(data)).appendTo('body'); });
Step 2:
Register the resource in the manifest.json under web_accessible_resources:
"web_accessible_resources": [ "template.html", "foo.jpg" ]
Another way of doing it is to use new Fetch API:
If the file's name is modal.html
- update manifest.json
accordingly
"web_accessible_resources": [ "modal.html", ],
and inject it like this:
fetch(chrome.runtime.getURL('/modal.html')) .then(response => response.text()) .then(data => { document.getElementById('inject-container').innerHTML = data; // other code // eg update injected elements, // add event listeners or logic to connect to other parts of the app }).catch(err => { // handle error });
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