简体   繁体   English

如何在 Chrome 控制台中包含 JavaScript 文件或库?

[英]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?是否有更简单的(可能是本机的?)方法来在 Google Chrome 浏览器中包含外部脚本文件?

Currently I'm doing it like this:目前我是这样做的:

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

appendChild() is a more native way: appendChild()是一种更原生的方式:

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

Do you use some AJAX framework?你使用一些 AJAX 框架吗? Using jQuery it would be:使用 jQuery 将是:

$.getScript('script.js');

If you're not using any framework then see the answer by Harmen.如果您没有使用任何框架,请参阅 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.) (也许仅仅为了做这件简单的事情而使用 jQuery 是不值得的( 或者它可能是),但是如果你已经加载了它,那么你也可以使用它。我见过加载了 jQuery 的网站,例如 Bootstrap 但仍然以一种并不总是可移植的方式直接使用 DOM API,而不是为此使用已经加载的 jQuery,而且许多人不知道即使getElementById()也无法在所有浏览器上始终如一地工作 - 请参阅此答案详情。)

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 .另请参阅: Guy Bedford 在 2014 年的 Fluent 演讲:ES6 模块的实用工作流程

In the modern browsers you can use the fetch to download resource ( Mozilla docs ) and then eval to execute it.在现代浏览器中,您可以使用fetch来下载资源( Mozilla docs ),然后 eval 来执行它。

For example to download Angular1 you need to type:例如要下载 Angular1,您需要输入:

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.作为^^^ 以上@maciej-bukowski 答案的后续,在支持 async/await 的现代浏览器中(2017 年春季),您可以按如下方式加载。 In this example we load the load html2canvas library:在这个例子中,我们加载了 load html2canvas 库:

 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.如果您运行该代码段,然后打开浏览器的控制台,您应该会看到函数 html2canvas() 现已定义。

In chrome, your best option might be the Snippets tab under Sources in the Developer Tools.在 chrome 中,最好的选择可能是开发者工具中 Sources 下的 Snippets 选项卡。

It will allow you to write and run code, for example, in a about:blank page.它将允许您编写和运行代码,例如,在 about:blank 页面中。

More information here: https://developers.google.com/web/tools/chrome-devtools/debug/snippets/?hl=en更多信息: 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:如果有人因为脚本违反了 script-src“内容安全策略”或“因为 unsafe-eval' 是不允许的”而无法加载,我会建议使用我的非常小的模块注入器作为开发工具片段,那么你就可以像这样加载:

 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.它在xhr 中加载库 - 这允许来自控制台的 CORS,并避免 script-src 策略。
  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.它使用 xhr 的同步选项,它允许您停留在控制台/代码段的上下文中,因此您将有权评估脚本,而不会被视为不安全的评估。

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 .如果您刚刚开始学习 javascript 并且不想花时间创建一个完整的网页来嵌入测试脚本,只需在 Chrome 浏览器的新标签中打开开发工具,然后点击Console

Then type out some test scripts: eg.然后输入一些测试脚本:例如。

console.log('Aha!') 

Then press Enter after every line (to submit for execution by Chrome)然后在每一行后按Enter (提交以供 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在谷歌浏览器 85.0.4183.121 中测试

I use this to load ko knockout object in console我用它在控制台中加载ko淘汰赛对象

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:安装tampermonkey并添加以下 UserScript 和一个(或多个) @match与特定页面 url(或所有页面的匹配: https://* )例如:

// ==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.每当您需要控制台上的库或代码片段时,请启用特定的 UserScript 并刷新。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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