You can unsubscribe from an event by prepending the action with a single dash (-).
So if you subscribed to 155-questions-active
to get the realtime question feed
you can unsubscribe by sending -155-questions-active
.
see How do the Stack Exchange WebSockets work? What are all the options you can send to them? to get all the actions you can send to the websocket.
Here is small Stack Snippet to demo subscription and unsubscription:
var w = new WebSocket("wss://qa.sockets.stackexchange.com/"),
result = document.getElementById('result'),
control = document.getElementById('control');
//handle a message
w.onmessage = function(e) {
var raw;
data = JSON.parse(e.data);
if (data.data !== "hb") {
data.data = JSON.parse(data.data);
raw=document.createElement('div');
raw.textContent= data.action +
': ' +
(data.data.html ||
data.data.titleEncodedFancy ||
data.data.body);
result.appendChild(raw);
} else {
w.send("hb");
}
};
w.onopen = function() {
// do nothing
};
function subscriptionChanged() {
if (this.checked === true) {
// subscribe
w.send(this.value);
} else {
// unsubscribe
w.send('-'+ this.value);
}
}
function buildCheckbox(v) {
var cb = document.createElement('input');
cb.setAttribute('type','checkbox');
cb.setAttribute('value', v);
cb.setAttribute('id', 'c-' + v);
cb.addEventListener('change', subscriptionChanged);
return cb;
}
function buildLabel(v) {
var lbl = document.createElement('label');
lbl.textContent = v;
lbl.setAttribute('for', 'c-' + v);
return lbl;
}
function subscription(v) {
var container = document.createElement('div');
container.appendChild(buildCheckbox(v));
container.appendChild(buildLabel(v));
control.appendChild(container);
}
// setup which data to subscribe to
['155-questions-active',
'1-review-dashboard-update',
'1-questions-newest-tag-c',
'1-questions-newest-tag-c++',
'1-questions-newest-tag-c#',
'1-questions-newest-tag-java',
'1-questions-newest-tag-javascript',
'1-questions-newest-tag-php',
'1-questions-newest-tag-mysql',
'1-questions-newest-tag-python',
'1-questions-newest-tag-ruby',
'1-questions-newest-tag-html',
'1-questions-newest-tag-css'
].forEach(subscription);
subscribe
<div id="control">
</div>
<div id="result">
</div>
I reverse engineered this by looking up the full-anon.en.js on the dev.sstatic.net which turns out to reveal this method:
function unsubscribe(data) {
log("unsubscribing " + data);
var index = $.inArray(data, channelBuffer);
if (index == -1) return;
channelBuffer.splice(index, 1);
// unsubscribe happens immediately and is sent directly
if (socket == null || !socket.isOpen()) return;
socket.send("-" + data);
}