【发布时间】:2015-02-13 04:06:17
【问题描述】:
我想使用 Chrome 扩展程序来下载当前页面的 DOM。我不知道为什么,但是当我下载时,结果只是一个带有“null”或“undefined”的文本文件,而不是 DOM。我试图吸收来自here 和here 的知识,但我似乎无法从content.js 到popup.js 获取信息。
此外,我不确定为什么 this 确实有效。当我阅读docs 时,似乎我需要通过选择活动选项卡将消息从popup.js 发送到content.js:
chrome.tabs.query({currentWindow: true, active: true}, function(tabs) {
chrome.tabs.sendMessage(tabs[0].id, {message: 'getMessageFromContent'}, function(response) {
//Code to handle response from content.js
}
});
我当前的代码:
content.js
var page_html = DOMtoString(document);
chrome.runtime.sendMessage({method: 'downloadPageDOM', pageDOM: thisPage});
function DOMtoString(document_root) { ... }
background.js
chrome.tabs.query({currentWindow: true, active: true}, function(tab) {
var page_html;
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
if (request.message == 'downloadPageDOM')
page_html = request.pageDOM;
else if (request.message == 'getPageDOM')
sendResponse(page_html);
});
});
popup.js
document.addEventListener('DOMContentLoaded', function() {
var download_button = document.getElementById('download_button');
download_button.addEventListener('click', function() {
chrome.runtime.sendMessage({message:'getPageDOM'}, function(response) {
download(response, "download.html", "text/html");
});
});
});
function download(data, fileName, mimeType) { ... }
我觉得我缺少对消息传递如何工作的重要理解。如果有人能花点时间帮助我理解为什么下载的文件只有“null”,我将不胜感激。
【问题讨论】:
-
调用
chrome.tabs.query背后的逻辑是什么?你没有使用响应。
标签: javascript dom google-chrome-extension message-passing