How to include JavaScript file or library in Chrome console?

JavascriptGoogle ChromeConsoleInclude

Javascript Problem Overview


Is there a simpler (native perhaps?) way to include an external script file in the Google Chrome browser?

Currently I’m doing it like this:

document.head.innerHTML += '<script src="http://example.com/file.js"></script>';

Javascript Solutions


Solution 1 - Javascript

appendChild() is a more native way:

var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'script.js';
document.head.appendChild(script);

Solution 2 - Javascript

Do you use some AJAX framework? Using jQuery it would be:

$.getScript('script.js');

If you're not using any framework then see the answer by Harmen.

(Maybe it is not worth to use jQuery just to do this one simple thing (or maybe it is) but if you already have it loaded then you might as well use it. I have seen websites that have jQuery loaded e.g. with Bootstrap but still use the DOM API directly in a way that is not always portable, instead of using the already loaded jQuery for that, and many people are not aware of the fact that even getElementById() doesn't work consistently on all browsers - see this answer for details.)

UPDATE:

It's been years since I wrote this answer and I think it's worth pointing out here that today you can use:

to dynamically load scripts. Those may be relevant to people reading this question.

See also: The Fluent 2014 talk by Guy Bedford: Practical Workflows for ES6 Modules.

Solution 3 - Javascript

In the modern browsers you can use the fetch to download resource (Mozilla docs) and then eval to execute it.

For example to download Angular1 you need to type:

fetch('https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/angular.min.js')
    .then(response => response.text())
    .then(text => eval(text))
    .then(() => { /* now you can use your library */ })

Solution 4 - Javascript

As a follow-up to the answer of @maciej-bukowski [above ^^^][1], in modern browsers as of now (spring 2017) that support async/await you can load as follows. In this example we load the load html2canvas library:

async function loadScript(url) {
  let response = await fetch(url);
  let script = await response.text();
  eval(script);
}

let scriptUrl = 'https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.4.1/html2canvas.min.js'
loadScript(scriptUrl);

If you run the snippet and then open your browser's console you should see the function html2canvas() is now defined.

[1]: https://stackoverflow.com/a/38700405/567525 "above"

Solution 5 - Javascript

In chrome, your best option might be the Snippets tab under Sources in the Developer Tools.

It will allow you to write and run code, for example, in a about:blank page.

More information here: https://developers.google.com/web/tools/chrome-devtools/debug/snippets/?hl=en

Solution 6 - Javascript

var el = document.createElement("script"),
loaded = false;
el.onload = el.onreadystatechange = function () {
  if ((el.readyState && el.readyState !== "complete" && el.readyState !== "loaded") || loaded) {
    return false;
  }
  el.onload = el.onreadystatechange = null;
  loaded = true;
  // done!
};
el.async = true;
el.src = path;
var hhead = document.getElementsByTagName('head')[0];
hhead.insertBefore(el, hhead.firstChild);

Solution 7 - Javascript

If anyone, fails to load because hes script violates the script-src "Content Security Policy" or "because unsafe-eval' is not an allowed", I will advice using my pretty-small module-injector as a dev-tools snippet, then you'll be able to load like this:

imports('https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.js')
  .then(()=>alert(`today is ${moment().format('dddd')}`));

<script src="https://raw.githack.com/shmuelf/PowerJS/master/src/power-moduleInjector.js"></script>

this solution works because:

  1. It loades the library in xhr - which allows CORS from console, and avoids the script-src policy.
  2. It uses the synchronous option of xhr which allows you to stay at the console/snippet's context, so you'll have the permission to eval the script, and not to get-treated as an unsafe-eval.

Solution 8 - Javascript

If you're just starting out learning javascript & don't want to spend time creating an entire webpage just for embedding test scripts, just open Dev Tools in a new tab in Chrome Browser, and click on Console.

Then type out some test scripts: eg.

console.log('Aha!') 

Then press Enter after every line (to submit for execution by Chrome)

or load your own "external script file":

document.createElement('script').src = 'http://example.com/file.js';

Then call your functions:

console.log(file.function('驨ꍬ啯ꍲᕤ'))

Tested in Google Chrome 85.0.4183.121

Solution 9 - Javascript

You could fetch the script as text and then evaluate it:

eval(await (await fetch('http://example.com/file.js')).text())

Solution 10 - Javascript

I use this to load ko knockout object in console

document.write("<script src='https://cdnjs.cloudflare.com/ajax/libs/knockout/3.5.0/knockout-3.5.0.debug.js'></script>");

or host locally

document.write("<script src='http://localhost/js/knockout-3.5.0.debug.js'></script>");

Solution 11 - Javascript

Install tampermonkey and add the following UserScript with one (or more) @match with specific page url (or a match of all pages: https://*) e.g.:

// ==UserScript==
// @name         inject-rx
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  Inject rx library on the page
// @author       Me
// @match        https://www.some-website.com/*
// @require      https://cdnjs.cloudflare.com/ajax/libs/rxjs/6.5.4/rxjs.umd.min.js
// @grant        none
// ==/UserScript==

(function() {
    'use strict';
     window.injectedRx = rxjs;
     //Or even:  window.rxjs = rxjs;
    
})();

Whenever you need the library on the console, or on a snippet enable the specific UserScript and refresh.

This solution prevents namespace pollution. You can use custom namespaces to avoid accidental overwrite of existing global variables on the page.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiontechnocakeView Question on Stackoverflow
Solution 1 - JavascriptHarmenView Answer on Stackoverflow
Solution 2 - JavascriptrspView Answer on Stackoverflow
Solution 3 - JavascriptMaciej BukowskiView Answer on Stackoverflow
Solution 4 - JavascriptjbustamovejView Answer on Stackoverflow
Solution 5 - JavascriptatiradoView Answer on Stackoverflow
Solution 6 - Javascriptxiao 啸View Answer on Stackoverflow
Solution 7 - Javascriptshmulik friedmanView Answer on Stackoverflow
Solution 8 - JavascriptZimbaView Answer on Stackoverflow
Solution 9 - Javascriptg-otnView Answer on Stackoverflow
Solution 10 - JavascriptDeepak VishwakarmaView Answer on Stackoverflow
Solution 11 - JavascriptJannis IoannouView Answer on Stackoverflow