使用Chrome内容脚本添加复杂的HTML

Mal*_*hak 17 javascript html5 google-chrome google-chrome-extension content-script

我正在使用Chrome扩展程序的内容脚本来创建添加到网页上的复杂显示.

我首先将它直接集成在一个网站上进行测试,但现在我需要把它放在一个扩展中.

问题是Chrome的内容脚本API只允许注入javascript.这意味着,为了注入复杂的HTML布局,我需要完全用JS对象来编写它,这很难编写,难以维护并且绝对不是设计人员友好的.

我想知道是否有人知道或者可以想到一个聪明的方法来获得更好的工作流程.

Bro*_*ams 32

通过让内容脚本将它们注入iframe来添加整个网页相对容易.请遵循以下准则:

  1. *.htm*.html文件放在扩展程序的源文件夹中.

  2. 将HTML使用的任何文件*.css*.js文件也放在扩展文件夹中.

  3. 将HTML文件声明为资源.例如:

    "web_accessible_resources": ["Embedded_Hello_world.htm"]
    
    Run Code Online (Sandbox Code Playgroud)


  4. 不要在HTML文件中使用任何内联或外部服务器javascript.这避免了问题内容安全策略(CSP) .

  5. 这个问题不包括与页面/ iframe的通信,但如果你想这样做,它会涉及更多.在这里搜索SO; 它被覆盖了很多次.


例:

你可以通过以下方式看到这个:

  1. 创建新的扩展文件夹.
  2. jQuery下载到其中.
  3. 按照以下指定创建5个文件.
  4. 加载解压缩的扩展(您可以在此答案中看到类似的步骤.)
  5. 在Chrome中重新加载此页面; 你会看到嵌入在顶部的"Hello World"页面.

在扩展文件夹中创建这些文件:

manifest.json的:

{
    "manifest_version":         2,
    "content_scripts":          [ {
        "js":       [ "iframeInjector.js" ],
        "matches":  [   "https://stackoverflow.com/questions/*"
        ]
    } ],
    "description":              "Inject a complete, premade web page",
    "name":                     "Inject whole web page",
    "version":                  "1",
    "web_accessible_resources": ["Embedded_Hello_world.htm"]
}
Run Code Online (Sandbox Code Playgroud)


iframeInjector.js:

var iFrame  = document.createElement ("iframe");
iFrame.src  = chrome.extension.getURL ("Embedded_Hello_world.htm");

document.body.insertBefore (iFrame, document.body.firstChild);
Run Code Online (Sandbox Code Playgroud)


Embedded_Hello_world.htm:

<!DOCTYPE html>
<html><head>
    <title>Embedded Hello World</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">

    <link href="HelloWorld.css" rel="stylesheet" type="text/css">

    <script type="text/javascript" src="jquery.min.js"></script>
    <script type="text/javascript" src="HelloWorld.js"></script>
</head><body>
<p>Hello World!</p>
</body></html>
Run Code Online (Sandbox Code Playgroud)


HelloWorld.css:

body {
    color:              red;
    background-color:   lightgreen;
}
Run Code Online (Sandbox Code Playgroud)


HelloWorld.js:

$(document).ready (jQueryMain);

function jQueryMain () {
    $("body").append ('<p>Added by jQuery</p>');
}
Run Code Online (Sandbox Code Playgroud)

  • 注意:此功能自 2019 年 9 月起有效,但使用“chrome.runtime.getURL”而不是“chrome.extension.getURL”。请参阅/sf/ask/2264140791/ (2认同)

Pho*_*nic 5

这可能更好,没有外部库和 iframe。与 iautomation 解决方案几乎相同。

var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        var div = document.createElement('div');
        div.innerHTML = this.responseText;
        document.body.insertBefore(div, document.body.firstChild);
    } else {
        console.log('files not found');
    }
};
xhttp.open("GET", chrome.extension.getURL("/content.htm"), true);
xhttp.send();
Run Code Online (Sandbox Code Playgroud)