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

标签 javascript google-chrome text google-chrome-extension copy-paste

我在 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 应用程序接口(interface)。以下两个函数显示了如何将文本复制为文本,或针对您的情况将 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 .

以下是 XSS 如何使用 executeCopy 被滥用的众多示例中的两个。从你的问题中发挥作用:

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

关于javascript - 以纯文本形式复制到剪贴板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25099409/

相关文章:

javascript newwindow.document.getElementById 有时不起作用

javascript - noscript.innerHTML 跨浏览器有不同的结果

c - c - 如何在c中比fprintf更快地写入文本文件?

javascript - Safari 和 Chrome 中的跨域 AJAX 调用

html - Chrome 渲染问题?

android - Toast 中的文本居中

text - 批量查找并替换Sublime Text 2

javascript - 如何在React Native ART中绘制圆 Angular 矩形

javascript - 下载由 Javascript 生成的动态创建的 CSS 文件

javascript - 文件上传返回 "undefined"