2015-12-03 54 views
0

我需要做一個按鈕,將工作在每一個頁面和瀏覽器,可以複製文本區域的輸入。我想用下面的函數來做到這一點:複製到剪貼板在mozzila firefox純粹的JavaScript功能

selectElementContents: function(){ 
     el = document.getElementById("tag_text"); 

     var range = document.createRange(); 
     range.selectNode(el); 
     window.getSelection().removeAllRanges(); 
     window.getSelection().addRange(range); 

     try { 
     var successful = document.execCommand('copy'); 
     } catch(err) { 
     console.log('Oops, unable to copy'); 
     } 

這是目前除Firefox和Safari瀏覽器都工作正常。我讀了一些關於Safari的內容,似乎它不支持這種功能,或者我誤會了?但是,當我嘗試使用document.execCommand('copy')複製輸入內容時,它會引發以下錯誤:[Exception... "Failure" nsresult: "0x80004005 (NS_ERROR_FAILURE)" location: "JS frame :: debugger eval code :: <TOP_LEVEL> :: line 1" data: no]。我查了這個錯誤,它是一種通用的,因爲代碼出現在多個錯誤中。

最後我的問題是如何使它在Firefox上工作,出了什麼問題?

+0

這可能有助於http://stackoverflow.com/questions/21696052/copy-to-clipboard-with-javascript-in-firefox – vidriduch

+0

我不能創建一個插件。此功能必須適用於銷售產品的每個網站。 –

+0

netscape.security.PrivilegeManager。 vidriduch你知道那是什麼嗎? –

回答

2

不幸的是,execCommand('copy')在任何地方都不受支持。它也不是非常安全,因爲它將東西放入剪貼板而不提醒用戶。

HTML:

<form id="test_form"> 
    <p>Copy this:</p> 
    <input id="tag_text" type="text" size="40" /> 
    <input type="button" onClick="select_element_contents()" value="Copy" /> 
</form> 

的Javascript:

在任何情況下,你可以在這個answer對於不支持的瀏覽器提出這樣的解決方案將execCommand( '複製')相結合

function select_element_contents(){ 
    var el = document.getElementById("tag_text"); 
    var el_text = el.value; 

    var range = document.createRange(); 
    range.selectNode(el); 
    window.getSelection().removeAllRanges(); 
    window.getSelection().addRange(range); 

    try { 
     var successful = document.execCommand('copy'); 
    } catch(err) { 
     window.prompt("Copy to clipboard: Ctrl+C/Cmd+C, Enter", el_text); 
    } 
} 

當然這並不理想,但由於Mozilla Firefox不支持自動複製到剪貼板,用戶將不得不按下按鈕。不妨儘可能透明。