Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inject HTML into a page from a content script

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"     ],     ... } 
like image 443
QFDev Avatar asked May 02 '13 09:05

QFDev


People also ask

What is chrome content script?

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.

What is inject JS in Chrome?

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.


2 Answers

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"   ] 
like image 60
Rob W Avatar answered Sep 20 '22 21:09

Rob W


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         }); 
like image 23
ego Avatar answered Sep 19 '22 21:09

ego