JavaScript复制网页内容自带版权信息

Uiaoin 2019-04-30 3355

博主在IE11、Chrome、搜狗浏览器上亲测可用,直接上代码

  1. ;(function () {
  2. function _copyRight(options){
  3. //Get Selected Text
  4. var text_copy = ''
  5. if (document.Selection){
  6. //IE
  7. text_copy = document.selection.createRange().text
  8. }else {
  9. text_copy = window.getSelection().toString()
  10. }
  11. //Text Length Limit
  12. if (typeof options.limit !== 'undefined' && text_copy.length < options.limit){
  13. return
  14. }
  15. var _title = '<br /><br />文字来源:' + options.source
  16. var _author = '<br />作者:' + options.author
  17. var _link = '<br />原文链接:' + location.href
  18. var _description = '<br />申明:' + options.description
  19. var selection = window.getSelection()
  20. var div = document.createElement('div')
  21. div.innerHTML = text_copy + _title + _author + _link + _description
  22. document.body.appendChild(div)
  23. selection.selectAllChildren(div)
  24. setTimeout(function () {
  25. document.body.removeChild(div)
  26. },50)
  27. //CallBack Function
  28. if (typeof options.callback !== 'undefined'){
  29. options.callback()
  30. }
  31. }
  32. window.$u = {
  33. copyRight: _copyRight
  34. }
  35. return $u
  36. })()


调用

  1. document.body.oncopy = function () {
  2.     $u.copyRight({
  3.         source: '徐啸林的个人博客',
  4.         author: '徐啸林',
  5.         description: '著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。',
  6.         limit: 100,
  7.         callback: function () {
  8. //提醒复制成功
  9. globalAlert('Copy Successfully')
  10.         }
  11.     })
  12. }


注意:IE11下用document.oncopy会失败!

当然申明一下,主要目的不是为了不让人家复制,重在学习!

加载更多