289

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>';
6
  • 7
    You mean you want a quick solution to include a file on a random web page where you have opened the Developer Tools? Commented Mar 12, 2011 at 12:50
  • 7
    I made an add-on to do this: download from google store Commented Oct 19, 2012 at 20:16
  • 2
    possible duplicate of Load javascript via Firebug console Commented Aug 26, 2013 at 1:07
  • I use this to load knockout in console document.write("<script src='cdnjs.cloudflare.com/ajax/libs/knockout/3.5.0/…) Commented Apr 2, 2019 at 6:58
  • Unfortunately there's no way to load a local javascript file to console, Chrome won't allow local files to be used. Commented Sep 25, 2019 at 9:34

12 Answers 12

324

appendChild() is a more native way:

var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'script.js';
document.head.appendChild(script);
Sign up to request clarification or add additional context in comments.

6 Comments

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('documentcloud.github.com/underscore/underscore-min.js'); _loadScript('backbonejs.org/backbone-min.js');
I got: TypeError: Property 'appendChild' of object #<HTMLHeadElement> is not a function
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('underscorejs.org/underscore-min.js');
Thanks! I used script.innerHTML = javascript_code</code> to inject direct javascript code
this stops working on 2023/03/04, chrome version 110. Error: "VM216:3 This document requires 'TrustedScriptURL' assignment."
|
102

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.

3 Comments

What folder will it load the script from?
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');
if using jquery, then you could make a bookmarklet to install jquery on the page, superuser.com/questions/1460015/…
53

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 */ })

4 Comments

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 I checked this and the snippet still works in Chrome Canary (64.0.3241.0).
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.
@Vassilis use my answer bellow (stackoverflow.com/a/57814219/6553339) to avoid this error
28

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.

2 Comments

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 use my answer to avoid your error (stackoverflow.com/a/57814219/6553339)
25

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

5 Comments

Whilst this may theoretically answer the question, it would be preferable to include the essential parts of the answer here, and provide the link for reference.
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.
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!
@EnamulHassan, I don't understand your issue. As atirado said, his first two lines are spot on. In fact, this is precisely the solution I needed and I got it from the first line alone. Here's the 2024 link.
@Ricardo Glad that we are hearing from you though it is 8+ years later! It seems I commented this garbage 8+ year ago so that you can leave comments 8+ years later. Thank you.
13

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

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

1 Comment

Uncaught EvalError: Refused to evaluate a string as JavaScript because 'unsafe-eval'
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);

Comments

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.

4 Comments

It doesn't work for me: Refused to load the script 'raw.githack.com/shmuelf/PowerJS/master/src/…' because it violates the following Content Security Policy directive: "script-src ...
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?
Link is broken. "Internal Server Error"
it's on github: raw.githubusercontent.com/shmuelf/PowerJS/master/src/… just download it from there, and use it's code in console
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

3 Comments

I got this error when using your code: "This document requires 'TrustedScriptURL' assignment." My browser us Chrome 110.
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
Worked for me on new tab in Version 90.0.4430.72 (Official Build) (32-bit)
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>");

Comments

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.

Comments

1

You could either do

const require = url => fetch(url).then(response => response.text()).then(window.eval);

Fetches the raw text from the URL and then evals it, so you have to do await require(...).

Or

const require = src => document.head.appendChild(document.createElement("script")).src = src

Makes a new script with the "src" attribute, so you can just do require(...)

Both work, it's just a matter of preference

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.