Load HTML File in Chrome Plugin, The Easy Way

August 26th, 2014 — 2 min read

Load HTML File in Chrome Plugin, The Easy Way

Greetings. Today i am going to present a simple trick to load html file in chrome plugin. There are so many posts on this topic already still i assume you will like this. Let’s get started.

At first lets see the plugin structure.

/myplugin
    /css
    /images
    /js
    /background.js
    /manifest.json
    /plugin/
        /plugin.html
        /plugin.js

OK. Pretty simple.
Now you can write html code in your plugin.html. We need to add plugin.html in manifest.json so that chrome plugin allow it to load.
In manifest.json add this.

"web_accessible_resources": [
    "plugin/plugin.html"
]

Also we need to load plugin.js file which we can add in content_scripts js array

"content_scripts": [
    {
        matches: [
 
        ],
        css : [],
        js : ["jquery.js","plugin/plugin.js"]
    }
]

We can now proceed to see how plugin.js will load the html file. For this lets make a simple function in plugin.js

function loadPluginTemplate(path){
    var xmlHttp = null;
    xmlHttp = new XMLHttpRequest();
    xmlHttp.open( "GET", chrome.extension.getURL(path), false );
    xmlHttp.send( null );
    return xmlHttp.responseText
}
/* Plugin Template */
var pluginTemplate = loadPluginTemplate("plugin/plugin.html")

this will first load the file using chrome getURL function then with our request it will send the response and we can easily get the responseText and bind it to the body.

$('body').append(pluginTemplate);

And that’s all.

Hope it is very easy and useful.