利用JavaScript选中网页所有内容的示例代码

可以使用window.getSelection()和document.createRange()方法来创建一个范围,将整个body元素包含进去,然后调用selection.addRange(range)来实现全选。例如:

function selectAllContent() {

const selection = window.getSelection();

const range = document.createRange();

range.selectNodeContents(document.body);

selection.removeAllRanges();

selection.addRange(range);

}

调用该函数即可选中网页上的所有内容。