280

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>';
toraritte
  • 6,300
  • 3
  • 46
  • 67
technocake
  • 2,909
  • 2
  • 15
  • 4
  • 7
    You mean you want a quick solution to include a file on a random web page where you have opened the Developer Tools? – Christian Tellnes Mar 12 '11 at 12:50
  • 7
    I made an add-on to do this: [download from google store](https://chrome.google.com/webstore/detail/javascript-library-for-co/hoooohdeiheekoemicbaeeiaokjhnpko) – w00d Oct 19 '12 at 20:16
  • 2
    possible duplicate of [Load javascript via Firebug console](http://stackoverflow.com/questions/3011817/load-javascript-via-firebug-console) – gak Aug 26 '13 at 01:07
  • I use this to load knockout in console document.write("") – Deepak Vishwakarma Apr 02 '19 at 06:58
  • Unfortunately there's no way to load a local javascript file to console, Chrome won't allow local files to be used. – Shayan Sep 25 '19 at 09:34
  • @Shayan. Not "unfortunately", but fortunately. Because otherwise, it would be real easy to steal passwords, and stuff like that. – mathheadinclouds Nov 07 '19 at 16:33

11 Answers11

310

appendChild() is a more native way:

var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'script.js';
document.head.appendChild(script);
Harmen
  • 22,092
  • 4
  • 54
  • 76
  • 17
    To extend Harman's answer, I wrapped it around a JS function and use it as follows ... var _loadScript = function(path){ var script= document.createElement('script'); script.type= 'text/javascript'; script.src= path; document.head.appendChild(script); } _loadScript('http://documentcloud.github.com/underscore/underscore-min.js'); _loadScript('http://backbonejs.org/backbone-min.js'); – Ajay Bhosale Sep 28 '12 at 05:03
  • I got: `TypeError: Property 'appendChild' of object # is not a function` – Muhammad Hewedy Aug 31 '13 at 05:47
  • 1
    Ajay , thanks, but you have few syntax error. copy/paste the text below, to have underscore in console. Or replace for other lib **var _loadScript = function(path){ var script= document.createElement('script'); script.type= 'text/javascript'; script.src= path; document.head.appendChild(script); } ; _loadScript('http://underscorejs.org/underscore-min.js');** – TPAKTOPA Nov 26 '15 at 15:51
  • Thanks! I used script.innerHTML = `javascript_code` to inject direct javascript code – Jonathan_Ng Oct 29 '19 at 08:57
  • this stops working on 2023/03/04, chrome version 110. Error: "VM216:3 This document requires 'TrustedScriptURL' assignment." – oldpride Mar 04 '23 at 23:00
  • turned out the error was because I used chrome's new tab without going to an URL. If I enter "google.com" in chrome URL, the above solution works. see https://stackoverflow.com/questions/75636895 – oldpride Mar 05 '23 at 03:36
98

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.

rsp
  • 107,747
  • 29
  • 201
  • 177
  • What folder will it load the script from? – Qwerty Jan 16 '14 at 01:05
  • 4
    If you use it like `$.getScript('script.js');` or `$.getScript('../scripts/script.js');` then it's relative to the document but it can load absolute urls as well, eg. `$.getScript('https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.6.0/underscore.js');` – rsp May 16 '14 at 00:38
  • if using jquery, then you could make a bookmarklet to install jquery on the page, https://superuser.com/questions/1460015/how-can-i-make-a-bookmark-that-installs-jquery/1460016#1460016 – barlop Jul 27 '19 at 13:33
51

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 */ })
Maciej Bukowski
  • 3,240
  • 23
  • 28
  • 2
    Latest Chrome disallows the use of `eval`, with the following message: `VM1929:11 Uncaught (in promise) EvalError: Refused to evaluate a string as JavaScript because 'unsafe-eval' is not an allowed source of script in the following Content Security Policy directive: "script-src 'self' blob: filesystem: chrome-extension-resource:".` – Vassilis Oct 11 '17 at 15:34
  • 2
    @Vassilis I checked this and the snippet still works in Chrome Canary (64.0.3241.0). – Maciej Bukowski Oct 16 '17 at 15:46
  • 3
    I think Vassilis problem is because there's a content security policy in place on the app he's using. Chrome works for me as well. – Solomons_Ecclesiastes Apr 04 '19 at 00:22
  • 1
    @Vassilis use my answer bellow (https://stackoverflow.com/a/57814219/6553339) to avoid this error – shmulik friedman Sep 11 '19 at 17:42
26

As a follow-up to the answer of @maciej-bukowski above ^^^, 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.

Community
  • 1
  • 1
jbustamovej
  • 559
  • 4
  • 12
  • 5
    Security policy prevents this from working, at least on the Chrome new tab page as of version 66. *Uncaught (in promise) EvalError: Refused to evaluate a string as JavaScript because 'unsafe-eval' is not an allowed source of script in the following Content Security Policy directive: "script-src 'strict-dynamic' ...* – Tatsh Mar 23 '18 at 10:19
  • @Tatsh use my answer to avoid your error (https://stackoverflow.com/a/57814219/6553339) – shmulik friedman Sep 11 '19 at 17:44
21

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

atirado
  • 311
  • 2
  • 2
  • 6
    Whilst this may theoretically answer the question, [it would be preferable](//meta.stackoverflow.com/q/8259) to include the essential parts of the answer here, and provide the link for reference. – Enamul Hassan Aug 23 '16 at 01:30
  • 2
    I thought my first two lines were the essential part of the answer. They describe exactly how to get to Snippets in Chrome. Then I complemented with the Google documentation. – atirado Aug 25 '16 at 04:49
  • Yeah personally, I think this is the best answer, as it also shows devs and easy way to save and run any javascript against the current page... nice! – Brad Parks Apr 03 '18 at 16:29
12

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

eval(await (await fetch('http://example.com/file.js')).text())
g-otn
  • 293
  • 4
  • 9
6
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);
Community
  • 1
  • 1
xiao 啸
  • 6,350
  • 9
  • 40
  • 51
5

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.
  • It doesn't work for me: Refused to load the script 'https://raw.githack.com/shmuelf/PowerJS/master/src/power-moduleInjector.js' because it violates the following Content Security Policy directive: "script-src ... – ThomasRones May 04 '20 at 16:48
  • how did you tried to load that script? this is the code that loads other scripts, you have to put that (or any such) code manually, it's prety small and you can minify it if you want, but you have to start with something right? if you run the snippet above, will it work for you? – shmulik friedman Jul 24 '20 at 13:21
  • Link is broken. "Internal Server Error" – belkka Aug 02 '20 at 16:29
  • it's on github: https://raw.githubusercontent.com/shmuelf/PowerJS/master/src/power-moduleInjector.js just download it from there, and use it's code in console – shmulik friedman Aug 05 '20 at 07:59
4

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

Zimba
  • 2,854
  • 18
  • 26
  • I got this error when using your code: "This document requires 'TrustedScriptURL' assignment." My browser us Chrome 110. – oldpride Mar 04 '23 at 22:58
  • turned out the error was because I used chrome's new tab without going to an URL. If I enter "google.com" in chrome URL, the above solution works. see stackoverflow.com/questions/75636895 – oldpride Mar 05 '23 at 03:37
  • Worked for me on new tab in Version 90.0.4430.72 (Official Build) (32-bit) – Zimba Mar 29 '23 at 03:51
3

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>");
1

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.

Jannis Ioannou
  • 1,692
  • 1
  • 14
  • 17