你好!将socket.io.js添加到Chrome扩展程序时遇到问题,它不顺利!我试过这样的
var script = document.createElement('script');
script.src = 'socket.io.js';
script.type = 'text/javascript';
document.getElementsByTagName('head')[0].appendChild(script);
但它不起作用,它只附加在HTML上(我在Dev工具网络中看到过),但是控制台仍然说未捕获的ReferenceError:io未定义。我该怎么办?
码: 的manifest.json
{
"name": "Test",
"version": "0.0.1",
"description": "Test app",
"permissions": [ "background", "tts", "storage" ],
"background": { "scripts": ["my.js"] },
"browser_action": {
"default_popup": "my.html"
},
"content_security_policy": "script-src 'self' 'unsafe-eval'; object-src 'self'",
"content_scripts": [
{
"matches": ["http://*/*"],
"js": ["socket.io.js", "my.js"]
}
],
"manifest_version": 2
}
my.js
console.log("hey");
var script = document.createElement('script');
script.src = 'socket.io.js';
script.type = 'text/javascript';
document.getElementsByTagName('head')[0].appendChild(script);
var script2 = document.createElement('script');
script2.src = 'smart.js';
script2.type = 'text/javascript';
document.getElementsByTagName('head')[0].appendChild(script2);
smart.js
var socket = io.connect('http://localhost:3000');
socket.on('connect', function() {
console.log('Client connected');
});
my.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script src="my.js"></script>
</head>
<body>
</body>
</html>
如何使它工作?
的 P.S。 sockets.io.js与所有脚本位于同一目录中
答案 0 :(得分:0)
您需要等待加载第一个脚本。
my.js:
(function(d, s, id){
if (d.getElementById(id)){ return; } // exec only once
var js1 = d.createElement(s);
js1.id = id;
js1.onload = function(){
console.log("js1 is ready");
var js2 = document.createElement(s);
js2.src = 'smart.js';
document.getElementsByTagName('head')[0].appendChild(js2);
};
console.log("loading js1");
js1.src = "socket.io.js";
document.getElementsByTagName('head')[0].appendChild(js1);
}(document, 'script', 'some unique id'));