Gracie williams
Gracie williams

Reputation: 1145

Get the console log of website and send to websocket

I have the following situation:

I want to get the console log of a website and send that to WebSocket clients.

I was able to create a node server and send data to connected users with below code.

const puppeteer = require('puppeteer');
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 2222 });

wss.on('connection', function connection(ws) {
  ws.send("sending the sample data");
});

I was able to get the console log of website using following code:

(async () => {
  const browser = await puppeteer.launch({
    args: [
      '--no-sandbox',
      '--headless',
      '--disable-gpu',
      '--window-size=1920x1080'
    ]
  });

  const page = await browser.newPage();

  await page.goto('https://example.com/test.php');

  page.on('console', msg => console.log(msg.text()));

})();

Here page.on is a callback function, which is called every time there is a console log. How do I broadcast that msg (console.log from puppeteer) to WebSocket clients?

Please note that the website is opened once only when the app is started and console.log output is generated using setInterval every second. So new users get only the latest data.

Upvotes: 1

Views: 5250

Answers (1)

yeya
yeya

Reputation: 2204

Instead of console.log(msg.text()) you need to broadcast the message to all ws clients, right?

So a simple code will be:

page.on('console', msg => {
  wss.clients.forEach(function each(client) {
    if (client.readyState === WebSocket.OPEN) {
      client.send(msg.text());
    }
  });
});

Read here for more info

Upvotes: 2

Related Questions