How to paste on click? It works in google docs

前端 未结 3 1408
予麋鹿
予麋鹿 2020-12-02 15:58

I want to be able to initiate real paste event when user clicks. I can understand this may be a security issue, because if any webpage had access to users clipboard, that wo

3条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-02 16:07

    Custom paste works in Chrome, but only through an extension. If you look at google docs code, you'll see that without the extension installed, you can't paste. And you can try in Firefox to use the context menu paste, it'll tell you it's not available, and that you need to use CTRL+V. You can find this in google docs source code:

    Copying and pasting requires the free Google Drive web app. This lets us access your clipboard so you can cut, copy and paste.

    So it seems clear that the paste command needs an extension to work.

    One way to do it is to use execCommand('paste') which doesn't work when called from a page, but actually works in an extension content script. You only need to add clipboardRead to the manifest.json permissions, like this:

    permissions: {
        ...
        "clipboardRead"
        ...
    }
    

    Then in your content script document.execCommand('paste') will work.

    EDIT:

    As pointed by @tomas-M and @Mi-Creativity, the implementation in google docs on Chrome seems to be in Chrome itself, not in an exposed extension. Maybe this can give a clue as to where it is defined: https://code.google.com/p/chromium/codesearch#chromium/src/chrome/common/extensions/api/_permission_features.json&q=clipboardRead&sq=package:chromium&dr=C&l=164

    Hard to say if it's really the way it works, but in any case, you can 'unlock' execCommand('paste') for other site through an extension. Not very practical, but it works.

    And testing document.execCommand('paste') in console, while on google docs gives true, while on other pages it gives false, so I really think that it's how this feature is implemented in google docs.

提交回复
热议问题