ContentScript 运行在页面的 DOM 上,但运行在不同的 JS 沙箱上,所以不能像示例中那样直接通过 DOM 注入 JS。
我建议您将 firebase lib 加载到后台页面,然后您可以通过后台后端从后台脚本和来自内容脚本的代理请求访问它。这不会导致每次加载页面加载内容脚本时都加载firebase lib,并且它将在后台页面初始化时加载一次(或者您可以使用非持久性后台脚本通过请求加载它)。
例子:
manifest.json
{
"manifest_version": 2,
"name": "FireBase Demo",
"description": "FireBase client demo",
"version": "0.0.1",
"permissions": [
"<all_urls>",
"tabs"
],
"background": {
"page": "bg.html",
"persistent": false
},
"content_scripts": [{
"matches": ["https://*/*","http://*/*"],
"js": ["cs.js"]
}],
"content_security_policy": "script-src 'self' https://www.gstatic.com/firebasejs/5.3.0/firebase.js; object-src 'self'"
}
bg.html
<html>
<head>
<script src="https://www.gstatic.com/firebasejs/5.3.0/firebase.js"></script>
<script src="bg.js"></script>
</head>
<body></body>
</html>
bg.js
firebase.initializeApp({
apiKey: '...',
authDomain: '...',
projectId: '...'
});
var db = firebase.firestore();
db.settings({timestampsInSnapshots: true});
chrome.runtime.onMessage.addListener((msg, sender, response) => {
if (msg.command == "add"){
console.log("process msg add", msg, sender, response);
db.collection(msg.collection).add(msg.data).then((result) => {
console.log("success", result)
response({type: "result", status: "success", data: result, request: msg});
}).catch((result) => {
console.log("error", result);
response({type: "result", status: "error", data: result, request: msg});
});
}
return true;
});
cs.js
chrome.runtime.sendMessage({command: "add", collection: "users", data: {name: "user"}}, (msg) => {
console.log("response", msg)
});
另一个变体是加载你的 firebase JS lib 和你需要运行到页面的 JS 沙箱的代码,方法是将其注入页面的 DOM,如下所示:
var script = document.createElement("script");
script.src = "https://www.gstatic.com/firebasejs/5.3.0/firebase.js"
document.body.append(script); // firebase lib will be loaded to the page's JS sandbox and page's DOM
var fn = function injectedFunction(seed) { /* your JS code you want to run is page's sandbox */ }
var ele = document.createElement("script");
ele.textContent = fn+"console.log(injectedFunction());";
但是这个变种很糟糕,因为在这种情况下页面的 CSP 可能会阻塞你的 JS。
document.body.appendChild(ele);