2014-10-31 2 views
3

SO answer은 Chrome 확장 프로그램을 통해 파일을 다운로드하는 방법을 자세히 설명하지만 콘텐츠 스크립트 인 which has limited access to Chrome's APIs을 사용하고 있습니다. 즉, chrome.downloads 개체에 액세스 할 수 없습니다. 나는 또한 이것을 시도했다 vanilla JS solution, 그러나 저를 위해 작동하지 않았다. 누구나 컨텐츠 스크립트 용 솔루션을 보유하고 있거나 두 번째 솔루션이 작동하지 않는 이유를 알고 있습니까?Chrome 콘텐츠 스크립트를 통해 파일을 다운로드하는 방법은 무엇인가요?

답변

6

background page 또는 event page을 작성하고 여기에서 example in your linked answer을 사용하십시오. chrome messages으로 콘텐츠 스크립트와주고받습니다. 당신이 파일을 일으킬 수 있습니다, 첫째

: 당신이 사용자의 컴퓨터로 다운로드 할 파일을 일으키는 원인이 의미하는 경우

0

,이 코드는 JS 스크립트 Chrome 확장 콘텐츠 스크립트 또는에서 일반 웹 페이지를 작동합니다 앵커 태그에 "download" attribute을 추가하기 만하면 JS없이 다운로드 할 수 있습니다. 이 태그를 사용하면 "href"속성의 URL로 이동하는 대신 URL이 다운로드됩니다. 당신이 다운로드가 링크를 클릭 이외의 다른에 의해 시작되도록하려면

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

, 당신은 링크를 클릭을 시뮬레이션 할 수 있습니다 :

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

동적으로 URL을 업데이트합니다. .trigger()는이 목적으로는 작동하지 않습니다. 대신 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');