更新时间:2023-12-05 18:38:10
(在几种可能的方法中)你可以达到你想要的效果:
(Among several possible approaches) you can achieve what you want like this:
chrome.tabs.executeScript()
将一些代码注入选项卡的网页。chrome.tabs.executeScript()
to inject some code into the tab's web-page.
以下是示例扩展程序的源代码确切地说:
Below is the source code of a sample extension that does exactly that:
在 maifest.json :
In 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 :
In 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 :
In 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();
}
});
});