How to include JavaScript file or library in Chrome console?

后端 未结 10 1805
广开言路
广开言路 2020-11-27 08:58

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.         


        
相关标签:
10条回答
  • 2020-11-27 09:27

    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>");
    
    0 讨论(0)
  • 2020-11-27 09:34

    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.

    0 讨论(0)
  • 2020-11-27 09:34

    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

    0 讨论(0)
  • 2020-11-27 09:38

    appendChild() is a more native way:

    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = 'script.js';
    document.head.appendChild(script);
    
    0 讨论(0)
  • 2020-11-27 09:38

    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

    0 讨论(0)
  • 2020-11-27 09:41
    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);
    
    0 讨论(0)
提交回复
热议问题