Skip to content

Instantly share code, notes, and snippets.

@mikeri
Created June 7, 2026 07:40
Show Gist options
  • Select an option

  • Save mikeri/777b60f49b3c29c4a6de8274200b0eac to your computer and use it in GitHub Desktop.

Select an option

Save mikeri/777b60f49b3c29c4a6de8274200b0eac to your computer and use it in GitHub Desktop.
Add magnet links to Transmission via RPC on click
// ==UserScript==
// @name Magnet to Transmission
// @namespace https://mikeri.net/magnetadd
// @version 1.0.0
// @description Click a normal magnet: link to add it straight to Transmission via its RPC API.
// @author mikeri@mikeri.net
// @match *://*/*
// @run-at document-idle
// @grant GM_xmlhttpRequest
// @grant GM_getValue
// @grant GM_setValue
// @grant GM_registerMenuCommand
// @connect *
// ==/UserScript==
(function () {
'use strict';
// ---- Configuration -------------------------------------------------------
// Configure once via the userscript manager menu ("Configure Transmission"),
// or edit the defaults below. Stored values take precedence over defaults.
const DEFAULTS = {
// Full RPC endpoint of your Transmission instance.
rpcUrl: 'http://localhost:9091/transmission/rpc',
// Leave username/password empty if Transmission has no auth configured.
username: '',
password: '',
// Optional: download directory to pass to Transmission (empty = server default).
downloadDir: '',
};
function cfg(key) {
const v = GM_getValue(key, null);
return v === null || v === '' ? DEFAULTS[key] : v;
}
// ---- Transmission RPC ----------------------------------------------------
// Transmission protects its RPC with a CSRF token: the first request returns
// HTTP 409 plus an X-Transmission-Session-Id header that must be echoed on
// subsequent requests. We cache it and refresh on 409.
let sessionId = GM_getValue('sessionId', '');
function authHeader() {
const user = cfg('username');
const pass = cfg('password');
if (!user && !pass) return {};
return { Authorization: 'Basic ' + btoa(user + ':' + pass) };
}
function rpcRequest(payload, isRetry = false) {
const headers = Object.assign(
{ 'Content-Type': 'application/json' },
authHeader()
);
if (sessionId) headers['X-Transmission-Session-Id'] = sessionId;
GM_xmlhttpRequest({
method: 'POST',
url: cfg('rpcUrl'),
headers: headers,
data: JSON.stringify(payload),
onload: function (res) {
if (res.status === 409 && !isRetry) {
// Grab the fresh session id and replay the request once.
const match = /X-Transmission-Session-Id:\s*(\S+)/i.exec(
res.responseHeaders || ''
);
if (match) {
sessionId = match[1];
GM_setValue('sessionId', sessionId);
rpcRequest(payload, true);
return;
}
notify('error', 'Transmission rejected the request (no session id).');
return;
}
if (res.status === 401) {
notify('error', 'Transmission authentication failed (check username/password).');
return;
}
if (res.status < 200 || res.status >= 300) {
notify('error', 'Transmission error: HTTP ' + res.status);
return;
}
let body;
try {
body = JSON.parse(res.responseText);
} catch (e) {
notify('error', 'Transmission returned an unreadable response.');
return;
}
if (body.result !== 'success') {
notify('error', 'Transmission: ' + body.result);
return;
}
const args = body.arguments || {};
if (args['torrent-duplicate']) {
notify('info', 'Already in Transmission: ' + name(args['torrent-duplicate']));
} else {
notify('success', 'Added to Transmission: ' + name(args['torrent-added']));
}
},
onerror: function () {
notify('error', 'Could not reach Transmission at ' + cfg('rpcUrl'));
},
ontimeout: function () {
notify('error', 'Transmission request timed out.');
},
});
}
function name(t) {
return (t && t.name) ? t.name : 'torrent';
}
function addMagnet(magnetUri) {
const args = { filename: magnetUri, paused: false };
const dir = cfg('downloadDir');
if (dir) args['download-dir'] = dir;
rpcRequest({ method: 'torrent-add', arguments: args });
}
// ---- Notifications -------------------------------------------------------
// A lightweight on-page toast in the bottom-right corner.
let toastEl = null;
function notify(kind, message) {
if (!toastEl) {
toastEl = document.createElement('div');
toastEl.style.cssText = [
'position:fixed', 'z-index:2147483647', 'right:16px', 'bottom:16px',
'max-width:360px', 'padding:10px 14px', 'border-radius:6px',
'font:13px/1.4 system-ui,sans-serif', 'color:#fff',
'box-shadow:0 2px 10px rgba(0,0,0,.3)', 'transition:opacity .3s',
].join(';');
document.body.appendChild(toastEl);
}
const colors = { success: '#2e7d32', info: '#1565c0', error: '#c62828' };
toastEl.style.background = colors[kind] || '#333';
toastEl.textContent = message;
toastEl.style.opacity = '1';
clearTimeout(toastEl._t);
toastEl._t = setTimeout(() => { toastEl.style.opacity = '0'; }, kind === 'error' ? 6000 : 3000);
}
// ---- Click interception --------------------------------------------------
// Capture-phase listener so we beat any page handlers and the browser's own
// default magnet handler. We only act on real magnet anchors.
document.addEventListener(
'click',
function (e) {
// Respect modifier-clicks (open in new tab, etc.) by ignoring them.
if (e.ctrlKey || e.metaKey || e.shiftKey || e.altKey || e.button !== 0) {
return;
}
const anchor = e.target.closest && e.target.closest('a[href^="magnet:"]');
if (!anchor) return;
e.preventDefault();
e.stopPropagation();
addMagnet(anchor.getAttribute('href'));
},
true
);
// ---- Settings menu -------------------------------------------------------
if (typeof GM_registerMenuCommand === 'function') {
GM_registerMenuCommand('Configure Transmission', function () {
const url = prompt('Transmission RPC URL:', cfg('rpcUrl'));
if (url === null) return;
const user = prompt('Username (blank for none):', cfg('username'));
if (user === null) return;
const pass = prompt('Password (blank for none):', cfg('password'));
if (pass === null) return;
const dir = prompt('Download directory (blank for server default):', cfg('downloadDir'));
if (dir === null) return;
GM_setValue('rpcUrl', url.trim());
GM_setValue('username', user);
GM_setValue('password', pass);
GM_setValue('downloadDir', dir.trim());
GM_setValue('sessionId', ''); // force a fresh CSRF handshake
sessionId = '';
notify('info', 'Transmission settings saved.');
});
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment