且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Firefox扩展内容脚本不加载和附加HTML

更新时间:2023-12-04 23:42:58

它并没有默默地落在我身上,而是给了我:

  XML分析错误:文档元素
之后的垃圾位置:https://www.google.gr/
行号2,列1

这是因为它不是一个有效的XML文档(一个根元素nt只应该存在)。



我的方法使其工作如下:
$ b

测试.html :(使之有效)

 < div> 
< style>< / style>
< div id =test_element>
< p>我的名字是牛< / p>
< / div>
< / div>

test.js :(使用XMLSerializer)

  $(document).ready(function(){
$ .get(chrome.extension.getURL('/ html / test.html '),函数(data){
res = new XMLSerializer()。serializeToString(data);
$(document.body).append(res);
});
});


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

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