0

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
});
Community
  • 1
  • 1
Peter
  • 3,186
  • 3
  • 26
  • 59
  • Not sure you can initiate a download from the link element in a background page. Things to try: 1) do it in the popup, 2) use dispatchEvent for the click. – wOxxOm Mar 24 '17 at 04:46
  • Well it works as long as it's called in the main function, just not after I've actually managed to grab the source html. Would I use a`dispatchEvent` to replace the `chrome.runtime.sendMessage` part? – Peter Mar 24 '17 at 12:46
  • No. I expected you to use search to find the exact command to send the mouse click via dispatchEvent... – wOxxOm Mar 24 '17 at 13:09
  • I'm not quite getting you here, do you mean replace the click for the workaround part? That's the bit which works, but I'd prefer the save dialogue from `chrome.downloads.download` – Peter Mar 25 '17 at 02:36

0 Answers0