Firefox extension content script does not load or add HTML
Everything below works in Chrome extension but fails when ported to Firefox:
- Load
test.html
if I don't remove from it<style></style>
- addition
#test_element
to body
Do you need styles in a separate file for the Firefox extension? Why crash append()
?
test.js
$(document).ready(function() {
$.get(chrome.extension.getURL('/html/test.html'), function(data) {
// not called unless style element is removed from HTML
// and never actually appended if it is removed
$(document.body).append($.parseHTML(data));
});
});
test.html
<style></style>
<div id="test_element">
<p>my name is cow</p>
</div>
manifest.json
{
"manifest_version": 2,
"name": "Test",
"version": "1.0",
"icons": {
"64": "icons/icon-64.png"
},
"permissions": [
"tabs",
"storage",
"idle"
],
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["lib/jquery.js", "src/test.js"]
}
],
"web_accessible_resources": [
"html/test.html"
]
}
source to share
This doesn't fall silently for me, but gives me:
XML Parsing Error: junk after document element
Location: https://www.google.gr/
Line Number 2, Column 1
This is because it is not a valid XML document (only one root element must exist).
My way to make it work:
test.html : (make it valid)
<div>
<style></style>
<div id="test_element">
<p>my name is cow</p>
</div>
</div>
test.js : (use XMLSerializer)
$(document).ready(function() {
$.get(chrome.extension.getURL('/html/test.html'), function(data) {
res = new XMLSerializer().serializeToString(data);
$(document.body).append(res);
});
});
source to share
For # 1: see solution from Christos. For # 2: $.get()
Returns a string in Chrome, but XMLDocument
in Firefox (it must be serialized with serializeToString()
before being added). Anyway, I removed jQuery to make the script content more lightweight ( $(document).ready()
not required by the way, because by default the content of the scripts is injected after the DOM is ready):
var httpRequest = new XMLHttpRequest();
httpRequest.onload = function(data) {
httpRequest.onload = null;
var template = document.createElement('template');
template.innerHTML = data.target.responseText;
var element = template.content.firstChild;
document.body.appendChild(element);
}
httpRequest.open('GET', chrome.extension.getURL('/html/test.html'));
httpRequest.send();
source to share