typescript puppeteer支持window及document属性
# 问题:支持window等属性
在使用ts+puppeteer开发时, 需要用到一个功能,页面滚动,但在vscode中, 会报window 和document无法找到
// 滑动屏幕,滚至页面底部
function autoScroll(page:any) {
console.log('autoScroll')
return page.evaluate(() => {
return new Promise((resolve) => {
var totalHeight = 0;
var distance = 100;
// 每500毫秒让页面下滑100像素的距离
var timer = setInterval(() => {
var scrollHeight = document.body.scrollHeight;
window.scrollBy(0, distance);
totalHeight += distance;
if (totalHeight >= scrollHeight) {
clearInterval(timer);
console.log('resolve')
resolve();
}
}, 500);
})
});
}
# 解决方法
- 在tsconfig.js中加入 dom
- 引入@types/puppeteer 声明包
//tsconfig.json
{
"compilerOptions": {
"module": "commonjs",
"moduleResolution": "node",
"target": "esnext",
"outDir": "dist",
"strict": true,
"pretty": true,
"sourceMap": true,
"strictPropertyInitialization": true,
"strictNullChecks": true,
"lib": [ "es2017", "dom"]
},
"include": ["src"],
"exclude": ["node_modules", "**/*.spec.ts"]
}
npm i @types/puppeteer
解决问题,在没有找到答案之前还是很苦恼的,明明方法没问题, 就是无法执行,找了一遍才知道这种解决方式
上次更新: 2021/12/19, 18:05:42