您的代码存在很多问题(请参阅上面我的评论)。
首先是一些建议/考虑因素:
不要将您的内容脚本注入all网页。以编程方式注入并且仅当用户想要搜索时。
在内容脚本中进行“搜索”可能是一个更好的主意,您可以直接访问 DOM 并可以对其进行操作(例如突出显示搜索结果等)。如果您采用这种方法,您可能需要调整您的权限,但始终尝试将它们保持在最低限度(例如,不要使用tabs
where activeTab
就足够了,等等)。
请记住,一旦弹出窗口关闭/隐藏(例如选项卡获得焦点),在弹出窗口上下文中执行的所有 JS 都会中止。
如果您想要某种持久性(即使是暂时的),例如记住最近的结果或最后的搜索词,您可以使用类似的东西铬存储 or 本地存储.
最后,来自我的扩展演示版本的示例代码:
扩展文件组织:
extension-root-directory/
|
|_____fg/
| |_____content.js
|
|_____popup/
| |_____popup.html
| |_____popup.js
|
|_____manifest.json
清单.json:
{
"manifest_version": 2,
"name": "Test Extension",
"version": "0.0",
"offline_enabled": true,
"content_scripts": [
{
"matches": [
"http://*/*",
"https://*/*"
],
"js": ["fg/content.js"],
"run_at": "document_end",
}
],
"browser_action": {
"default_title": "Test Extension",
"default_popup": "popup/popup.html"
}
}
内容.js:
// Listen for message...
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
// If the request asks for the DOM content...
if (request.method && (request.method === "getDOM")) {
// ...send back the content of the <html> element
// (Note: You can't send back the current '#document',
// because it is recognised as a circular object and
// cannot be converted to a JSON string.)
var html = document.all[0];
sendResponse({ "htmlContent": html.innerHTML });
}
});
弹出.html:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="popup.js"></script>
</head>
<body>
Search:
<input type="text" id="search" />
<input type="button" id="searchBtn" value=" Find "
style="width:100%;" />
</body>
</html>
弹出.js:
window.addEventListener("DOMContentLoaded", function() {
var inp = document.getElementById("search");
var btn = document.getElementById("searchBtn");
btn.addEventListener("click", function() {
var searchTerm = inp.value;
if (!inp.value) {
alert("Please, enter a term to search for !");
} else {
// Get the active tab
chrome.tabs.query({
active: true,
currentWindow: true
}, function(tabs) {
// If there is an active tab...
if (tabs.length > 0) {
// ...send a message requesting the DOM...
chrome.tabs.sendMessage(tabs[0].id, {
method: "getDOM"
}, function(response) {
if (chrome.runtime.lastError) {
// An error occurred :(
console.log("ERROR: ", chrome.runtime.lastError);
} else {
// Do something useful with the HTML content
console.log([
"<html>",
response.htmlContent,
"</html>"
].join("\n"));
}
});
}
});
}
});
});