我想从内容脚本中下载JSON对象。首先,当我请求下载时,它下载一个文件,但在第二个请求时,它下载两个文件;在第三次请求时,下载了三个文件,等等。
chrome.browserAction.onClicked.addListener(function (tab) {
download();
chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
//Alert the message
console.log(request);
chrome.downloads.download({
url: request.method,
filename: request.name
}, function (downloadId) {
});
//You have to choose which part of the response you want to display
// ie. request.method
//alert('The message from the content script: ' + request.method);
//Construct & send a response
sendResponse({
response: "Message received"
});
});
});
function download() {
chrome.tabs.executeScript(null, {
file: "jquery.js"
}, function () {
chrome.tabs.executeScript(null, {
file: "content_script.js"
});
});
}
function sendMessage(url, filename) {
//Construct & send message
chrome.runtime.sendMessage({
method: url,
name: filename
}, function (response) {
//Alert the message
//You have to choose which part of the response you want to display
// ie. response.response
//alert("The response from the background page: " + response.response);
});
}
var json = JSON.stringify(ticket);
var blob = new Blob([json], {
type: "application/json"
});
var url = URL.createObjectURL(blob);
var a = document.createElement('a');
a.download = "backup.json";
a.href = url;
a.textContent = "Download backup.json";
var container = document.getElementById('ticketDetail');
//container.appendChild(a);
var fName = ticket.date.replace(".", "_")
sendMessage(url, fName.replace(".", "_") + ".json");
答案 0 :(得分:1)
与这种问题模式的情况一样,问题是您要向事件添加多个匿名侦听器。具体来说,每次单击chrome.runtime.onMessage
时,您都会添加另一个action_button
侦听器。您只需要添加一次侦听器。
对此的简单解决方案是只添加chrome.runtime.onMessage
一次:
chrome.browserAction.onClicked.addListener(function (tab) {
download();
});
chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
//Alert the message
console.log(request);
chrome.downloads.download({
url: request.method,
filename: request.name
}, function (downloadId) {
});
//You have to choose which part of the response you want to display
// ie. request.method
//alert('The message from the content script: ' + request.method);
//Construct & send a response
sendResponse({
response: "Message received"
});
});
function download() {
chrome.tabs.executeScript(null, {
file: "jquery.js"
}, function () {
chrome.tabs.executeScript(null, {
file: "content_script.js"
});
});
}