我无法从我的内容脚本中获得响应以显示在我的 popup.html 中。当此代码运行并单击查找按钮时,“Hello from response!”打印,但变量 response 打印为未定义。最终目标是将当前选项卡的 DOM 放入我的脚本文件中,以便我可以解析它。我正在向内容脚本使用单一时间消息来获取 DOM,但它没有被返回并且显示为未定义。我正在寻找任何可能的帮助。谢谢。
popup.html:
<!DOCTYPE html>
<html>
<body>
<head>
<script src="script.js"></script>
</head>
<form >
Find: <input id="find" type="text"> </input>
</form>
<button id="find_button"> Find </button>
</body>
</html>
list .json:
{
"name": "Enhanced Find",
"version": "1.0",
"manifest_version": 2,
"description": "Ctrl+F, but better",
"browser_action": {
"default_icon": "icon.png",
"default_popup": "popup.html"
},
"permissions": [
"tabs",
"*://*/*"
],
"background":{
"scripts": ["script.js"],
"persistent": true
},
"content_scripts":[
{
"matches": ["http://*/*", "https://*/*"],
"js": ["content_script.js"],
"run_at": "document_end"
}
]
}
脚本.js:
var bkg = chrome.extension.getBackgroundPage();
function eventHandler(){
var input = document.getElementById("find");
var text = input.value;
chrome.tabs.query({active: true, currentWindow: true}, function(tabs){
var tab = tabs[0];
var url = tab.url;
chrome.tabs.sendMessage(tab.id, {method: "getDocuments"}, function(response){
bkg.console.log("Hello from response!");
bkg.console.log(response);
});
});
}
content_script.js:
var bkg = chrome.extension.getBackgroundPage();
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse){
if(request.method == "getDOM"){
sendResponse({data : bkg.document});
}else{
sendResponse({});
}
});
最佳答案
你的代码有很多问题(见我上面的评论)。
首先是一些建议/注意事项:
不要将您的内容脚本插入到所有 网页中。 <强> Inject programmatically 并且仅当用户想要搜索时。
最好直接在内容脚本中进行“搜索”,这样您可以直接访问 DOM 并对其进行操作(例如突出显示搜索结果等)。如果您采用这种方法,您可能需要调整您的权限,但始终尽量将它们保持在最低限度(例如,不要在
activeTab
就足够的地方使用tabs
等).请记住,一旦弹出窗口关闭/隐藏(例如,一个选项卡获得焦点),所有在弹出窗口上下文中执行的 JS 都将中止。
如果您想要某种持久性(甚至是临时性的),例如记住最近的结果或上一个搜索词,您可以使用类似 chrome.storage 的东西 或 localStorage .
最后,来 self 的扩展程序演示版本的示例代码:
扩展文件组织:
extension-root-directory/
|
|_____fg/
| |_____content.js
|
|_____popup/
| |_____popup.html
| |_____popup.js
|
|_____manifest.json
list .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"
}
}
content.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 });
}
});
popup.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>
popup.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"));
}
});
}
});
}
});
});
关于javascript - chrome 扩展中内容脚本的未定义响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19641042/