javascript - 当我尝试从 chrome 扩展中的 url 下载文件时,Chrome 崩溃
问题描述
所以我正在尝试使用 chrome 扩展从 url 下载文件。为此,我向 runtime.sendmessage() 传递了一个 url,然后我的 background.js 中的侦听器尝试制作一些魔法。消息正确到达,我可以用 sendResponse() 回复而不会出错。当我尝试在侦听器函数中添加使用 chrome.downloads.download() 的函数以使用户下载文件时,chrome 应用程序崩溃。我不知道如何检查我是否有一些错误导致它关闭所有内容..
背景.js
chrome.runtime.onMessage.addListener(
function (request, sender, sendResponse) {
let url = request.url; //request correctly arrive
let filename = url.split("/");
filename = filename[filename.length - 1]; //just a split to get the name of the file from the url where i have to point
try{
download(url, filename);//If i don't call the chrome.download nothing crashes,
//viceversa if i only call the chrome.download and not the onMessage, it doesn't crashes
//it crashes only when i combine the listener and the download method
}
catch(exception){
sendResponse({status: "KO", message: "Download not completed: " + exception, url:url, filename:filename});
}
sendResponse({status: "OK", message: "Download completed", url:url, filename:filename});
return true;
})
function download(url, filename) {
chrome.downloads.download({
url: url,
filename: "videos/" + filename //Create a video folder inside default download folder
})
}
manifest.js
{
"name": "Camnet",
"description": "Build an Extension!",
"version": "1.0",
"manifest_version": 3,
"background": {
"service_worker": "background.js"
},
"permissions": [
"storage","downloads"
],
"action": {
"default_popup": "popup.html"
},
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["contentScript.js"]
}
]
}
contentScript.js
document.getElementById('generaVideo').addEventListener("click", () => {
chrome.runtime.sendMessage({ url: "http://mirrors.prometeus.net/centos/8.3.2011/isos/x86_64/CentOS-8.3.2011-x86_64-boot.iso" }, function (response) {
console.log(response.message);
alert(response.url);
alert(response.filename);
});
}, false)
下载只是一个centos发行版。
解决方案
我在使用清单 3 运行时遇到了同样的问题,但后来我将其转换为清单 2:
"background": {
"persistent": true,
"scripts": [
"background.js"
]
}
我不知道为什么它作为 service_worker 失败或如何使其持久运行。我的意思是,它不是已经作为 service_worker 持久化了吗?
推荐阅读
- flutter - 如何在flutter_svg中使用preCachePicture()
- sql - 如何对我的一个表行内的列表执行 SQL 更新?
- c# - 为什么有些 udp 数据包没有在不同的网络上发送
- flutter - 颤动中自动更改布局
- argv - 无法使用 sys.argv 运行文件
- sql - 如何使用 OR 优化 sql 查询在哪里过滤来自不同列的值?
- angular - 令人尴尬的简单 NGXS - 无法解析 LanguageState 的所有参数
- python - Kivy,按下按钮时更新值
- python-3.x - 在 xlsxwriter 中合并图形时出现问题
- django - 如何自动过滤掉 Django 关联表中的 is_deleted 记录?