MCPcopy Create free account
hub / github.com/violentmonkey/violentmonkey / inject

Function inject

src/injected/content/inject.js:269–332  ·  view source on GitHub ↗
(item, iframeCb)

Source from the content-addressed store, hash-verified

267}
268
269function inject(item, iframeCb) {
270 const { code } = item;
271 const isCodeArray = isObject(code);
272 const script = makeElem('script', !isCodeArray && code);
273 // Firefox ignores sourceURL comment when a syntax error occurs so we'll print the name manually
274 const onError = IS_FIREFOX && !iframeCb && (e => {
275 const { stack } = e[ERROR];
276 if (!stack || `${stack}`.includes(VM_UUID)) {
277 log(ERROR, [item.displayName + ':' + e.lineno + ':' + e.colno], e[ERROR]);
278 e.preventDefault();
279 }
280 });
281 const div = makeElem('div');
282 // Hiding the script's code from mutation events like DOMNodeInserted or DOMNodeRemoved
283 const divRoot = injectedRoot || (
284 attachShadow
285 ? div::attachShadow({ mode: 'closed' })
286 : div
287 );
288 if (isCodeArray) {
289 safeApply(append, script, code);
290 }
291 addNonceAttribute(script);
292 let iframe;
293 let iframeDoc;
294 if (iframeCb) {
295 iframe = makeElem('iframe', {
296 /* Preventing other content scripts */// eslint-disable-next-line no-script-url
297 src: 'javascript:void 0',
298 sandbox: 'allow-same-origin allow-scripts',
299 style: 'display:none!important',
300 });
301 /* In FF the opener receives DOMNodeInserted attached at creation so it can see window[0] */
302 if (!IS_FIREFOX) {
303 divRoot::appendChild(iframe);
304 }
305 } else {
306 divRoot::appendChild(script);
307 }
308 if (onError) {
309 window::on(ERROR, onError);
310 }
311 if (!injectedRoot) {
312 // When using declarativeContent there's no documentElement so we'll append to `document`
313 (elemByTag('*') || document)::appendChild(div);
314 }
315 if (onError) {
316 window::off(ERROR, onError);
317 }
318 if (iframeCb) {
319 injectedRoot = divRoot;
320 if (IS_FIREFOX) divRoot::appendChild(iframe);
321 // Can be removed in DOMNodeInserted by a hostile web page or CSP forbids iframes(?)
322 if ((iframeDoc = iframe.contentDocument)) {
323 iframeDoc::getElementsByTagName('*')[0]::appendChild(script);
324 iframeCb();
325 }
326 iframe::remove();

Callers 4

injectPageSandboxFunction · 0.85
startHandshakeFunction · 0.85
didPageLoseInjectabilityFunction · 0.85
injectPageListFunction · 0.85

Calls 9

makeElemFunction · 0.90
elemByTagFunction · 0.90
isObjectFunction · 0.85
addNonceAttributeFunction · 0.85
onFunction · 0.85
offFunction · 0.85
preventDefaultMethod · 0.80
logFunction · 0.50
removeFunction · 0.50

Tested by

no test coverage detected