Skip to content

Examples (external link)

Bhsd edited this page Apr 15, 2026 · 5 revisions

Replacing non-secure URLs with secure ones

Expand

You can replace http:// URLs from known domains with https:// URLs in the content of a page. This example demonstrates the use of MagicLinkToken.

// Replacing non-secure URLs with secure ones (main)
// The content of a page containing non-secure URLs
var content = `http://www.mediawiki.org/wiki/Foo

[http://www.mediawiki.org/wiki/Bar Baz]`,
	root = Parser.parse(content);
for (const link of root.querySelectorAll('free-ext-link, ext-link-url')) {
	try {
		// May throw if the URL is invalid
		const url = link.getUrl();
		if (url.host === 'www.mediawiki.org' && url.protocol === 'http:') {
			link.protocol = 'https://';
		}
	} catch {}
}
assert.equal(
	root,
	`https://www.mediawiki.org/wiki/Foo

[https://www.mediawiki.org/wiki/Bar Baz]`,
);

Replacing bare URLs with citation templates

Expand

You can replace bare URLs with citation templates in the content of a page. This example demonstrates the use of MagicLinkToken and ExtLinkToken.

// Replacing bare URLs with citation templates (main)
// The content of a page containing bare URLs
var content = `<ref>https://www.mediawiki.org/wiki/Foo</ref>

<ref>[https://www.mediawiki.org/wiki/Bar Baz]</ref>`,
	root = Parser.parse(content),
	links = root.querySelectorAll(
		'ext-inner#ref > ext-link, ext-inner#ref > free-ext-link',
	);
for (const link of links) {
	if (link.type === 'ext-link' && link.length === 2) {
		link.replaceWith(`{{Cite web|url=${link.link}|title=${link.innerText}}}`);
	} else {
		link.replaceWith(`{{Cite web|url=${link.link}}}`);
	}
}
assert.equal(
	root,
	`<ref>{{Cite web|url=https://www.mediawiki.org/wiki/Foo}}</ref>

<ref>{{Cite web|url=https://www.mediawiki.org/wiki/Bar|title=Baz}}</ref>`,
);

Replacing ISBN magic links with templates

Expand

You can replace deprecated ISBN magic links with templates in the content of a page. This example demonstrates the use of MagicLinkToken.

// Replacing bare URLs with citation templates (main)
// The content of a page containing bare URLs
var content = 'ISBN 1234567890',
	root = Parser.parse(content);
for (const isbn of root.querySelectorAll('magic-link[protocol=ISBN]')) {
	isbn.replaceWith(`{{ISBN|${isbn.link.slice(5)}}}`);
}
assert.equal(
	root,
	'{{ISBN|1234567890}}',
);

Clone this wiki locally