我需要在右侧的当前选项卡中插入一个div作为滑块。因此,我在清单中使用content_script来加载注入脚本。但是这里我需要注入更多的html元素,因此js中的createElement会使我的content.js变得丑陋。因此,我需要一些js模板引擎来编写html并使用content.js将其注入dom。我更喜欢handlejs,因为它使用每个编译器支持csp。
Am使用background.js将消息从那里发送到content.js以注入dom。那部分很好。现在,只有content.js必须包含html模板才能将我的大量需求注入页面内。
manifest.json
{
"name":"Stack me",
"version":"0.1",
"manifest_version":2,
"description":"hack the dom, inject our dom as a slidbar",
"background" : {
"scripts" : ["background/background.js"]
},
"content_scripts":
[
{
"matches": ["<all_urls>"],
"js":["thirdParty/jquery-3.3.1.min.js", "thirdParty/handlebars-v4.1.1.js", "content/content.js"]
}
],
"browser_action": {
"default_icon": "icons/icon.png"
},
"icons":{
"16":"icons/icon.png",
"128":"icons/icon.png"
},
"web_accessible_resources": [
"icons/icon.png"
]
}
background.js
console.log("background js")
chrome.browserAction.onClicked.addListener(iconClicked)
function iconClicked(tab) {
let msg = { type: "clientAuth"}
chrome.tabs.sendMessage(tab.id, msg)
}
content.js
chrome.runtime.onMessage.addListener(gotMessage);
function gotMessage(message, sender, sendResponse) {
switch(message.type){
case "clientAuth":
registerIfNeeded();
break;
}
}
function registerIfNeeded() {
//call api
//UI
if(document.getElementById("myDivId"))
document.getElementById("myDivId").remove()
else {
...
var div = document.createElement( 'div' );
div.id = 'myDivId';
...
}
}
//How to replace the below code to work with templates, which can be included here.
/*<script id="entry-template" type="text/x-handlebars-template">
<div class="entry">
<h1>AJ</h1>
<div class="body">
aj
</div>
</div>
</script>
var source = document.getElementById("entry-template").innerHTML;
var template = Handlebars.compile(source);*/