首页 > 解决方案 > 当我尝试从 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发行版。

标签: javascriptgoogle-chromegoogle-chrome-extensiondownloadcrash

解决方案


我在使用清单 3 运行时遇到了同样的问题,但后来我将其转换为清单 2:

"background": {
    "persistent": true,
    "scripts": [
        "background.js"
    ]
}

我不知道为什么它作为 service_worker 失败或如何使其持久运行。我的意思是,它不是已经作为 service_worker 持久化了吗?


推荐阅读