2013-01-16 23 views
4

我花了幾個小時在Web上搜索解決方案。我想要做的是在頁面上突出顯示文本,並將其傳送到Chrome擴展程序的popup.html中的textarea。我想知道是否有人可以爲我提供可以做到這一點的擴展的建議源代碼。創建一個Chrome擴展,它將頁面上突出顯示的文本插入到popup.html文本區域中

這是我最關注的線索,我認爲這將是最有幫助的 - 查詢是類似的。 Button in popup that get selected text - Chrome extension

我試着複製代碼並將其作爲擴展名運行,它不會獲得突出顯示的文本。想知道是否有人有任何建議,以及如何解決這個問題。非常感謝你。

回答

10

就像你連接的問題的答案一樣,你需要使用Message PassingContent Scripts。該代碼已超過2年,並使用折舊方法,如onRequestgetSelected。一些簡單的修改應該足以將其更新爲新的API。

Popup.html

<!DOCTYPE html> 
<html> 
    <head> 
    <script src="jquery-1.8.3.min.js"></script> 
    <script src="popup.js"></script> 
    <style> 
     body { width: 300px; } 
     textarea { width: 250px; height: 100px;} 
    </style> 
    </head> 
    <body> 
    <textarea id="text"> </textarea> 
    <button id="paste">Paste Selection</button> 
    </body> 
</html> 

popup.js(以不具有任何內聯代碼)

$(function(){ 
    $('#paste').click(function(){pasteSelection();}); 
}); 
function pasteSelection() { 
    chrome.tabs.query({active:true, windowId: chrome.windows.WINDOW_ID_CURRENT}, 
    function(tab) { 
    chrome.tabs.sendMessage(tab[0].id, {method: "getSelection"}, 
    function(response){ 
     var text = document.getElementById('text'); 
     text.innerHTML = response.data; 
    }); 
    }); 
} 

selection.js

chrome.extension.onMessage.addListener(function(request, sender, sendResponse) { 
    if (request.method == "getSelection") 
    sendResponse({data: window.getSelection().toString()}); 
    else 
    sendResponse({}); // snub them. 
}); 

的manifest.json

{ 
"name": "Selected Text", 
"version": "0.1", 
"description": "Selected Text", 
"manifest_version": 2, 
"browser_action": { 
    "default_title": "Selected Text", 
    "default_icon": "online.png", 
    "default_popup": "popup.html" 
}, 
"permissions": [ 
    "tabs", 
    "<all_urls>" 
], 
"content_scripts": [ 
    { 
    "matches": ["<all_urls>"], 
    "js": ["selection.js"], 
    "run_at": "document_start", 
    "all_frames": true 
    } 
] 
} 

Here是源文件的鏈接。

+0

你的代碼是局部的和多幀頁面,因爲不工作var text = document.getElementById('text'); text.innerHTML = response.data;'popup.js – Sudarshan

+0

@Sudarshan我猜你沒看過這個問題,因爲我所做的只是告訴他他連接的代碼有什麼問題。 – BeardFist

+0

嗨,非常感謝你爲此付出了很多努力!我試着複製上面的代碼並將它保存爲單獨的文件,然後將它作爲打包的擴展名運行,但不幸的是,它不會拉出任何突出顯示的文本,當你運行這個時它工作正常嗎?非常感謝您的幫助! – user1982011

1

popup.js

chrome.tabs.executeScript({ 
    code: "window.getSelection().toString();" 
}, function(selection) { 
    alert(selection[0]); 
}); 

的manifest.json

"permissions": [ 
    "activeTab", 
], 

看一看這個簡單的擴展https://github.com/kelly-apollo/zdic

相關問題