Ivan Mir
Ivan Mir

Reputation: 1239

Firefox extension content script does not load and append HTML

Everything below works in a Chrome extension but silently fails when ported to Firefox on:

  1. loading the test.html unless I remove <style></style> from it
  2. appending the #test_element to the body

Do styles have to go into a separate file for Firefox extension? Why does append() fail?

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"
    ]
}

Upvotes: 3

Views: 1908

Answers (2)

Ivan Mir
Ivan Mir

Reputation: 1239

For #1: see the solution by Christos. For #2: $.get() returns a string in Chrome but XMLDocument in Firefox (that must be serialized with serializeToString() before appending). Anyway, I removed jQuery to make the content script lighter (by the way, $(document).ready() is not required because by default content scripts are injected after 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();

Upvotes: 0

Christos Papoulas
Christos Papoulas

Reputation: 2568

It is not falling silently to 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 (one root element only should exists).

My way to make it work is the following:

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);
      });
  });

Upvotes: 1

Related Questions