【分享】JS如何为复制的Web文本添加其他信息

时间:2023-03-09 03:24:25
【分享】JS如何为复制的Web文本添加其他信息

看到了两篇关于这题的讨论,简单的记录一下!o(* ̄▽ ̄*)ブ

1.  * , How to add extra info to copied web text

2.  黑客派,https://hacpai.com/article/1510544423932

第一条使用两种方法对文章进行粘贴追加信息~~~

方法一:

①监听copy事件,然后将隐藏盒子中的信息添加到其中;

②结合window.selection()方法;

③浏览器兼容情况是主流浏览器IE8以上;

④线上demo http://jsfiddle.net/jp6nhmxf/ ;

⑤使用:复制一段文本再粘贴就会出现 pagelink中的内容 。

主要JS code

   function addLink() {
//Get the selected text and append the extra info
var selection = window.getSelection(),
pagelink = '\n\n Read more at: ' + document.location.href,
copytext = selection + pagelink,
newdiv = document.createElement('div'); //hide the newly created container
newdiv.style.position = 'absolute';
newdiv.style.left = '-99999px'; //insert the container, fill it with the extended text, and define the new selection
document.body.appendChild(newdiv);
newdiv.innerHTML = copytext;
selection.selectAllChildren(newdiv); window.setTimeout(function () {
document.body.removeChild(newdiv);
}, 100);
} document.addEventListener('copy', addLink);

方法二:

①监听copy事件,然后修改剪贴板中的内容,也就是clipboard使用;

②结合window.clipboardData.setData()方法;

③浏览器兼容情况是IE4以上(换言之只针对于IE);

④线上demo http://jsfiddle.net/m56af0je/ (IE模式下起效);

主要JS code

    function addLink(event) {
event.preventDefault(); var pagelink = '\n\n Read more at: ' + document.location.href,
copytext = window.getSelection() + pagelink; if (window.clipboardData) {
window.clipboardData.setData('Text', copytext);
}
} document.addEventListener('copy', addLink);

⑤另外疑问点来了,使用clipboard能在其他浏览器(比如谷歌/火狐/safari)中工作吗?

主要JS code

 function addLink(event) {
event.preventDefault(); var pagelink = '\n\n Read more at: ' + document.location.href,
copytext = window.getSelection() + pagelink; (event.clipboardData || window.clipboardData).setData('Text', copytext);
} document.addEventListener('copy', addLink);

区别在 window.clipboarddata  <-->  event.clipboardData

亲测在兼容模式、极速模式、谷歌、火狐、IE等浏览器中均测有效!

第二条使用的方法跟第一条类似~~~

主要JS code

 /**
* @description 添加版权
*/
const addCopyright = () => {
const genCopy = () => {
return [
'',
'',
'作者:Vanessa',
'链接 [文章复制添加版权](https://hacpai.com/article/1510544423932) ',
'来源:黑客派',
'著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。',
]
} $('.content-reset').on('copy', function (event) {
if (!window.getSelection) {
return
} let copyString = window.getSelection().toString() if (copyString.length < 128) {
return
} if ('object' === typeof event.originalEvent.clipboardData) {
event.originalEvent.clipboardData.setData('text/html', copyString + genCopy().join(''))
event.originalEvent.clipboardData.setData('text/plain', copyString + genCopy().join('\n'))
event.preventDefault()
return
} $('body').append(`${copyString}${genCopy().join('')}`)
window.getSelection().selectAllChildren($('#pipeFixCopy')[0])
setTimeout(function() {
$('#pipeFixCopy').remove()
}, 200)
})
}

找一个空白地方复制粘贴测试,~~本人只在极速模式下测通过,其他未测~~

敬请留意~~

~~~抱拳撒花*★,°*:.☆( ̄▽ ̄)/$:*.°★* 。~~~