限制从网站复制和粘贴的字符长度

时间:2016-04-07 20:43:44

标签: javascript html copy-paste

是否可以限制可以使用JS从网站复制的HTML文本的长度?我看过一些商业产品,例如Tynt,但似乎没有人允许你只允许选择200个字符?

1 个答案:

答案 0 :(得分:1)

此代码剪切为前200个字符,此外它还添加了一个读取更多链接到复制的内容。

document.body.oncopy = function () {
    var body_element = document.getElementsByTagName('body')[0];
    var selection;
    selection = window.getSelection();
    var pagelink = "<br />Read more at: <a href='" + document.location.href + "'>" + document.location.href + "</a><br />";
    var copytext = selection.substring(0,200) + pagelink;
    var newdiv = document.createElement('div');
    body_element.appendChild(newdiv);
    newdiv.innerHTML = copytext.substring(0,8);;
    selection.selectAllChildren(newdiv);
    window.setTimeout(function () {
        body_element.removeChild(newdiv);
    }, 0);
};