Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Render Mustache.js templates in a Chrome extension

I want to inject some HTML into some websites with a Chrome extension, and it would be much nicer to use a template system like Mustache.js to do it. I can't figure out how to access the content of the template file, though. An example of what I'm trying to do:

content_script.js

var image = chrome.extension.getURL('logo.jpg');
var tb = Mustache.to_html(
    chrome.extension.getURL('template.html'),
    {
        "imageURL": image,
        "num": 5
    }
);
$('body').prepend(tb);

template.html

<div id="topbar">
    <img src="{{imageURL}}"></img>
    {{num}}
</div>

The image shows up just fine, as you'd expect. And therefore loading template.html just returns the following string: chrome-extension://badmldhplgbmcbkolbmkhbamjaanjejj/template.html

How do I get the content of my template file as a string?

Thanks to Boris Smus for the solution

content_script.js

var req = new XMLHttpRequest();
req.open("GET", chrome.extension.getURL('template.html'), true);
req.onreadystatechange = function() {
    if (req.readyState == 4 && req.status == 200) {
        var image = chrome.extension.getURL('logo.jpg');
        console.log('Rendering Mustache.js template...');
        var tb = Mustache.to_html(
            req.responseText,
            {
                "imageURL": image,
                "num": 5
            }
        );
        $('body').prepend(tb);
    }
};
req.send(null);
like image 288
daharon Avatar asked Nov 03 '11 21:11

daharon


Video Answer


1 Answers

chrome.extension.getURL(file) returns the absolute URL of the requested file, not its contents. You should do an XHR on the template to get its contents instead.

Alternatively, store the contents of your template in your HTML itself using something like <script id="templ" type="text/x-template">...</script>, and then reference the contents of the template via document.getElementById('templ').

like image 180
Boris Smus Avatar answered Sep 21 '22 08:09

Boris Smus