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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5282228/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 16:27:59  来源:igfitidea点击:

How to include JavaScript file or library in Chrome console?

javascriptgoogle-chromeconsoleinclude

提问by technocake

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

回答by Harmen

appendChild()is a more native way:

appendChild()是一种更原生的方式:

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

回答by rsp

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

你使用一些 AJAX 框架吗?使用 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 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 answerfor 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 模块的实用工作流程

回答by Maciej Bukowski

In the modern browsers you can use the fetchto 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 */ })

回答by atirado

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

回答by jbustamovej

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:

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

回答by xiao Х

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

回答by shmulik friedman

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

回答by Deepak Vishwakarma

I use this to load koknockout 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>");

回答by Jannis Ioannou

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

安装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.

此解决方案可防止命名空间污染。您可以使用自定义命名空间来避免意外覆盖页面上现有的全局变量。