gpt4 book ai didi

javascript - 每个事件代码执行多次 : Multiple downloads

转载 作者:行者123 更新时间:2023-12-03 05:44:55 24 4
gpt4 key购买 nike

我想从内容脚本中下载 JSON 对象。第一次,当我请求下载时,它下载一个文件,但在第二次请求时,它下载两个文件;在第三次请求时,将下载三个文件,依此类推。

背景.js

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");

最佳答案

与这种问题模式的通常情况一样,问题在于您向一个事件添加了多个匿名监听器。具体来说,每次单击 action_button 时,您都会添加另一个 chrome.runtime.onMessage 监听器。您只需添加一次监听器。

解决此问题的简单方法是仅添加 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"
});
});
}

关于javascript - 每个事件代码执行多次 : Multiple downloads,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40368063/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com