user3851486
user3851486

Reputation: 109

How to get the url of downloading page in chrome extension?

I am trying to make a Chrome extension and I have two questions:

  1. What I want is to get the URL of the page from which my file is getting downloaded.
  2. How to restrict the JavaScript to just act on only some of the URLs and not all? I tried it using content_scripts matches but it didn't work. What to do?

Upvotes: 3

Views: 2609

Answers (1)

Rob W
Rob W

Reputation: 348962

You can rename downloads using chrome.downloads.onDeterminingFilename.

Use downloadItem.referrer to figure out where the download was initiated. This could be an empty string, e.g. when the user typed the download URL in the omnibox.

Here is an example that adds a prefix "downloadprefix-" before every file name if the download originates from http://www.example.com or https://www.example.com/.

chrome.downloads.onDeterminingFilename.addListener(function(downloadItem, suggest) {
    if (/^https?:\/\/www\.example\.com\//.test(downloadItem.referrer)) {
        suggest({
            filename: 'downloadprefix-' + downloadItem.filename
        });
    }
});

Upvotes: 2

Related Questions