Inject HTML into a page from a content script

后端 未结 5 1656
南旧
南旧 2020-11-28 23:35

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

相关标签:
5条回答
  • 2020-11-29 00:18

    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

    0 讨论(0)
  • 2020-11-29 00:21

    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);
    
    0 讨论(0)
  • 2020-11-29 00:25

    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.

    0 讨论(0)
  • 2020-11-29 00:26

    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
        });
    
    0 讨论(0)
  • 2020-11-29 00:27

    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);
    
    0 讨论(0)
提交回复
热议问题