I'm trying to copy all the links of a web page to clipboard. I'm trying to join all the anchor tags into a string, putting that string into a input field and then copying it by document.execCommand("copy")
but somehow document.execCommand("copy")
only works in browser developer tools. I want it to work in a script loaded in web page. Kindly Help me, Thanks in advance.
var
body = document.querySelector("body"),
input = document.createElement("textarea"),
a = document.getElementsByTagName("a"),
list = [],
anchor = document.createElement("a");
for (let i = 0; i < a.length; i++){
list.push(a[i]);
};
list = list.join("\r\n");
input.value = list;
input.setAttribute("readonly", "");
input.style = "position: absolute; left: -9999px;";
body.appendChild(input);
input.select();
document.execCommand('copy');
body.removeChild(input);
<!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>test</title>
</head>
<body>
<a href="http://ali.com">sample link</a>
<script src="script.js"></script>
</body>
</html>