I would like to answer to new javascript, react, react-native and node questions. So, how would I know about the new questions which are asked by users on these areas?
Advertisement
Answer
Open a Websocket connection to wss://qa.sockets.stackexchange.com/
, then send the message 1-questions-newest-tag-TAG
where TAG
is the tag you want to watch for. When a new question is posted, you’ll be sent a message with the question ID.
The question data needs to be retrieved separately (as of SE’s winter 2021/2022 redesign). One way to do it – as SE does it on /newest
pages – is to POST to /posts/ajax-load-realtime-list/
with the question ID, and it will respond with the question summary. (Unfortunately, due to cross-origin restrictions, this approach can’t be embedded into a live Stack Snippet)
Open a blank page on Stack Overflow, such as this one, and then paste the following into your console, and you’ll see new questions appear on the page as they’re posted:
const socket = new WebSocket('wss://qa.sockets.stackexchange.com/'); socket.onopen = () => { socket.send('1-questions-newest-tag-javascript'); socket.send('1-questions-newest-tag-java'); socket.send('1-questions-newest-tag-python'); socket.send('1-questions-newest-tag-php'); console.log('Listening...'); }; const seenQuestions = new Set(); socket.onmessage = ({ data }) => { const obj = JSON.parse(data); if (obj.action === 'hb') { socket.send('pong'); return; } const { id, body } = JSON.parse(obj.data); if (seenQuestions.has(id)) { // Duplicate question, a message for it has already been handled: return; } seenQuestions.add(id); console.log('New question:', id); insertQuestion(id) }; socket.onerror = console.error; // just in case const insertQuestion = (questionId) => { const params = new URLSearchParams(); params.append('postIdsSemiColonDelimited', questionId); fetch('https://stackoverflow.com/posts/ajax-load-realtime-list/', { method: 'post', body: params }) .then(r => r.json()) .then((result) => { document.body.insertAdjacentHTML('beforeend', result[questionId]); }) .catch(console.error); // just in case };
If you want to use this anywhere else other than on a Stack Exchange site, you might also wish to embed their CSS
You do need to listen for a hb
message and reply to it, so that StackExchange knows to keep the connection alive.
Do note that the socket will send data for a given question for every tag being listened for. Eg, if something is tagged with both Javascript and React, and you’ve sent requests to listen for both tags, you’ll receive a message for that twice, hence the need for the Set to avoid listing duplicates.