0

I'm trying to access document.getElementbyID and document.location in my typescript application. But getting error.

(node:3024) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): ReferenceError: document is not defined

NB: Please note that I don't want to use jquery so that it will reduce my bundle size.

Any other replacement of jquery in node is also acceptable with less size

Nirmal
  • 13
  • 9

1 Answers1

0

Actually, nodejs code don't run on browser. Its server side scripting language so there is no window or document object. If you still want to use document.getElementbyID. you can use "puppeteer".

Puppeteer is a Node library which provides a high-level API to control headless Chrome or Chromium over the DevTools Protocol. It can also be configured to use full (non-headless) Chrome or Chromiu

Example,

  1. npm install puppeteer
  2. Added below code,
const puppeteer = require('puppeteer');

function async xyz() {
   const browserData = await puppeteer.launch();
   page = await browserData.newPage();
   await page.goto('http://example.com/some.html', {waitUntil: 'load'});

const xyzPage = await page.evaluate(() => {
     return document.getElementById("xyzid").innerHTML;
});

console.log(xyzPage);

}

Note: there are another npm packages available that provide access to document object like JSDOM, etc. But lots of people are using "puppeteer".

Nikhil Kadam
  • 143
  • 6