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?
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);
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')
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With