Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add downloads samples #934

Open
wants to merge 25 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions api-samples/downloads/download_filename_controller/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
# chrome.downloads - Download Filename Controller

This sample uses the [`chrome.downloads`](https://developer.chrome.com/docs/extensions/reference/downloads/) API to control the names of files being downloaded.

## Overview

This sample lets you add rules to the extension's options page to set the conflict action for the files being downloaded.

## Running this extension

1. Clone this repository.
2. Load this directory in Chrome as an [unpacked extension](https://developer.chrome.com/docs/extensions/mv3/getstarted/development-basics/#load-unpacked).
3. Click the extension's action icon to open the options page.
4. Add rules in the extension's options page and download files to see the effect.
12 changes: 12 additions & 0 deletions api-samples/downloads/download_filename_controller/manifest.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
{
"name": "Download Filename Controller",
"description": "Demonstrates using the chrome.downloads API to control the names of files being downloaded.",
"version": "0.1",
"background": {
"service_worker": "service-worker.js"
},
"action": {},
"options_page": "options.html",
"permissions": ["downloads", "storage"],
"manifest_version": 3
}
40 changes: 40 additions & 0 deletions api-samples/downloads/download_filename_controller/options.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
<!DOCTYPE html>
<html>
<head>
<title>Download Filename Controller</title>
<script src="options.js"></script>
</head>

<body>
<table id="rules"></table>
<button id="new">New Rule</button>
<table hidden>
<tr id="rule-template" hidden>
<td class="nowrap">
<button class="move-up">&uarr;</button>
<button class="move-down">&darr;</button>
</td>
<td>
<select class="matcher">
<option value="hostname">Hostname</option>
<option value="url-regex">URL RegExp</option>
<option value="default">Default Filename</option>
<option value="default-regex">Default Filename RegExp</option>
</select>
<input type="text" class="match-param" />
<select class="action">
<option value="overwrite">Overwrite default filename</option>
<option value="prompt">Prompt if default filename exists</option>
</select>
</td>
<td>
<span class="nowrap"
><input type="checkbox" class="enabled" checked />
<label class="enabled-label">Enabled</label></span
>
<button class="remove">Remove</button>
</td>
</tr>
</table>
</body>
</html>
96 changes: 96 additions & 0 deletions api-samples/downloads/download_filename_controller/options.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
class Rule {
constructor(data) {
const rules = document.getElementById('rules');
this.node = document.getElementById('rule-template').cloneNode(true);
this.node.id = 'rule' + Rule.next_id++;
this.node.rule = this;
rules.appendChild(this.node);
this.node.hidden = false;

if (data) {
this.getElement('matcher').value = data.matcher;
this.getElement('match-param').value = data.match_param;
this.getElement('action').value = data.action;
this.getElement('enabled').checked = data.enabled;
}

this.getElement('enabled-label').htmlFor = this.getElement('enabled').id =
this.node.id + '-enabled';

this.render();

this.getElement('matcher').onchange = storeRules;
this.getElement('match-param').onkeyup = storeRules;
this.getElement('action').onchange = storeRules;
this.getElement('enabled').onchange = storeRules;

const rule = this;
this.getElement('move-up').onclick = function () {
const sib = rule.node.previousSibling;
rule.node.parentNode.removeChild(rule.node);
sib.parentNode.insertBefore(rule.node, sib);
storeRules();
};
this.getElement('move-down').onclick = function () {
const parentNode = rule.node.parentNode;
const sib = rule.node.nextSibling.nextSibling;
parentNode.removeChild(rule.node);
if (sib) {
parentNode.insertBefore(rule.node, sib);
} else {
parentNode.appendChild(rule.node);
}
storeRules();
};
this.getElement('remove').onclick = function () {
rule.node.parentNode.removeChild(rule.node);
storeRules();
};
storeRules();
}

getElement(name) {
return document.querySelector('#' + this.node.id + ' .' + name);
}

render() {
this.getElement('move-up').disabled = !this.node.previousSibling;
this.getElement('move-down').disabled = !this.node.nextSibling;
}
}

Rule.next_id = 0;

async function loadRules() {
const { rules } = await chrome.storage.local.get('rules');
try {
rules.forEach(function (rule) {
new Rule(rule);
});
} catch (e) {
await chrome.storage.local.set({ rules: [] });
}
}

async function storeRules() {
await chrome.storage.local.set({
rules: [...document.getElementById('rules').childNodes].map(function (
node
) {
node.rule.render();
return {
matcher: node.rule.getElement('matcher').value,
match_param: node.rule.getElement('match-param').value,
action: node.rule.getElement('action').value,
enabled: node.rule.getElement('enabled').checked
};
})
});
}

window.onload = function () {
loadRules();
document.getElementById('new').onclick = function () {
new Rule();
};
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
function matches(rule, item) {
switch (rule.matcher) {
case 'hostname': {
const link = new URL(item.url);
const host =
rule.match_param.indexOf(':') < 0 ? link.hostname : link.host;
return (
host.indexOf(rule.match_param.toLowerCase()) ==
host.length - rule.match_param.length
);
}
case 'default':
return item.filename == rule.match_param;
case 'url-regex':
return new RegExp(rule.match_param).test(item.url);
case 'default-regex':
return new RegExp(rule.match_param).test(item.filename);
default:
return false;
}
}

chrome.downloads.onDeterminingFilename.addListener(function (item, suggest) {
chrome.storage.local.get('rules').then(({ rules }) => {
if (!rules) {
rules = [];
chrome.storage.local.set({ rules });
}
for (let rule of rules) {
if (rule.enabled && matches(rule, item)) {
if (rule.action == 'overwrite') {
suggest({ filename: item.filename, conflictAction: 'overwrite' });
} else if (rule.action == 'prompt') {
suggest({ filename: item.filename, conflictAction: 'prompt' });
}
return;
}
}
suggest({ filename: item.filename });
});

// return true to indicate that suggest() was called asynchronously
return true;
});

chrome.action.onClicked.addListener(function () {
chrome.runtime.openOptionsPage();
});
13 changes: 13 additions & 0 deletions api-samples/downloads/download_links/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
# chrome.downloads - Download Links

This sample demonstrates using the [`chrome.downloads`](https://developer.chrome.com/docs/extensions/reference/downloads) API to download links visible on the active page.

## Overview

This sample lists all available links from the active page in a popup. The [`chrome.downloads.download()`](https://developer.chrome.com/docs/extensions/reference/downloads/#method-download) method is used to download all selected links.

## Running this extension

1. Clone this repository.
2. Load this directory in Chrome as an [unpacked extension](https://developer.chrome.com/docs/extensions/mv3/getstarted/development-basics/#load-unpacked).
3. Open the popup and select links to download.
11 changes: 11 additions & 0 deletions api-samples/downloads/download_links/manifest.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
{
"name": "Download Selected Links",
"description": "Uses the chrome.downloads.download() method to list all available links from the active page in a popup.",
"version": "0.1",
"permissions": ["downloads", "scripting"],
"host_permissions": ["<all_urls>"],
"action": {
"default_popup": "popup.html"
},
"manifest_version": 3
}
21 changes: 21 additions & 0 deletions api-samples/downloads/download_links/popup.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
<!DOCTYPE html>
<html lang="en">
<head>
<title>popup</title>
</head>

<body>
<input type="text" id="filter" placeholder="Filter" />
<input type="checkbox" id="regex" />
<label for="regex">Regex</label><br />
<button id="download0">Download All!</button>
<table id="links">
<tr>
<th><input type="checkbox" checked id="toggle_all" /></th>
<th align="left">URL</th>
</tr>
</table>
<button id="download1">Download All!</button>
<script src="popup.js"></script>
</body>
</html>
114 changes: 114 additions & 0 deletions api-samples/downloads/download_links/popup.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
// This extension demonstrates using chrome.downloads.download() to
// download URLs.

const allLinks = [];
let visibleLinks = [];

// Display all visible links.
function showLinks() {
const linksTable = document.getElementById('links');
while (linksTable.children.length > 1) {
linksTable.removeChild(linksTable.children[linksTable.children.length - 1]);
}
for (let i = 0; i < visibleLinks.length; ++i) {
const row = document.createElement('tr');
const col0 = document.createElement('td');
const col1 = document.createElement('td');
const checkbox = document.createElement('input');
checkbox.checked = true;
checkbox.type = 'checkbox';
checkbox.id = 'check' + i;
col0.appendChild(checkbox);
col1.innerText = visibleLinks[i];
col1.style.whiteSpace = 'nowrap';
col1.onclick = function () {
checkbox.checked = !checkbox.checked;
};
row.appendChild(col0);
row.appendChild(col1);
linksTable.appendChild(row);
}
}

// Toggle the checked state of all visible links.
function toggleAll() {
const checked = document.getElementById('toggle_all').checked;
for (let i = 0; i < visibleLinks.length; ++i) {
document.getElementById('check' + i).checked = checked;
}
}

// Download all visible checked links.
function downloadCheckedLinks() {
for (let i = 0; i < visibleLinks.length; ++i) {
if (document.getElementById('check' + i).checked) {
chrome.downloads.download({ url: visibleLinks[i] });
}
}
window.close();
}

// Re-filter allLinks into visibleLinks and reshow visibleLinks.
function filterLinks() {
const filterValue = document.getElementById('filter').value;
if (document.getElementById('regex').checked) {
visibleLinks = allLinks.filter(function (link) {
return link.match(filterValue);
});
} else {
const terms = filterValue.split(' ');
visibleLinks = allLinks.filter(function (link) {
for (let term of terms) {
if (term.length != 0) {
const expected = term[0] != '-';
if (!expected) {
term = term.slice(1);
if (term.length == 0) {
continue;
}
}
const found = -1 !== link.indexOf(term);
if (found != expected) {
return false;
}
}
}
return true;
});
}
showLinks();
}

// Add links to allLinks and visibleLinks, sort and show them. send_links.js is
// injected into all frames of the active tab, so this listener may be called
// multiple times.
chrome.runtime.onMessage.addListener(function (links) {
allLinks.push(...links);
allLinks.sort();
visibleLinks = allLinks;
showLinks();
});

// Set up event handlers and inject send_links.js into all frames in the active
// tab.
window.onload = async function () {
document.getElementById('filter').onkeyup = filterLinks;
document.getElementById('regex').onchange = filterLinks;
document.getElementById('toggle_all').onchange = toggleAll;
document.getElementById('download0').onclick = downloadCheckedLinks;
document.getElementById('download1').onclick = downloadCheckedLinks;

const { id: currentWindowId } = await chrome.windows.getCurrent();

const tabs = await chrome.tabs.query({
active: true,
windowId: currentWindowId
});

const activeTabId = tabs[0].id;

chrome.scripting.executeScript({
target: { tabId: activeTabId, allFrames: true },
files: ['send_links.js']
});
};
Loading