Last active
August 25, 2022 04:58
-
-
Save heug/c4a192981a64d5ef67df96df13e68a76 to your computer and use it in GitHub Desktop.
mabl function to scroll down a page once at a time and search for an element and innerText
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @NOTE - This is a snippet will not work in Internet Explorer. | |
*/ | |
function mablJavaScriptStep(mablInputs, callback) { | |
// ## Values that one could parameterize ## | |
let elementSelector = ".contents-genre-ranking .contents-more--center .btn--emphasis"; | |
let elementText = "ランキング一覧"; | |
// Call the "scrollDown" function once every second | |
let scrollInterval = setInterval(scrollDown, 1000); | |
let windowHeight = window.innerHeight; | |
let prevScrollHeight; | |
let loopCount = 0; | |
// Function to be called to scroll down | |
function scrollDown() { | |
// Increase the value of variable "loopCount" by 1 | |
++loopCount; | |
// Scroll down one page | |
window.scroll(0, loopCount * windowHeight); | |
// Get all the loaded elements matching elementSelector | |
let allElements = Array.from(document.querySelectorAll(elementSelector)); | |
// Find all the elements that contain the text in variable "elementText" | |
let matchingElements = allElements.filter((cell) => | |
cell.innerText.includes(elementText) | |
); | |
// If the innerText we were looking for was there, then there should be 1 value in the array (0 values otherwise) | |
let elementTextFound = matchingElements.length !== 0; | |
// Determine if we have scrolled to the bottom of the scroll view | |
let scrolledToBottom = | |
prevScrollHeight === document.documentElement.scrollHeight; | |
// Stop scrolling if the row was found and return | |
if (elementTextFound) { | |
console.log("Element Found"); | |
clearInterval(scrollInterval); | |
// click on first element in array | |
allElements[0].click() | |
callback("Element Found"); | |
} | |
// Stop scrolling if we have reached the bottom of the results and return | |
if (scrolledToBottom) { | |
console.log("Element Not Found. Bottom of scroll view reached."); | |
clearInterval(scrollInterval); | |
throw Error("Element not found. Bottom of scroll view reached."); | |
callback("Element Not Found. Bottom of scroll view reached."); | |
} | |
// Timeout after 25 seconds | |
if (loopCount = 25) { | |
clearInterval(scrollInterval) | |
callback("25 seconds elapsed. Loop Terminated. Element not found."); | |
} | |
// Update prevScrollHeight to check against to confirm entire document has been loaded | |
prevScrollHeight = document.documentElement.scrollHeight; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment