[英]How to access window or document object in nodejs /es2017
I'm trying to access document.getElementbyID and document.location in my typescript application. 我正在尝试访问我的typescript应用程序中的document.getElementbyID和document.location。 But getting error.
但是得到错误。
(node:3024) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): ReferenceError: document is not defined (node:3024)UnhandledPromiseRejectionWarning:未处理的promise promise(拒绝id:1):ReferenceError:未定义文档
NB: Please note that I don't want to use jquery so that it will reduce my bundle size. 注意:请注意,我不想使用jquery,这样会减少我的包大小。
Any other replacement of jquery in node is also acceptable with less size 在节点中任何其他jquery替换也可以接受更小的大小
Actually, nodejs code don't run on browser. 实际上,nodejs代码不能在浏览器上运行。 Its server side scripting language so there is no window or document object.
它的服务器端脚本语言因此没有窗口或文档对象。 If you still want to use document.getElementbyID.
如果您仍想使用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. Puppeteer是一个Node库,它提供了一个高级API,通过DevTools协议控制无头Chrome或Chromium。 It can also be configured to use full (non-headless) Chrome or Chromiu
它也可以配置为使用完整(非无头)Chrome或Chromiu
Example, 例,
npm install puppeteer
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". 注意:还有另一个可用的npm包提供对JSDOM等文档对象的访问。但是很多人正在使用“puppeteer”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.