How to download a file via a Chrome Content Script?

好久不见. 提交于 2020-01-02 09:28:33

问题


This SO answer details how to download a file via a Chrome Extension, but I am using a Content Script, which has limited access to Chrome's APIs. In other words, I don't have access to the chrome.downloads object. I also tried this vanilla JS solution, but it did not work for me. Does anyone have a solution for Content Scripts or know why the second solution doesn't work?


回答1:


Write a background page or event page and do it from there using the example in your linked answer. Communicate from/to the content script with chrome messages.




回答2:


If you mean causing a file to be downloaded to the user's computer, this code will work in a Chrome extension content script or in the JS script an a regular webpage:

Firstly, you can cause a file to download without any JS at all by simply adding the "download" attribute to an anchor tag. With this tag, instead of navigating to the URL in the "href" attribute, the URL will be downloaded.

<a href="http://website.com/example_1.txt" download="saved_as_filename.txt" id="downloader">
    static download link</a>

To update the URL dynamically:

var theURL = 'http://foo.com/example_2.txt';
$('#downloader').click(function() {
    $(this).attr('href',theURL);
});

If you want the download to be initiated by something other than clicking on a link, you can simulate a click on the link. Note that .trigger() won't work for this purpose. Instead you can use document.createEvent:

$('#downloader').css('display','none');
function initiateDownload(someURL) {    
     theURL = someURL;
     var event = document.createEvent("MouseEvent");
     event.initMouseEvent("click", true, true, window, 0, 0, 0, 80, 20, false, false, false, false, 0, null);
     // dispatch event won't work on a jQuery object, so use getElementById
     var el = document.getElementById('downloader');
     el.dispatchEvent(event);
}
initiateDownload('example_3.txt');


来源:https://stackoverflow.com/questions/26680060/how-to-download-a-file-via-a-chrome-content-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!