How to copy attr from page to clipboard with JavaScript?

2

It has an element of a page ( attr ) that I want to copy to Clipboard (Ctrl + C) automatically every time I enter it. I've been able to fetch it with JQuery. It looks like this on the page:

<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 looks like this:

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

Putting it to display in console it looks like this:

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

I just did not find any commands that worked for my need, even here in the community responses.

    
asked by anonymous 27.09.2017 / 23:15

1 answer

3

You can not set directly to the clipboard, first you have to create a hidden field any, remembering that it will not work if it is of type hidden, or with the property display: none, 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 field text:

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

Yes, you play on the clipboard:

document.execCommand('copy');

I've set an example for you to better understand: link

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');
  });
});
    
27.09.2017 / 23:51