【发布时间】:2017-09-20 15:50:29
【问题描述】:
我正在构建一个连接到 websocket 并检索数据的 Chrome 扩展程序。我正在尝试构建一种方式,让用户从 popup.html 中选择一个选项,并将其更改为将建立连接的 websocket。这工作正常。
我的问题是,在选择一个选项后,新连接会与该 websocket 建立连接,但前一个连接会不断返回数据。我想在打开新连接之前关闭之前的连接。
popup.js(单选按钮更改存储新值)
$(function() {
$("input:radio[name=exc]").change(function() {
chrome.storage.local.set({'checked':this.value}, function() {
});
});
});
update.js(接收新选择的单选按钮,我正在尝试关闭以前的 websocket)
chrome.storage.onChanged.addListener(function(changes, namespace) {
chrome.storage.local.get("checked", function(data) {
if(data.checked == "foo") {
var ws = new WebSocket('wss://api.foo.com/ws');
ws.onopen = function() {
ws.send(JSON.stringify({"event":"test", "channel":"test"}));
};
ws.onmessage = function(msg) {
var price = response[7];
if(hb != "hb" && typeof hb != 'undefined') {
price = price.toString();
chrome.extension.sendMessage(price);
}
};
ws.close();
}
else if(data.checked == "bar") {
var pusher = new Pusher('xxxxxxxxxxxxx');
var tradesChannel = pusher.subscribe('test'),
child = null;
tradesChannel.bind('test', function (data) {
var price = data.price;
if(typeof data.price != 'undefined') {
price = price.toString();
chrome.extension.sendMessage(price);
}
});
pusher.disconnect();
}
});
});
如果我按原样保留代码,我会收到 WebSocket connection to 'wss://api.foo.com/ws' failed: WebSocket is closed before the connection is established. 并且没有收到任何数据。
【问题讨论】:
标签: javascript jquery google-chrome-extension websocket pusher