简体   繁体   中英

How to include JavaScript file or library in Chrome console?

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>';

appendChild() is a more native way:

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

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 eg 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 .

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

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.

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

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

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.

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

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

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

// ==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.

您可以将脚本作为文本获取,然后对其进行评估:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM