Can we download a webpage completely with chrome.downloads.download? (Google Chrome Extension)

前端 未结 2 1409
遇见更好的自我
遇见更好的自我 2021-02-04 17:11

I want to save a wabpage completely from my Google Chrome extension. I added \"downloads\", \"\" permissions and confirmed that the following code s

2条回答
  •  后悔当初
    2021-02-04 17:58

    The downloads API downloads a single resource only. If you want to save a complete web page, then you can first open the web page, then export it as MHTML using chrome.pageCapture.saveAsMHTML, create a blob:-URL for the exported Blob using URL.createObjectURL and finally save this URL using the chrome.downloads.download API.

    The pageCapture API requires a valid tabId. For instance:

    // Create new tab, wait until it is loaded and save the page
    chrome.tabs.create({
        url: 'http://example.com'
    }, function(tab) {
        chrome.tabs.onUpdated.addListener(function func(tabId, changeInfo) {
            if (tabId == tab.id && changeInfo.status == 'complete') {
                chrome.tabs.onUpdated.removeListener(func);
                savePage(tabId);
            }
        });
    });
    
    function savePage(tabId) {
        chrome.pageCapture.saveAsMHTML({
            tabId: tabId
        }, function(blob) {
            var url = URL.createObjectURL(blob);
            // Optional: chrome.tabs.remove(tabId); // to close the tab
            chrome.downloads.download({
                url: url,
                filename: 'whatever.mhtml'
            });
        });
    }
    

    To try out, put the previous code in background.js,
    add the permissions to manifest.json (as shown below) and reload the extension. Then example.com will be opened, and the web page will be saved as a self-contained MHTML file.

    {
        "name": "Save full web page",
        "version": "1",
        "manifest_version": 2,
        "background": {
            "scripts": ["background.js"]
        },
        "permissions": [
            "pageCapture",
            "downloads"
        ]
    }
    

提交回复
热议问题