I’m trying to communicate with my local server from my chrome extension with scoket.io but I’m getting an XHR Polling Error.
I don’t get this error when I simulate a client, I only get it with the chrome extension.
I’ve also tried using my ip instead of localhost, defining a websocket protocol when creating the server or adding a cors but I always get the same error.
manifest.js
{
"manifest_version": 3,
"name": "DogadPrime Alerte",
"version": "2.0",
"description": "Ne manquez jamais un live de DogadPrime sur Twitch ainsi que les prochaines vidéos youtube grâce à des notifications instantanées !",
"permissions": [
"notifications",
"alarms",
"storage",
"activeTab",
"webRequest"
],
"minimum_chrome_version": "116",
"host_permissions": ["http://localhost:3000/*"],
"background": {
"service_worker": "background.js",
"type": "module"
},
"icons": {
"16": "icons/icon16.png",
"48": "icons/icon48.png",
"128": "icons/icon128.png"
}
}
background.js
import { io } from "https://cdn.jsdelivr.net/npm/[email protected]/+esm";
const socketUrl = "http://localhost:3000/";
const socket = io(socketUrl, {
transport: ["websocket"],
});
console.log("Lancement de l'extension browser");
if (typeof browser === "undefined") {
var browser = chrome;
}
function showNotificationTwitch(stream) {
browser.notifications.create('twitch-streamer-alert', {
type: 'basic',
iconUrl: 'icons/icon48.png',
title: `${stream.user_name} est en live !`,
message: `Regardez maintenant sur Twitch : ${stream.title}`,
priority: 2
});
}
browser.notifications.onClicked.addListener(function (notificationId) {
if (notificationId === 'twitch-streamer-alert') {
const twitchChannelUrl = 'https://www.twitch.tv/dogadprime';
console.log('Ouverture de l'URL Twitch:', twitchChannelUrl);
browser.tabs.create({ url: twitchChannelUrl });
}
});
// Événement lorsqu'une connexion est établie
socket.on('connection', () => {
console.log('Connexion au serveur');
});
socket.on('platformNotification', (data) => {
console.log(data);
const { platform, status, streamData } = data;
if (platform == 'twitch' && status == true) {
console.log('Le streamer est en direct !');
console.log('Détails du stream :', data.streamData);
showNotificationTwitch(streamData);
} else {
console.log('Le streamer n'est pas en direct.');
}
});
socket.on('connect_error', (error) => {
console.log('Erreur de connexion :', error);
});
server app.js
const express = require('express');
const http = require('http');
const socketIo = require('socket.io');
const fetch = require('node-fetch');
require('dotenv').config();
const app = express();
const server = http.createServer(app);
const io = socketIo(server, {
cors: {
origin: "*",
methods: ["GET", "POST"],
},
});
const clientId = process.env.TWITCH_CLIENT_ID;
const accessToken = process.env.TWITCH_ACCESS_TOKEN;
const streamerName = 'sc2skyblue';
const twitchApiUrl = `https://api.twitch.tv/helix/streams?user_login=${streamerName}`;
let isStreamerOnline = false;
async function checkStreamerLive() {
try {
const response = await fetch(twitchApiUrl, {
headers: {
'Client-ID': clientId,
'Authorization': `Bearer ${accessToken}`
}
});
const data = await response.json();
const currentlyOnline = data.data && data.data.length > 0;
if (currentlyOnline && !isStreamerOnline) {
io.emit('platformNotification', {
platform: 'twitch',
status: true,
streamData: data.data[0]
});
console.log("Le streamer est en direct. Notification envoyée.");
} else if (!currentlyOnline && isStreamerOnline) {
io.emit('platformNotification', {
platform: 'twitch',
status: false,
streamData: null
});
console.log("Le streamer est hors ligne. Notification envoyée.");
}
isStreamerOnline = currentlyOnline;
} catch (error) {
console.error('Erreur lors de la vérification du statut du streamer :', error);
}
}
const checkInterval = 1 * 60 * 1000; // 1 minute
setInterval(checkStreamerLive, checkInterval);
io.on('connection', (socket) => {
console.log('Un client est connecté');
socket.emit('welcome', { message: 'Bienvenue sur le serveur Socket.IO' });
socket.on('disconnect', () => {
console.log('Un client s'est déconnecté');
});
});
server.listen(3000, () => {
console.log('Serveur en écoute sur le port 3000');
});