javascript – 以纯文本形式复制到剪贴板

前端之家收集整理的这篇文章主要介绍了javascript – 以纯文本形式复制到剪贴板前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我在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.

幸运的是,攻击者无法在扩展的上下文中运行脚本,因为扩展的默认Content security policy禁止内联脚本.这个CSP是在Chrome扩展中执行的,正是因为这样的情况,才能防止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>作为换行符解释,请使用非标准(但在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>');
原文链接:https://www.f2er.com/js/152463.html

猜你在找的JavaScript相关文章