aboutsummaryrefslogtreecommitdiffstats
path: root/src/shared/script-injector.ts
blob: 16cb17c95a698616c19de1d9269dea232bbe858f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
type DataType = {
	[key: string]: string
};

/**
 * Injects a `<script>` element into the document head (or `<html>`) with
 * the given `src` pointing to an extension resource.  Optional key/value
 * data is attached as `data-*` attributes so the injected script can
 * read them via `document.currentScript`.
 *
 * @param src  - The extension-relative script path.
 * @param data - Optional key/value pairs to set as `data-*` attributes.
 */
export function injectScriptHead(src: string, data: DataType = {}) {
	const s = document.createElement("script") as HTMLScriptElement;
	s.src = chrome.runtime.getURL(src);
	for (const i in data) {
		s.setAttribute(`data-${i}`, data[i]);
	}
	(document.head || document.documentElement).append(s);
};