繁体   English   中英

以纯文本格式复制到剪贴板

[英]Copy to clipboard as plain text

我在Chrome扩展程序的background.js中使用此代码将文本复制到用户的剪贴板:

chrome.runtime.onMessage.addListener(
    function(request, sender, sendResponse) {
        if (request.command == "copy") {
            executeCopy(request.text);
            sendResponse({farewell: "copy request received"});
        }
    }
);

function executeCopy(text){
    var copyDiv = document.createElement('div');
    copyDiv.contentEditable = true;
    document.body.appendChild(copyDiv);
    copyDiv.innerHTML = text;
    copyDiv.unselectable = "off";
    copyDiv.focus();
    document.execCommand('SelectAll');
    document.execCommand("Copy", false, null);
    document.body.removeChild(copyDiv);
}

它使用格式复制文本。 如何以纯文本格式复制文本而不进行格式化?

您的问题代码包含一个称为XSS的常见安全问题。 因为您接受不受信任的输入并将其分配给.innerHTML ,所以您允许攻击者在文档的上下文中插入任意HTML。

幸运的是,攻击者无法在您的扩展上下文中运行脚本,因为扩展的默认内容安全策略禁止内联脚本。 正是因为这种情况,才在Chrome扩展程序中强制执行此CSP,以防止XSS漏洞。

将HTML转换为文本的正确方法是通过DOMParser API。 以下两个函数显示如何将文本复制为文本,或将HTML作为文本复制:

// 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);
}

请注意.textContent完全忽略HTML标记。 如果要将<br> s解释为换行符,请使用非标准(但在Chrome中受支持) .innerText属性而不是.textContent

以下是使用问题中的executeCopy函数如何滥用XSS的众多示例中的两个:

// This does not only copy "Text", but also trigger a network request
// to example.com!
executeCopy('<img src="http://example.com/">Text');

// If you step through with a debugger, this will show an "alert" dialog
// (an arbitrary script supplied by the attacker!!)
debugger;
executeCopy('<iframe src="data:text/html,<script>alert(/XXS-ed!/);<\/script>"></iframe>');

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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