Last active
May 16, 2019 10:01
-
-
Save elierotenberg/bfacc2ec7e9a3c25657b399c451e567d to your computer and use it in GitHub Desktop.
Get text within rectangle
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
(() => { | |
const MAX_BASENAME_LENGTH = 64; | |
const clicks = []; | |
const getNodesInRectangle = (topLeft, bottomRight) => | |
Array.from(document.querySelectorAll("*").values()).filter(node => { | |
const { x, y, width, height } = node.getBoundingClientRect(); | |
return ( | |
x >= topLeft.x && | |
x + width <= bottomRight.x && | |
y >= topLeft.y && | |
y + height <= bottomRight.y | |
); | |
}); | |
const extractSelection = (topLeft, bottomRight) => { | |
console.log({ topLeft, bottomRight }); | |
const nodes = getNodesInRectangle(topLeft, bottomRight); | |
console.log({ nodes }); | |
return nodes.map(node => node.textContent).join(" "); | |
}; | |
const saveToFile = text => { | |
const href = `data:text/plain;base64,${btoa(text)}`; | |
const { location} = document; | |
const baseName = `${location.hostname}-${location.pathname}`.slice(0, MAX_BASENAME_LENGTH); | |
const a = document.createElement("a"); | |
a.setAttribute( | |
"href", | |
href, | |
); | |
a.setAttribute( | |
"download", | |
`${baseName}.txt`, | |
); | |
a.style.display = "none"; | |
document.body.appendChild(a); | |
a.click(); | |
document.body.removeChild(a); | |
}; | |
const onClick = event => { | |
const point = { x: event.clientX, y: event.clientY }; | |
console.log(point); | |
clicks.push(point); | |
if (clicks.length === 2) { | |
document.removeEventListener("mousedown", onClick); | |
const [topLeft, bottomRight] = clicks; | |
saveToFile(extractSelection(topLeft, bottomRight)); | |
} | |
}; | |
document.addEventListener("mousedown", onClick); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment