[英]Chrome Extension Highlighted Text selection chrome.tabs
我在使用chrome擴展程序時遇到了麻煩。 我具有“標簽”權限,但是我不知道如何在沒有<背景頁的情況下檢索頁面上的選定文本。 <----我改變了主意,可以擁有背景頁面。
這是腳本:
var code = document.getSelection()。toString();
document.getElementsById(“ q”)。value =代碼;
我已經放置了chrome.executeCommand
方法(不記得該方法的方向),但是那也不起作用。 安裝此擴展程序時,我不希望有后台頁面來防止延遲。 當我有背景時,它可能不會浪費太多時間,但是每一點都很重要。 另外,基本上,我的擴展程序將涉及便攜式Google It! 擴展名,如果您突出顯示/選擇文本,它將自動設置輸入字段的值。 單擊https://www.dropbox.com/sh/c7q2puadva2vojf/GsuwWcXHjr查看到目前為止的進度!
(在幾種可能的方法中)您可以實現所需的目標:
chrome.tabs.executeScript()
將一些代碼注入該標簽的網頁中。 下面是一個示例擴展的源代碼,正是這個示例:
在maifest.json中 :
{
"manifest_version": 2,
"name": "Test Extension",
"version": "0.0",
"browser_action": {
"default_title": "Test Extension",
"default_popup": "popup.html"
},
"permissions": [
"<all_urls>"
],
}
在popup.html中 :
<!DOCTYPE html>
<html>
<head>
<title>Google It!</title>
<script type="text/javascript" src="popup.js"></script>
</head>
<body>
<input type="text" id="inp" size="20" placeholder="Search query..." />
<br />
<input type="button" id="btn" value="Google It!" />
</body>
</html>
在popup.js中 :
/* The URL for the Google search */
var google = 'http://google.com/#q=';
/* The function that finds and returns the selected text */
var funcToInject = function() {
var range = window.getSelection().getRangeAt(0);
var selectedText = range.cloneContents().textContent;
return selectedText;
};
/* This line converts the above function to string
* (and makes sure it will be called instantly) */
var jsCodeStr = ';(' + funcToInject + ')();';
window.addEventListener('DOMContentLoaded', function() {
/* Find our input elements from `popup.html` */
var inp = document.querySelector('input[type="text"]#inp');
var btn = document.querySelector('input[type="button"]#btn');
/* Open a new tab with the search results */
btn.addEventListener('click', function() {
var query = encodeURIComponent(inp.value);
chrome.tabs.create({ url: google + query });
});
/* Inject the code into all frames of the active tab */
chrome.tabs.executeScript({
code: jsCodeStr,
allFrames: true
}, function(selectedTextPerFrame) {
if (chrome.runtime.lastError) {
/* Report any error */
alert('ERROR:\n' + chrome.runtime.lastError.message);
} else if ((selectedTextPerFrame.length > 0)
&& (typeof(selectedTextPerFrame[0]) === 'string')) {
/* The results are as expected,
* populate the "search-query" input field */
inp.value = selectedTextPerFrame[0].trim();
}
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.