Javascript - copy all html code into clipboard

荒凉一梦 提交于 2021-02-08 10:31:00

问题


I am making an app which has to check an information from a special webpage. What I need to do is to pass the html content from this page to my existing program, and it does all the rest.

The website where I get the data works in IE8 and newer, so it kinda narrows the problem. I need to make an extension for IE which could copy ALL the html code from the page it has been called from (and save it into a .txt, in the best case), so result would be as on the example:

<html>
<body>
Hello world
</body>
</html>

I know how to make such extensions, the only problem is javascript: I am a newbie. Are there any short solutions for this problem?


回答1:


There are many options available

1) using XMLSerializer

var Source = new XMLSerializer().serializeToString(document);

2)

   document.documentElement.outerHTML
   or

   document.documentElement.innerHTML



回答2:


Reference from here

function copyTextToClipboard(text) {
  var textArea = document.createElement("textarea");
  textArea.style.position = 'fixed';
  textArea.style.top = 0;
  textArea.style.left = 0;
  textArea.style.width = '2em';
  textArea.style.height = '2em';
  textArea.style.padding = 0;
  textArea.style.border = 'none';
  textArea.style.outline = 'none';
  textArea.style.boxShadow = 'none';
  textArea.style.background = 'transparent';
  textArea.value = text;
  document.body.appendChild(textArea);
  textArea.select();
  try {
    var successful = document.execCommand('copy');
    var msg = successful ? 'successful' : 'unsuccessful';
    console.log('Copying text command was ' + msg);
  } catch (err) {
    console.log('Oops, unable to copy');
  }
  document.body.removeChild(textArea);
}
$(document).ready(function() {
  $("#btnDate").click(function() {
    var allHTML = document.documentElement.outerHTML;
    copyTextToClipboard(allHTML);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button type="button" id="btnDate" class="btn btn-primary">Copy HTML
</button>


来源:https://stackoverflow.com/questions/32435161/javascript-copy-all-html-code-into-clipboard

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!