-
Notifications
You must be signed in to change notification settings - Fork 761
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: getCoreContentText for any websites
- Loading branch information
Showing
2 changed files
with
46 additions
and
0 deletions.
There are no files selected for viewing
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,45 @@ | ||
function getArea(e) { | ||
const rect = e.getBoundingClientRect() | ||
return rect.width * rect.height | ||
} | ||
|
||
function findLargestElement(e) { | ||
let maxArea = 0 | ||
let largestElement = null | ||
const limitedArea = 0.8 * getArea(e) | ||
|
||
function traverseDOM(node) { | ||
if (node.nodeType === Node.ELEMENT_NODE) { | ||
const area = getArea(node) | ||
|
||
if (area > maxArea && area < limitedArea) { | ||
maxArea = area | ||
largestElement = node | ||
} | ||
|
||
Array.from(node.children).forEach(traverseDOM) | ||
} | ||
} | ||
|
||
traverseDOM(e) | ||
return largestElement | ||
} | ||
|
||
export function getCoreContentText() { | ||
const largestElement = findLargestElement(document.body) | ||
const secondLargestElement = findLargestElement(largestElement) | ||
console.log(largestElement) | ||
console.log(secondLargestElement) | ||
|
||
if (!largestElement) return | ||
|
||
let ret | ||
if (secondLargestElement && getArea(secondLargestElement) > 0.5 * getArea(largestElement)) { | ||
ret = secondLargestElement.textContent | ||
console.log('use second') | ||
} else { | ||
ret = largestElement.textContent | ||
console.log('use first') | ||
} | ||
return ret.trim().replaceAll(' ', '').replaceAll('\n\n', '').replaceAll(',,', '') | ||
} |
This file contains 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