2011-03-08 42 views

回答

7

在你的內容腳本,有這樣的:

// step 1: get the text you mean to copy 
// (actual implementation not included) 

// step 2: send it to your background page 
chrome.extension.sendRequest({ text: "text you want to copy" }); 

在你的背景頁,有這樣的:

// step 3: set up your background page HTML 
// and 
<html> 
<head> 
<script type="text/javascript"> 
    chrome.extension.onRequest.addListener(function (msg, sender, sendResponse) { 

     var textarea = document.getElementById("tmp-clipboard"); 

     // now we put the message in the textarea 
     textarea.value = msg.text; 

     // and copy the text from the textarea 
     textarea.select(); 
     document.execCommand("copy", false, null); 


     // finally, cleanup/close the connection 
     sendResponse({}); 
    }); 
    </script> 
    </head> 

    <body> 
    <textarea id="tmp-clipboard"></textarea> 
    </body> 
</html> 
+0

我有文字可在彈出的文本區域已經複製。我還需要使用背景頁嗎?我嘗試了doc.execCommand(「copy」,false,null);命令,但似乎並不奏效。 :S – thameera 2011-03-11 11:16:32

+0

這個問題/答案對初學者非常有用,這是一個常見問題。這個答案可以更新爲使用'sendMessage'和'onMessage'嗎? – LukeP 2015-01-11 18:47:29