I'm making a simple first extension as I've not used javascript before, and I've got a bit stuck on this part.
Basically I've cut down the source html to get an image url, and I want to save it. I'm using getPagesSource.js
from here (though I'm using a context menu instead of a popup) to get the source code, but I've found I can't then download the image after getting the URL.
If I put the download function in context_click()
with a test URL, it works fine and pops up the download box, but if it's in that listener function (with the same URL), it doesn't do anything.
How would I get the URL to work with the download function?
manifest.json:
{
"name": "Test",
"version": "1.0",
"manifest_version": 2,
"description": "test",
"browser_action": {
"default_icon": "icon.png"
},
"permissions": ["tabs", "contextMenus", "<all_urls>", "downloads"],
"background": {"page": "background.html"},
}
main.js (linked in background.html):
chrome.runtime.onMessage.addListener(function(request, sender) {
if (request.action == "getSource") {
//message.innerText = request.source;
var page_source = request.source;
var image_url = page_source.(do things);
//This works
//chrome.tabs.create({url: image_url});
//This doesn't, and it's what I want to get working
//chrome.downloads.download({
// url: image_url,
// saveAs: true
//});
//Workaround that doesn't have a save dialogue
var a = document.createElement('a');
a.href = image_url;
var url_parts = image_url.split('/');
a.download = url_parts[url_parts.length - 1];
a.click();
}
});
function context_click() {
chrome.tabs.executeScript(null, {
file: "getPagesSource.js"
});
//This works from this point
//chrome.downloads.download({
// url: 'some random url',
// saveAs: true
//});
}
chrome.contextMenus.create({
title: "test",
//contexts:["selection"], // ContextType
onclick: context_click
});