How to simulate ctrl + v [duplicate]

1

Is there any way to simulate a ctrl + v using JavaScript?

I want to include a button and an input. When you click the button, what is on the clipboard should appear in the input.

The code is for an HTML page that shortens links. It has only two fields: URL and link name.

My idea is for the user to copy the URL and to access the page, click the button to paste the content into the input.

    
asked by anonymous 30.08.2017 / 16:33

3 answers

6

I'll respond because I do not have access to the comments. Then I can edit this answer.

Copying clipboard content is very well protected by browsers because of security. Simulating copying content from memory can cause serious problems (imagine pasting a credit card number and sending it secretly via ajax). So, no, the way it was described is impossible.

However, it may be possible to simulate a "paste" event via code. Maybe you can think of some workarounds depending on where the information comes from. Can you provide more information?

    
30.08.2017 / 16:41
2

Extensions using WebExtension APIs

Extensions created using WebExtension APIs can interact with the system clipboard using document.execCommand (). Here is an example that would fit your case:

function paste() {
  var pasteText = document.querySelector("#inputSaida");
  pasteText.focus();
  document.execCommand("Paste");
}
    
document.querySelector("#botaoColar").addEventListener("click", paste);
<input type="text" id="inputSaida"></input>
<button id="botaoColar">Colar</button>

Here you have complete API documentation.

Lack of support (or permission) ...

Chrome does not support this by default, so you have to give clipboardRead access / permission to your manifest.js and run this function in the background, some links that can help:

30.08.2017 / 17:10
1

I do not see the need for much work , yet something that implies user security .

If you are using a link shortener of your own, you could simply resolve with session or localStorage or sessionStorage , you can even use a send via HTTP using POST or GET of the generated link, since that are all in the same domain or you have "control" over such a "link shortener".

If the link shortener is a third-party service (such as googl.gl or bitly ) you could simply use an API, generally the link shortcut services have APIs to automate the service.

Some examples:

Shorten link with googl

More "clients": link

Shortening link with bitly

More "clients": link

    
30.08.2017 / 17:33