How do I upload a file via Chrome Script content?

This SO answer describes how to upload a file via a Chrome extension, but I'm using Content Script which has limited access to the Chrome API . In other words, I have no access to the object chrome.downloads

. I also tried this vanilla JS solution , but it didn't work for me. Does anyone have a content scripting solution or know why the second solution doesn't work?

+3


source to share


2 answers


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



+6


source


If you mean the file is being downloaded to the user's computer, this code will work in the content of a Chrome extension script, or in a JS script on a normal web page:

First, you can force the file to download without any JS whatsoever by simply adding the download attribute to the anchor tag. This tag will load the URL instead of navigating to the URL in the "href" attribute.

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

      

To dynamically update the url:



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

      

If you want the download to be triggered by something other than clicking a link, you can simulate clicking a link. Please note that .trigger () will not work for this purpose. You can use document.createEvent instead :

$('#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');

      

0


source







All Articles