简体   繁体   中英

Copy all webpage text to clipboard with javascript

I was wondering if there was a way to select all text on a web page, and copy it to clipboard on button click.

I have a PHP script that echo s the output of dmesg on my server, and I want a way to copy all text on button click.

If there is only one output on one page. you can use XML HTTP Request (XHR) to get the content of the page, store the response of XHR request and then use clipboard.js ( https://clipboardjs.com/ ) to copy the content to the clipboard

Try this. Pass the element you want to this function on click of a button:

function selectText(element) {
    var doc = document
        , text = element
        , range, selection
    ;
    if (doc.body.createTextRange) { //ms
        range = doc.body.createTextRange();
        range.moveToElementText(text);
        range.select();
    } else if (window.getSelection) { //all others
        selection = window.getSelection();
        range = doc.createRange();
        range.selectNodeContents(text);
        selection.removeAllRanges();
        selection.addRange(range);
    }
}

read more about it here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM