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
Yes, that's possible. Use chrome.extension.getURL to get an absolute URL for the resource. For example:
Step 1:
$.get(chrome.extension.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 under web_accessible_resources: See https://developer.chrome.com/extensions/manifest#web_accessible_resources (Provided by @QFDev)
Update (10/04/2020)
chrome.extension.getURL is deprecated since Chrome 58. Use this instead chrome.runtime.getURL
I use this code. It's only 3 lines of code and you don't need any jquery's garbage.
var iframe = document.createElement ('iframe');
iframe.src = chrome.extension.getURL ('iframe.html');
document.body.appendChild (iframe);
This is my approach:
var xmlHttp = null;
xmlHttp = new XMLHttpRequest();
xmlHttp.open( "GET", chrome.extension.getURL ("src/inject/inject.html"), false );
xmlHttp.send( null );
var inject = document.createElement("div");
inject.innerHTML = xmlHttp.responseText
document.body.insertBefore (inject, document.body.firstChild);
Without jQuery etc.
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.extension.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're using Angular in your Chrome extension, you can make use of ng-include
var injectedContent = document.createElement("div");
injectedContent.setAttribute("ng-include", "");
//ng-include src value must be wrapped in single quotes
injectedContent.setAttribute("src", "'" + chrome.extension.getURL("template.html") + "'");
existingElement.appendChild(injectedContent);