FireFox, Safari 및 Chrome을 사용하여 클립 보드에 텍스트 복사 / 붙여 넣기
Internet Explorer에서 clipboardData 객체를 사용하여 클립 보드에 액세스 할 수 있습니다. FireFox, Safari 및 / 또는 Chrome에서 어떻게 할 수 있습니까?
이제는 최신 브라우저에서 쉽게 사용할 수있는 방법이 있습니다.
document.execCommand('copy');
현재 선택된 텍스트가 복사됩니다. 다음을 사용하여 textArea 또는 입력 필드를 선택할 수 있습니다
document.getElementById('myText').select();
보이지 않는 텍스트를 복사하려면 textArea를 빠르게 생성하고 상자에서 텍스트를 수정하고 선택한 다음 복사 한 다음 textArea를 삭제할 수 있습니다. 대부분의 경우이 textArea는 화면에 깜박이지 않습니다.
보안상의 이유로 브라우저는 사용자가 어떤 종류의 조치 (예 : 단추 클릭)를 수행하는 경우에만 복사를 허용합니다. 이를 수행하는 한 가지 방법은 텍스트를 복사하는 메소드를 호출하는 html 버튼에 onClick 이벤트를 추가하는 것입니다.
전체 예는 다음과 같습니다
<html>
<head>
<title>copy test</title>
</head>
<body>
<button onclick="copier()">Copy</button>
<textarea id="myText">Copy me PLEASE!!!</textarea>
<script>
function copier(){
document.getElementById('myText').select();
document.execCommand('copy');
}
</script>
</body>
</html>
보안상의 이유로 Firefox에서는 클립 보드에 텍스트를 배치 할 수 없습니다. 그러나 Flash를 사용하면 해결 방법이 있습니다.
function copyIntoClipboard(text) {
var flashId = 'flashId-HKxmj5';
/* Replace this with your clipboard.swf location */
var clipboardSWF = 'http://appengine.bravo9.com/copy-into-clipboard/clipboard.swf';
if(!document.getElementById(flashId)) {
var div = document.createElement('div');
div.id = flashId;
document.body.appendChild(div);
}
document.getElementById(flashId).innerHTML = '';
var content = '<embed src="' +
clipboardSWF +
'" FlashVars="clipboard=' + encodeURIComponent(text) +
'" width="0" height="0" type="application/x-shockwave-flash"></embed>';
document.getElementById(flashId).innerHTML = content;
}
유일한 단점은 플래시를 활성화해야한다는 것입니다.
소스는 현재 죽었습니다 : http://bravo9.com/journal/copying-text-into-the-clipboard-with-javascript-in-firefox-safari-ie-opera-292559a2-cc6c-4ebf-9724-d23e8bc5ad8a/ ( 그래서 그것의 인 구글 캐시 )
온라인 스프레드 시트는 Ctrl + C, Ctrl + V 이벤트를 연결하고 숨겨진 TextArea 컨트롤로 포커스를 옮기고 복사를 위해 원하는 새 클립 보드 내용으로 내용을 설정하거나 붙여 넣기가 끝난 후에 내용을 읽습니다.
또한 참조 는 자바 스크립트를 사용하여 파이어 폭스, 사파리와 크롬에서 클립 보드를 읽을 수 있습니까?
2015 년 여름이며 플래시를 둘러싼 혼란이 너무 많아서이 질문에 전혀 사용하지 않는 새로운 답변을 추가 할 것이라고 생각했습니다.
clipboard.js 는 텍스트 또는 html 데이터를 클립 보드에 복사 할 수있는 유용한 유틸리티입니다. 사용하기가 매우 쉽습니다. .js를 포함시키고 다음과 같이 사용하십시오.
<button id='markup-copy'>Copy Button</button>
<script>
document.getElementById('markup-copy').addEventListener('click', function() {
clipboard.copy({
'text/plain': 'Markup text. Paste me into a rich text editor.',
'text/html': '<i>here</i> is some <b>rich text</b>'
}).then(
function(){console.log('success'); },
function(err){console.log('failure', err);
});
});
</script>
2017 년 에이 작업을 수행 할 수 있습니다 (이 스레드는 거의 9 세이기 때문에 이것을 말합니다!)
function copyStringToClipboard (string) {
function handler (event){
event.clipboardData.setData('text/plain', string);
event.preventDefault();
document.removeEventListener('copy', handler, true);
}
document.addEventListener('copy', handler, true);
document.execCommand('copy');
}
그리고 지금 복사 copyStringToClipboard('Hello World')
setData
라인 을 발견하고 다른 데이터 유형을 설정할 수 있는지 궁금하다면 대답은 예입니다.
Firefox에서는 클립 보드에 데이터를 저장할 수 있지만 보안상의 영향으로 기본적으로 비활성화되어 있습니다. Mozilla Firefox 기술 자료의 "클립 보드에 JavaScript 액세스 권한 부여" 에서이를 활성화하는 방법을 참조하십시오 .
많은 사용자가 있고 브라우저 구성이 옵션이 아닌 경우 amdfan에서 제공하는 솔루션이 가장 좋습니다. 사용자가 기술에 정통한 경우 클립 보드를 사용할 수 있는지 테스트하고 설정을 변경하기위한 링크를 제공 할 수 있습니다. JavaScript 편집기 TinyMCE 는이 접근법을 따릅니다.
copyIntoClipboard () 함수는 Flash 9에서 작동하지만 Flash Player 10 릴리스로 인해 중단 된 것으로 보입니다. 다음은 새 Flash Player에서 작동하는 솔루션입니다.
http://bowser.macminicolo.net/~jhuckaby/zeroclipboard/
복잡한 솔루션이지만 작동합니다.
이 솔루션 중 어느 것도 실제로 작동 하지 않는다고 말해야합니다 . 허용 된 답변에서 클립 보드 솔루션을 시도했지만 Flash Player 10에서는 작동하지 않습니다. ZeroClipboard도 시도했으며 잠시 동안 매우 만족했습니다.
나는 현재 내 사이트 ( http://www.blogtrog.com )에서 사용하고 있지만 이상한 버그를 발견했습니다. ZeroClipboard가 작동하는 방식은 보이지 않는 플래시 객체를 페이지의 요소 위에 놓는 것입니다. 사용자가 창 크기를 조정하고 올바르게 정렬 된 경우와 같이 요소가 이동하면 ZeroClipboard 플래시 객체가 엉망이되어 더 이상 객체를 덮지 않습니다. 아마도 원래 위치에 여전히 앉아있을 것입니다. 그것들은 그것을 막거나 요소에 다시 붙이는 코드를 가지고 있지만 잘 작동하지 않는 것 같습니다.
따라서 ... BlogTrog의 다음 버전에서는 야생에서 본 다른 모든 코드 형광펜을 사용하여 클립 보드에 복사 버튼을 제거합니다. :-(
(dp.syntaxhiglighter의 Copy to Clipboard도 이제 깨졌습니다.)
너무 오래된 질문이지만 어디에서 나이 답변을 보지 못했습니다 ...
이 링크를 확인하십시오 :
http://kb.mozillazine.org/Granting_JavaScript_access_to_the_clipboard
모두가 말했듯이 보안상의 이유로 기본적으로 비활성화되어 있습니다. 위의 링크는 활성화 방법에 대한 지침을 보여줍니다 (firefox 또는 user.js에서 about : config를 편집하여).
다행히도 "AllowClipboardHelper"라는 플러그인이있어 몇 번의 클릭만으로 쉽게 작업 할 수 있습니다. 그러나 여전히 웹 사이트 방문자에게 firefox에서 액세스를 활성화하는 방법을 알려 주어야합니다.
필자는 Github의 Clippy 를 간단한 플래시 기반 버튼으로 사용했습니다. 스타일링이 필요하지 않고 미리 서버 측에 붙여 넣을 내용을 넣는 것에 만족한다면 제대로 작동 합니다.
최신 document.execCommand ( "copy") 및 jQuery를 사용하십시오. 이 stackoverflow 답변을 참조하십시오
var ClipboardHelper = { // as Object
copyElement: function ($element)
{
this.copyText($element.text())
},
copyText:function(text) // Linebreaks with \n
{
var $tempInput = $("<textarea>");
$("body").append($tempInput);
$tempInput.val(text).select();
document.execCommand("copy");
$tempInput.remove();
}};
전화하는 방법 :
ClipboardHelper.copyText('Hello\nWorld');
ClipboardHelper.copyElement($('body h1').first());
// JQUERY DOCUMENT
;(function ( $, window, document, undefined ) {
var ClipboardHelper = {
copyElement: function ($element)
{
this.copyText($element.text())
},
copyText:function(text) // Linebreaks with \n
{
var $tempInput = $("<textarea>");
$("body").append($tempInput);
//todo prepare Text: remove double whitespaces, trim
$tempInput.val(text).select();
document.execCommand("copy");
$tempInput.remove();
}
};
$(document).ready(function()
{
var $body=$('body');
$body.on('click', '*[data-copy-text-to-clipboard]', function(event)
{
var $btn=$(this);
var text=$btn.attr('data-copy-text-to-clipboard');
ClipboardHelper.copyText(text);
});
$body.on('click', '.js-copy-element-to-clipboard', function(event)
{
ClipboardHelper.copyElement($(this));
});
});
})( jQuery, window, document );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<span data-copy-text-to-clipboard=
"Hello
World">
Copy Text
</span>
<br><br>
<span class="js-copy-element-to-clipboard">
Hello
World
Element
</span>
Flash 솔루션에서 약간의 개선은 swfobject를 사용하여 플래시 10을 감지하는 것입니다.
http://code.google.com/p/swfobject/
플래시 10으로 표시되면 javascript를 사용하여 Shockwave 객체를로드 해보십시오. Shockwave는 lingo에서 copyToClipboard () 명령을 사용하여 클립 보드 (모든 버전)를 읽고 쓸 수 있습니다.
http://www.rodsdot.com/ee/cross_browser_clipboard_copy_with_pop_over_message.asp 는 Flash 10 및 모든 Flash 지원 브라우저에서 작동합니다.
Also ZeroClipboard has been updated to avoid the bug mentioned about page scrolling causing the Flash movie to no longer be in the correct place.
Since that method "Requires" the user to click a button to copy this is a convenience to the user and nothing nefarious is occurring.
If you support flash you can use https://everyplay.com/assets/clipboard.swf and use the flashvars text to set the text
https://everyplay.com/assets/clipboard.swf?text=It%20Works
Thats the one i use to copy and you can set as extra if doesn't support these options you can use :
For Internet Explorer: window.clipboardData.setData(DataFormat, Text) and window.clipboardData.getData(DataFormat)
You can use the DataFormat's Text and Url to getData and setData.
And to delete data:
You can use the DataFormat's File, HTML, Image, Text and URL. PS: You Need To Use window.clipboardData.clearData(DataFormat);
And for other thats not support window.clipboardData and swf flash files you can also use control + c button on your keyboard for windows and for mac its command + c
From addon code:
In case anyone else was looking for how to do it from chrome code, you can use the nsIClipboardHelper interface as described here: https://developer.mozilla.org/en-US/docs/Using_the_Clipboard
Use document.execCommand('copy')
. Supported in the latest versions of Chrome
, Firefox
, Edge
, and Safari
.
function copyText(text){
function selectElementText(element) {
if (document.selection) {
var range = document.body.createTextRange();
range.moveToElementText(element);
range.select();
} else if (window.getSelection) {
var range = document.createRange();
range.selectNode(element);
window.getSelection().removeAllRanges();
window.getSelection().addRange(range);
}
}
var element = document.createElement('DIV');
element.textContent = text;
document.body.appendChild(element);
selectElementText(element);
document.execCommand('copy');
element.remove();
}
var txt = document.getElementById('txt');
var btn = document.getElementById('btn');
btn.addEventListener('click', function(){
copyText(txt.value);
})
<input id="txt" value="Hello World!" />
<button id="btn">Copy To Clipboard</button>
try creating a memory global variable storing the selection, then the other function can access the variable and do a paste for example..
var memory = '';//outside the functions but within the script tag.
function moz_stringCopy(DOMEle,firstPos,secondPos) {
var copiedString = DOMEle.value.slice(firstPos, secondPos);
memory = copiedString;
}
function moz_stringPaste(DOMEle, newpos) {
DOMEle.value = DOMEle.value.slice(0,newpos) + memory + DOMEle.value.slice(newpos);
}
Clipboard API is designed to supersede document.execCommand
. Safari is still working on support so you should provide a fallback until spec settles and Safari finishes implementation.
const permalink = document.querySelector('[rel="bookmark"]');
const output = document.querySelector('output');
permalink.onclick = evt => {
evt.preventDefault();
window.navigator.clipboard.writeText(
permalink.href
).then(() => {
output.textContent = 'Copied';
}, () => {
output.textContent = 'Not copied';
});
};
<a href="https://stackoverflow.com/questions/127040/" rel="bookmark">Permalink</a>
<output></output>
For security reasons clipboard Permissions
may be necessary to read and write from the clipboard. If the snippet doesn't work on SO give it a shot on localhost
or an otherwise trusted domain.
'programing tip' 카테고리의 다른 글
메이븐 빌드에서 junit 테스트를 병렬로 실행합니까? (0) | 2020.08.02 |
---|---|
스칼라 배우 : 수신 대 반응 (0) | 2020.08.02 |
iOS 버전 통계는 어디서 찾을 수 있습니까? (0) | 2020.08.02 |
img 태그가 잘못된 방향을 표시합니다 (0) | 2020.08.02 |
빌드 도구 란 무엇입니까? (0) | 2020.08.02 |