文章复制添加版权【更新 - fixed text/html bug】

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
/**
* @description 添加版权
*/
const addCopyright = () => {
const genCopy = () => {
return [
'',
'',
'作者:Vanessa',
'链接:https://hacpai.com/article/1510544423932',
'来源:黑客派',
'著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。',
]
}

$('.content-reset').on('copy', function (event) {
if (!window.getSelection) {
return
}

var selectionObj = window.getSelection()
var author = $(this).data('author') || 'HacPai'
var link = $(this).data('link') || location.href

if (selectionObj.toString().length < 128) {
return
}

if (selectionObj.rangeCount) {
var container = document.createElement("div");
for (var i = 0, len = selectionObj.rangeCount; i < len; ++i) {
container.appendChild(selectionObj.getRangeAt(i).cloneContents());
}
}

if ('object' === typeof event.originalEvent.clipboardData) {
event.originalEvent.clipboardData.setData('text/html', container.innerHTML + genCopy(author, link).join('<br>'))
container.remove();
event.originalEvent.clipboardData.setData('text/plain', selectionObj.toString() + genCopy(author, link).join('\n'))
event.preventDefault();
return
}

$('body').append('<div id="symFixCopy" style="position: fixed; left: -9999px;">' +
selectionObj.toString() + genCopy(author, link).join('<br>') + '</div>')
window.getSelection().selectAllChildren($('#symFixCopy')[0])
setTimeout(function () {
$('#symFixCopy').remove()
}, 200)
})
}

打开 F12,复制以上代码运行,再执行 addCopyright() 后。在文章内容区域拷贝长度大于 128 的文字,再粘贴即可看到效果