-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathindex.js
50 lines (43 loc) · 1.75 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
function scrollPage(scrollDirection) {
return async (page, { delay = 100, size = 250, stepsLimit = null } = {}) => {
let lastScrollPosition = await page.evaluate(
async (pixelsToScroll, delayAfterStep, limit, direction) => {
let getElementScrollHeight = element => {
if (!element) return 0
let { clientHeight, offsetHeight, scrollHeight } = element
return Math.max(scrollHeight, offsetHeight, clientHeight)
}
let initialScrollPosition = window.pageYOffset
let availableScrollHeight = getElementScrollHeight(document.body)
let lastPosition = direction === 'bottom' ? 0 : initialScrollPosition
let scrollFn = resolve => {
let intervalId = setInterval(() => {
window.scrollBy(0, direction === 'bottom' ? pixelsToScroll : -pixelsToScroll)
lastPosition += direction === 'bottom' ? pixelsToScroll : -pixelsToScroll
if (
(direction === 'bottom' && lastPosition >= availableScrollHeight) ||
(direction === 'bottom' &&
limit !== null &&
lastPosition >= pixelsToScroll * limit) ||
(direction === 'top' && lastPosition <= 0) ||
(direction === 'top' &&
limit !== null &&
lastPosition <= initialScrollPosition - pixelsToScroll * limit)
) {
clearInterval(intervalId)
resolve(lastPosition)
}
}, delayAfterStep)
}
return new Promise(scrollFn)
},
size,
delay,
stepsLimit,
scrollDirection
)
return lastScrollPosition
}
}
export const scrollPageToBottom = scrollPage('bottom');
export const scrollPageToTop = scrollPage('top');