How to copy attr from page to clipboard with Javascript?

Asked

Viewed 564 times

2

Has a page element (attr) I want to copy to clipboard (Ctrl+C) automatically whenever I enter it. I have already been able to find it with Jquery. On the page it’s like this:

<div class="image-constrain js-image-wrap image-constrain_zoommed">
    <img class="image__pic js-image-pic" src="https://ig.img.com/image/E0SlHdTiS-SLAGDD3o3aOw.png" alt="" id="screenshot-image" image-id="gqgn5p">
</div>

In the script it’s like this:

var divACopiar = $('.image-constrain').find('img').attr('src');

Put to display on console it shows like this:

https://ig.img.com/image/E0SlHdTiS-SLAGDD3o3aOw.png

I just couldn’t find commands that would work for my need, even here in community responses.

1 answer

3


You cannot set directly to the clipboard, first you have to create any hidden field, remembering that it will not work if it is of type Hidden, or with the display:None property, width:0 or height:0, for example:

<input id="temp" type="text" name="temp" value="">

To hide use this css:

#temp{
  opacity: 0;
  filter: alpha(opacity=0);
  width:1px;
  height:1px;
}

Then you set the value in this field:

$('#temp').val('O que vai ficar na area de transferencia');

Now you select the text of the field:

$('#temp').select();

Ay yes, you play to the clipboard:

document.execCommand('copy');

I made an example for you to understand better: https://jsfiddle.net/wictor/tyLnu67a/2/

Html:

<input id="temp" type="text" name="temp" value="">
<input id="botao" type="button" value="Enviar">

Css:

#temp{
  opacity: 0;
  filter: alpha(opacity=0);
  width:1px;
  height:1px;
}

Jquery:

$(function(){
    $('#botao').click(function(){
        $('#temp').val('O que vai fioicar na area de transferenciddda');
      $('#temp').select();
      document.execCommand('copy');
  });
});
  • 1

    +1. However... this type of concealment may be considered an attack and will eventually be prohibited by the browsers, so be advised to those who implement. It is recommended to make it clear to the user what will be copied to the clipboard. Other than that, perfect response.

  • That’s what I was looking for, Wictor! Very good! Thanks for the clarifications, guys!!! And aware of the risk @Renan. ;)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.