Button to copy html from page

Asked

Viewed 5,730 times

1

I need to provide a button where users will just click and copy all the code that was used to develop that page.

I’ve seen a lot of similar questions, but none of them have solved my problem. It would be basically like this, imagine that the code example below corresponds to the page I need to copy:

  <div class="conteudo-total">       
       <div>
           <h1>Titulo</h1>
           <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aperiam laboriosam inventore blanditiis repellendus corrupti, ea, maxime magnam odio, vero consequatur, dolores hic. Accusantium voluptatem nulla velit, deserunt sequi eveniet debitis.</p>
       </div>       
 </div>   
 <div class="copiar">Copiar Código</div>

When you click Copiar Código I need to copy all content html, that is, the entire contents of the file. I know it would be much simpler to go into the archive and copy the code directly from there, but it is an indispensable requirement that it be through a button...

  • Can use JQuery?

  • Yes, I even tried some jQuery shapes, but I couldn’t.

  • Yeah, but, hey? It’s gonna stick where that?

  • 1

    if it’s just the html css and js of the page you can use var code = Document.body.innerHTML;

  • Julio Henrique, will be pasted in other projects, for being a model page

  • Good, Anderson, I hadn’t thought of it. But you would know how to copy the contents of this variable code, as if it were a Ctrl+c?

Show 1 more comment

2 answers

4


I made a feature to copy the HTML of the current page through the button, but depending on the browser, some 'garbage' is generated in the compilation, mainly in the opera, in the chrome and in the mozilla is quiet, and locally is perfect, in case I discover how to remove this type of imperfection edit the answer, follows the function...

function copiarHTML() {
        let copyText = document.getElementsByTagName("html")[0];
        let input = document.createElement("input");
        input.id = "inp";
        input.value = copyText.outerHTML;
        copyText.appendChild(input);
        
        let copy = document.getElementById('inp');
        copy.select();
        document.execCommand("Copy");
        alert("O texto copiado foi: " + copy.value);
        
        copyText.removeChild(input);

        let textArea = document.createElement('textarea');
        textArea.cols = "80";
        textArea.rows = "40";
        textArea.placeholder = "Pressione Ctrl+v aqui";

        copyText.appendChild(textArea);
        }
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Copiar HTML</title>
</head>
<body>
    <button onclick="copiarHTML()">
        Copiar HTML
    </button>
</body>
</html>

  • 1

    That’s just what I needed, thank you very much!

  • and if you detect if the browser is opera?

1

With pure javascript

function copiarHtml() {
    var x = document.getElementsByTagName("html")[0];
    var z = x.outerHTML;
    document.getElementById("demo").innerHTML = z;
    document.getElementById("demo").select();
    document.execCommand('copy');
}
    //para fora da viewport
    #demo{
      position :absolute;
      top: -1000px;
      left: -1000px;
    }
<button onclick="copiarHtml()">Copiar HTML</button>

<textarea id="demo"></textarea>
<br>
<textarea placeholder="cole aqui"></textarea>

With Jquery

$('button').click(function(){
  var txt = document.getElementsByTagName("html")[0];

  $('textarea.hide').text( txt.outerHTML) ;
  $("textarea.hide").select();
  document.execCommand('copy');
});
//para fora da viewport
textarea.hide{
  position :absolute;
  top: -1000px;
  left: -1000px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button>Copie meu html</button>
<br />
<textarea class="hide"></textarea>

<textarea placeholder="cole aqui"></textarea>

With PHP

Library

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

CSS

<style type="text/css">
//para fora da viewport
.hide {
    position: absolute;
    top: -1000px;
    left: -1000px
}
</style>

SCRIPT

<script language="javascript">
$(document).ready(function() {
    $("button").click(function(){
        $("textarea").select();
        document.execCommand('copy');
    });
});
</script>

PHP + HTML

<?php
    // Lê todo o conteúdo de um arquivo
    $html = file_get_contents("Nome_do_arquivo_para_ler");

    $html = htmlentities($html);

    echo "<textarea class='hide'>". $html ."</textarea>";

?>

<button>Copie meu html</button>

Since Copying text from hidden elements does not work (browser security limitation), all of the above examples use the technique “off -left” (described in Screenreadervisibility in css-discuss Wiki), which involves absolute positioning of the hidden element out of the viewport.

However, it is possible to copy text from hidden elements using the following technique:

Comments on the code itself

var copyBtn   = $("#copy-btn"),
textarea     = $("#copy-me");
    //conteúdo do arquivo
    var x = document.getElementsByTagName("html")[0];
    var z = x.outerHTML;
    document.getElementById("copy-me").innerHTML = z;

function copyToClipboard() {
  var success   = true,
      range     = document.createRange(),
      selection;

  // IE.
  if (window.clipboardData) {
    window.clipboardData.setData("Text", textarea.val());        
  } else {
    // Crie um elemento temporário fora da tela.
    var tmpElem = $('<div>');
    tmpElem.css({
      position: "absolute",
      left:     "-1000px",
      top:      "-1000px",
    });
    // Adicione o valor de entrada ao elemento temporário
    tmpElem.text(textarea.val());
    $("body").append(tmpElem);
    //Selecione o elemento temporario.
    range.selectNodeContents(tmpElem.get(0));
    selection = window.getSelection ();
    selection.removeAllRanges ();
    selection.addRange (range);
    // Permite copiar.
    try { 
      success = document.execCommand ("copy", false, null);
    }
    catch (e) {
      copyToClipboardFF(textarea.val());
    }
    if (success) {
      alert ("O código fonte desta página está na área de transferência, cole-o!");
      // remove o elemento temporario.
      tmpElem.remove();
    }
  }
}

copyBtn.on('click', copyToClipboard);
#copy-me {
    display:none
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea name="" id="copy-me"/></textarea>
<button id="copy-btn">Copiar HTML</button><br/><br/>
<textarea placeholder="cole aqui"></textarea>

Source - by brother Daviddomain

Browser other questions tagged

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