关于javascript:将文本从小书签复制到剪贴板

Copy text to clipboard from bookmarklet

我正在尝试编写一个小书签,可以从活动页面中提取一些文本并将其加载到剪贴板中。

提取很容易,但是我真的很困于剪贴板复制部分。 目前,我只是alert输入文本,然后单击Ctrl + C从消息框中复制文本,这并不理想。

我已经阅读了《如何使用JavaScript复制到剪贴板》以及其他一些建议我使用zeroclipboard的问题,但是考虑到必须加载外部Flash和javascript资源才能使用,我不知道如何通过书签实现该功能。 图书馆。

考虑到这只是一个私人书签,我不会弄乱页面的DOM来完成此操作,也不必在浏览器(Google Chrome)上启用某些权限,所以我没有任何问题。

任何指针将不胜感激。


Github Gist有一个不错的小书市,可完成您想要的核心工作-复制到剪贴板。它不使用任何外部库,我认为这是一个优势。

在编写时,它会复制一些静态文本,但是在底部,它讨论将其适应其他用途,例如复制页面标题。

既然您已经说过"提取很容易...",那么您应该能够轻松地使要点适应您想要做的事情。

我尝试了普通的香草版本的bookmarklet,因为我经常需要将一些静态文本传输到剪贴板。无需修改即可在Chrome 61中很好地运行。但是请确保您已阅读评论;有些人对如何使其在其他浏览器和方案中正常运行提出了建议。

这是我测试过的代码,已经缩小并且可以转换为小书签:

1
javascript:!function(a){var b=document.createElement("textarea"),c=document.getSelection();b.textContent=a,document.body.appendChild(b),c.removeAllRanges(),b.select(),document.execCommand("copy"),c.removeAllRanges(),document.body.removeChild(b)}("Text To Copy");

吉斯特(Gist)也具有预先缩小的代码。


这就是我使用答案中提到的@zzzzBov技术通过书签将Zeroclipboard导入页面的方法。

当书市运行时,手形光标会悬停在身体??的任何位置。单击会将文档标题复制(例如)到剪贴板。

(指向零剪贴板资源的链接已替换为占位符,并且由于Chrome似乎正在删除小书签(或其他内容)中的所有换行符,因此已使用多行注释。)

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
javascript:

var s = document.createElement('script');
s.setAttribute('src', 'http://example.com/ZeroClipboard.js');

s.onload = s.onreadystatechange =
  function()
  {
     ZeroClipboard.setMoviePath( 'http://example.com/ZeroClipboard.swf');
     var clip = new ZeroClipboard.Client();  

     /* glue to the body: sample only, in reality  we should
        probably create a new visible element and glue to that. */

     clip.glue(document.body);  

     clip.setHandCursor( true );

     /* copy to clipboard on mouse-up */
     clip.addEventListener('onMouseUp',
      function (client)
      {      
         /* example */
         var toCopy = document.title;        
         clip.setText(toCopy);    

         alert(toCopy + ' copied.');
         clip.hide();
      });  
   };

document.body.appendChild(s);

几个免责声明:

  • 我不是要向您发送垃圾邮件
  • 如果您选择使用此功能,我一无所获
  • 不久前,我制作了一个小书签生成器,以使我更容易创建小书签。

    它启用了jQuery,但这并不意味着您必须使用jQuery。

    您可以查看源代码,以了解如何通过书签将另一个脚本/库导入页面。

    特别是,导入jQuery的行:

    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
    if (!window.zbooks)
      {
        //if zbooks hasn't been set, initialize it

        //s used for the Script element
        var s = document.createElement('script');
        //r used for the Ready state
        var r = false;
        //set the script to the latest version of jQuery
        s.setAttribute('src', 'http://code.jquery.com/jquery-latest.min.js');
        //set the load/readystate events
        s.onload = s.onreadystatechange = function()
        {
    /**
     * LOAD/READYSTATE LOGIC
     * execute if the script hasn't been ready yet and:
     * - the ready state isn't set
     * - the ready state is complete
     *   - note: readyState == 'loaded' executes before the script gets called so
     *     we skip this event because it wouldn't have loaded the init event yet.
     */

          if ( !r && (!this.readyState || this.readyState == 'complete' ) )
          {
            //set the ready flag to true to keep the event from initializing again
            r = true;
            //prevent jQuery conflicts by placing jQuery in the zbooks object
            window.zbooks = {'jQuery':jQuery.noConflict()};
            //make a new zbook
            window.zbooks[n] = new zbooks(c);
          }
        };
        //append the jQuery script to the body
        b.appendChild(s);
      }

    希望对您有所帮助。


    在最新版本的Firefox中,由于缺少权限,通常无法通过书签与剪贴板进行交互(有关更多详细信息,请参见此信息)。但是,可能有一种方法可以使小书签显示一个按钮,并在按钮单击事件处理程序的上下文中执行剪贴板交互。

    可能更直接的解决方案是使用用户脚本管理器,并以可以通过键盘组合激活的用户脚本的形式定义小书签。例如,请参见以下用户脚本,以确保完整性:

    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
    // Add the following as a user-script (via an extension like https://github.com/violentmonkey/violentmonkey) in order to copy the
    // current webpage and selected text to the clipboard in a format suitable for pasting into an org-mode document.
    // To execute the action, you need to press Alt-C on a webpage, though this can be modified by changing the keycode
    // used in the onkeyup function.

    // ==UserScript==
    // @name Copy Org-mode Link
    // @namespace Violentmonkey Scripts
    // @match *://*/*
    // @grant clipboardWrite
    // ==/UserScript==

    function main() {
        function copyTextToClipboard(text) { var textArea = document.createElement("textarea"); textArea.style.position = 'fixed'; textArea.style.top = 0; textArea.style.left = 0; textArea.style.width = '2em'; textArea.style.height = '2em'; textArea.style.padding = 0; textArea.style.border = 'none'; textArea.style.outline = 'none'; textArea.style.boxShadow = 'none'; textArea.style.background = 'transparent'; textArea.value = text; document.body.appendChild(textArea); textArea.select(); try { var successful = document.execCommand('copy'); var msg = successful ? 'successful' : 'unsuccessful'; console.log('Copying text command was ' + msg); } catch (err) { console.log('Oops, unable to copy'); } document.body.removeChild(textArea); }; var url = encodeURIComponent(location.href); url = url.replace(/%253A/g, ':').replace(/%252F/g, '/'); var title = document.title; title = title.replace(/\\[/g, '{'); title = title.replace(/\\]/g, '}'); var sel_text = window.getSelection(); copyTextToClipboard('[['+url+']['+title+']]'+'\
    \
    '
    +sel_text);
    }

    // listen for Alt-C key-combination, and then execute
    document.onkeyup=function(e){
        var e = e || window.event; // for IE to cover IEs window object
        if(e.altKey && e.which == 67) {
             main();
             return false;
        }
    }

    答案有点不寻常:打开空白页,用户可从中复制文本:

    1
    2
    supdocument.execCommand(\'selectAll\')</html>')">
      Copy the text"
    sup"

    只需将sup替换为您要用户复制的文本即可。

    JS Bin示例


    由于有了新的Clipboard API,在支持它的浏览器中这很容易:

    1
    javascript: navigator.clipboard.writeText('some text from somewhere');null;

    注意:小书签中的任何警报或提示都将导致文档失去焦点,并且剪贴板API将变得不可用。在这种情况下,您需要先将焦点移回到文档中,然后再执行任何剪贴板操作:

    1
    2
    3
    4
    const oldFocus = document.activeElement;
    // do popup stuff
    oldFocus.focus();
    // do clipboard stuff