3 回答

TA貢獻(xiàn)2003條經(jīng)驗 獲得超2個贊
使用content_scripts并不是一個很好的解決方案,因為它會注入包括iframe-ads等在內(nèi)的所有文檔。我在其他頁面上得到的空文本選擇比在雜亂的網(wǎng)站上預(yù)期的翻倍還多。
更好的解決方案是僅將代碼注入所選選項卡,因為無論如何這就是您選擇的文本所在的位置。jQuery Doc ready部分的示例:
$(document).ready(function() {
// set up an event listener that triggers when chrome.extension.sendRequest is fired.
chrome.extension.onRequest.addListener(
function(request, sender, sendResponse) {
// text selection is stored in request.selection
$('#text').val( request.selection );
});
// inject javascript into DOM of selected window and tab.
// injected code send a message (with selected text) back to the plugin using chrome.extension.sendRequest
chrome.tabs.executeScript(null, {code: "chrome.extension.sendRequest({selection: window.getSelection().toString() });"});
});
添加回答
舉報