Mal*_*hak 17 javascript html5 google-chrome google-chrome-extension content-script
我正在使用Chrome扩展程序的内容脚本来创建添加到网页上的复杂显示.
我首先将它直接集成在一个网站上进行测试,但现在我需要把它放在一个扩展中.
问题是Chrome的内容脚本API只允许注入javascript.这意味着,为了注入复杂的HTML布局,我需要完全用JS对象来编写它,这很难编写,难以维护并且绝对不是设计人员友好的.
我想知道是否有人知道或者可以想到一个聪明的方法来获得更好的工作流程.
Bro*_*ams 32
通过让内容脚本将它们注入iframe来添加整个网页相对容易.请遵循以下准则:
将*.htm或*.html文件放在扩展程序的源文件夹中.
将HTML使用的任何文件*.css和*.js文件也放在扩展文件夹中.
将HTML文件声明为资源.例如:
"web_accessible_resources": ["Embedded_Hello_world.htm"]
Run Code Online (Sandbox Code Playgroud)
不要在HTML文件中使用任何内联或外部服务器javascript.这避免了问题的内容安全策略(CSP) .
这个问题不包括与页面/ iframe的通信,但如果你想这样做,它会涉及更多.在这里搜索SO; 它被覆盖了很多次.
你可以通过以下方式看到这个:
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)
这可能更好,没有外部库和 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)