我有一个非常基本的 socket.io 应用程序,它在服务器端监听 html 页面上的按钮单击。
index.html:
<html>
<head>
<script src="jquery.min.js"></script>
<script src="socket.io.js"></script>
<script src="index.js"></script>
</head>
<body><button id="asdf">click</buton></body>
</html>
index.js:
var socket = io('http://localhost:3000');
socket.on('connect',function(){
$(document).ready(function(){
$('#asdf').click(function(){
socket.emit('0.1');
});
});
});
这部分有效。我想做的就是将此功能放入 chrome 扩展中,以便我可以让我的 Node 应用程序响应 DOM 中的事件。现在,我有一个后台页面,当单击扩展程序图标时,它会注入(inject)脚本。
背景.js:
chrome.browserAction.onClicked.addListener(function(tab) {
chrome.tabs.executeScript({
file: 'script.js'
});
});
脚本.js:
console.log('test');
所以这也有效,但是当我将 socket.io.js 代码复制并粘贴到 script.js 文件中时,控制台上没有记录任何内容,我认为这意味着脚本无法正常工作。为什么这不起作用,是否有更好的方法将 socket.io.js 集成到浏览器扩展中?
最佳答案
所以我基本上最终通过后台页面连接到套接字,并从内容脚本通过该页面发送消息,这对我的应用程序来说效果很好。
关于javascript - 为什么我不能使用 chrome 扩展注入(inject) socket.io,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28868835/