Copy to clipboard as plain text

后端 未结 1 1634
北海茫月
北海茫月 2021-02-02 16:29

I\'m using this code in background.js in a Chrome extension to copy text to the user\'s clipboard:

chrome.runtime.onMessage.addListener(
    functio         


        
1条回答
  •  有刺的猬
    2021-02-02 16:31

    Your question's code contains a common security issue known as XSS. Because you take untrusted input and assign it to .innerHTML, you're allowing attackers to insert arbitrary HTML in the context of your document.

    Fortunately, attackers cannot run scripts in the context of your extension because the extension's default Content security policy forbid inline scripts. This CSP is enforced in Chrome extensions exactly because of situations like this, to prevent XSS vulnerabilities.

    The correct way to convert HTML to text is via the DOMParser API. The following two functions show how to copy text as text, or for your case HTML as text:

    // Copy text as text
    function executeCopy(text) {
        var input = document.createElement('textarea');
        document.body.appendChild(input);
        input.value = text;
        input.focus();
        input.select();
        document.execCommand('Copy');
        input.remove();
    }
    
    // Copy HTML as text (without HTML tags)
    function executeCopy2(html) {
        var doc = new DOMParser().parseFromString(html, 'text/html');
        var text = doc.body.textContent;
        return executeCopy(text);
    }
    

    Note that .textContent completely ignores HTML tags. If you want to interpret
    s as line breaks, use the non-standard (but supported in Chrome) .innerText property instead of .textContent.

    Here are two of the many examples of how XSS could be abused using the executeCopy function from your question:

    // This does not only copy "Text", but also trigger a network request
    // to example.com!
    executeCopy('Text');
    
    // If you step through with a debugger, this will show an "alert" dialog
    // (an arbitrary script supplied by the attacker!!)
    debugger;
    executeCopy('');
    

    0 讨论(0)
提交回复
热议问题