Ali Tor Ali Tor - 27 days ago 21
Javascript Question

How to cancel a chrome download before it starts and get the download url?

I want to integrate my C# download manager using a Chrome Extension and I am new in extension development.

So I need to detect when a download request is sent in chrome. Then I need to get the url and pass it to my program to download. I tried it but couldn't get any response.

My code:

manifest.js

{
"manifest_version": 2,

"name": "ADM",
"description": "This extension shows a Google Image search result for the current page",
"version": "1.0",

"browser_action": {
"default_icon": "icon.png"
},
"permissions": [
"downloads",
"https://ajax.googleapis.com/"
],

"content_scripts": [{
"matches" : ["http://*/*", "https://*/*"],
"js" : ["myscript.js"]
}]
}


myscript.js

chrome.downloads.onDeterminingFilename.addListener(function (item) {
chrome.downloads.cancel(item.id);
alert(item.url);
});


As I said, this code didn't cancel the download and show the url for test. How can I do it?

Answer

You are trying to access privileged Chrome apis from a content script, which is not permitted for security reasons. You need to move your code to an event page.

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

Also, read the architecture overview: https://developer.chrome.com/extensions/overview#arch