如何解决当我尝试从 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",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 持久化了吗?
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。