[javascript] Editing in the Chrome debugger

How do I "dynamically" edit JavaScript code in the Chrome debugger? It's not for me, so I don't have access to the source file. I want to edit code and see what effects they have on the page, in this case stopping an animation from queuing up a bunch of times.

This question is related to javascript google-chrome debugging

The answer is


I came across this today, when I was playing around with someone else's website.

I realized I could attach a break-point in the debugger to some line of code before what I wanted to dynamically edit. And since break-points stay even after a reload of the page, I was able to edit the changes I wanted while paused at break-point and then continued to let the page load.

So as a quick work around, and if it works with your situation:

  1. Add a break-point at an earlier point in the script
  2. Reload page
  3. Edit your changes into the code
  4. CTRL + s (save changes)
  5. Unpause the debugger

You can use "Overrides" in Chrome to persist javascript changes between page loads, even where you aren't hosting the original source.

  1. Create a folder under Developer Tools > Sources > Overrides
  2. Chrome will ask for permission to the folder, click Allow
  3. Edit the file in Sources>Page then save (ctrl-s). A purple dot will indicate the file is saved locally.

The Overrides sub tab in Chrome Developer Tools


This is what you are looking for:

1.- Navigate to the Source tab and open the javascript file

2.- Edit the file, right-click it and a menu will appear: click Save and save it locally.

In order to view the diff or revert your changes, right-click and select the option Local Modifications... from the menu. You will see your changes diff with respect to the original file if you expand the timestamp shown.

More detailed info here: http://www.sitepoint.com/edit-source-files-in-chrome/


Pretty easy, go to the 'scripts' tab. And select the source file you want and double-click any line to edit it.


If its javascript that runs on a button click, then making the change under Sources>Sources (in the developer tools in chrome ) and pressing Ctrl +S to save, is enough. I do this all the time.

If you refresh the page, your javascript changes would be gone, but chrome will still remember your break points.


As this is quite popular question that deals with live-editing of JS, I want to point out another useful option. As described by svjacob in his answer:

I realized I could attach a break-point in the debugger to some line of code before what I wanted to dynamically edit. And since break-points stay even after a reload of the page, I was able to edit the changes I wanted while paused at break-point and then continued to let the page load.

The above solution didn't work for me for quite large JS (webpack bundle - 3.21MB minified version, 130k lines of code in prettified version) - chrome crashed and asked for page reloading which reverted any saved changes. The way to go in this case was Fiddler where you can set AutoRespond option to replace any remote resource with any local file from your computer - see this SO question for details.

In my case I also had to add CORS headers to fiddler to successfully mock response.


Just like @mark 's answer, we can create a Snippets in Chrome DevTools, to override the default JavaScript. Finally, we can see what effects they have on the page.

Image


Now google chrome has introduce new feature. By Using this feature You can edit you code in chrome browse. (Permanent change on code location)

For that Press F12 --> Source Tab -- (right side) --> File System - in that please select your location of code. and then chrome browser will ask you permission and after that code will be sink with green color. and you can modify your code and it will also reflect on you code location (It means it will Permanent change)

Thanks


I was looking for a way to change the script and debug that new script. Way I managed to do that is:

  1. Set the breakpoint in the first line of the script you want to change and debug.

  2. Reload the page so the breakpoint is being hit

  3. Paste your new script and set desired breakpoints in it

  4. Ctrl+s, and the page will refresh causing that breakpoint in first line to be hit.

  5. F8 to continue, and now your newly pasted script replaces original one as long as no redirections and reloads are made.


here's a gentle introduction to the js debugger in chrome that i wrote. Maybe it will help others looking for info on this: http://meeech.amihod.com/getting-started-with-javascript-debugging-in-chrome/


you can edit the javascrpit files dynamically in the Chrome debugger, under the Sources tab, however your changes will be lost if you refresh the page, to pause page loading before doing your changes, you will need to set a break point then reload the page and edit your changes and finally unpause the debugger to see your changes take effect. Chrome debugger


  1. Place a breakpoint
  2. Right click on the breakpoint and select 'Edit breakpoint'
  3. Insert your code. Use SHIFT+ENTER to create a new line.

enter image description here


Chrome DevTools has a Snippets panel where you can create and edit JavaScript code as you would in an editor, and execute it. Open DevTools, then select the Sources panel, then select the Snippets tab.

https://developers.google.com/web/tools/chrome-devtools/snippets

enter image description here


Questions with javascript tag:

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax Drag and drop menuitems Is it possible to execute multiple _addItem calls asynchronously using Google Analytics? DevTools failed to load SourceMap: Could not load content for chrome-extension TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received type undefined raised when starting react app What does 'x packages are looking for funding' mean when running `npm install`? SyntaxError: Cannot use import statement outside a module SameSite warning Chrome 77 "Uncaught SyntaxError: Cannot use import statement outside a module" when importing ECMAScript 6 Why powershell does not run Angular commands? Typescript: No index signature with a parameter of type 'string' was found on type '{ "A": string; } Uncaught Invariant Violation: Too many re-renders. React limits the number of renders to prevent an infinite loop Push method in React Hooks (useState)? JS file gets a net::ERR_ABORTED 404 (Not Found) React Hooks useState() with Object useState set method not reflecting change immediately Can't perform a React state update on an unmounted component UnhandledPromiseRejectionWarning: This error originated either by throwing inside of an async function without a catch block Can I set state inside a useEffect hook internal/modules/cjs/loader.js:582 throw err How to post query parameters with Axios? How to use componentWillMount() in React Hooks? React Hook Warnings for async function in useEffect: useEffect function must return a cleanup function or nothing FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory in ionic 3 How can I force component to re-render with hooks in React? What is useState() in React? How to call loading function with React useEffect only once Objects are not valid as a React child. If you meant to render a collection of children, use an array instead How to reload current page? Center content vertically on Vuetify Getting all documents from one collection in Firestore ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment How can I add raw data body to an axios request? Sort Array of object by object field in Angular 6 Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) Axios Delete request with body and headers? Enable CORS in fetch api Vue.js get selected option on @change Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) Angular 6: How to set response type as text while making http call

Questions with google-chrome tag:

SessionNotCreatedException: Message: session not created: This version of ChromeDriver only supports Chrome version 81 SameSite warning Chrome 77 What's the net::ERR_HTTP2_PROTOCOL_ERROR about? session not created: This version of ChromeDriver only supports Chrome version 74 error with ChromeDriver Chrome using Selenium Jupyter Notebook not saving: '_xsrf' argument missing from post How to fix 'Unchecked runtime.lastError: The message port closed before a response was received' chrome issue? Selenium: WebDriverException:Chrome failed to start: crashed as google-chrome is no longer running so ChromeDriver is assuming that Chrome has crashed WebDriverException: unknown error: DevToolsActivePort file doesn't exist while trying to initiate Chrome Browser How to make audio autoplay on chrome How to handle "Uncaught (in promise) DOMException: play() failed because the user didn't interact with the document first." on Desktop with Chrome 66? how to open Jupyter notebook in chrome on windows Access Control Origin Header error using Axios in React Web throwing error in Chrome Invalid self signed SSL cert - "Subject Alternative Name Missing" Chrome violation : [Violation] Handler took 83ms of runtime Getting Error "Form submission canceled because the form is not connected" Violation Long running JavaScript task took xx ms Which ChromeDriver version is compatible with which Chrome Browser version? In Chrome 55, prevent showing Download button for HTML 5 video Why does this "Slow network detected..." log appear in Chrome? A Parser-blocking, cross-origin script is invoked via document.write - how to circumvent it? Disable Chrome strict MIME type checking Cannot open local file - Chrome: Not allowed to load local resource Chrome dev tools fails to show response even the content returned has header Content-Type:text/html; charset=UTF-8 "Uncaught TypeError: a.indexOf is not a function" error when opening new foundation project Is there any way to debug chrome in any IOS device net::ERR_INSECURE_RESPONSE in Chrome How to change the locale in chrome browser What does ==$0 (double equals dollar zero) mean in Chrome Developer Tools? How to prevent "The play() request was interrupted by a call to pause()" error? Disable-web-security in Chrome 48+ When you use 'badidea' or 'thisisunsafe' to bypass a Chrome certificate/HSTS error, does it only apply for the current site? How to open a link in new tab (chrome) using Selenium WebDriver? How to open google chrome from terminal? HTML 5 Video "autoplay" not automatically starting in CHROME Chrome / Safari not filling 100% height of flex parent Chrome:The website uses HSTS. Network errors...this page will probably work later Can a website detect when you are using Selenium with chromedriver? What is the "Upgrade-Insecure-Requests" HTTP header? require is not defined? Node.js Where does Chrome store cookies? Chrome net::ERR_INCOMPLETE_CHUNKED_ENCODING error Understanding Chrome network log "Stalled" state Edit and replay XHR chrome/firefox etc? Force hide address bar in Chrome on Android Google Chrome forcing download of "f.txt" file SSL cert "err_cert_authority_invalid" on mobile chrome only Run chrome in fullscreen mode on Windows "Proxy server connection failed" in google chrome How do I execute .js files locally in my browser? Google Chrome: This setting is enforced by your administrator

Questions with debugging tag:

How do I enable logging for Spring Security? How to run or debug php on Visual Studio Code (VSCode) How do you debug React Native? How do I debug "Error: spawn ENOENT" on node.js? How can I inspect the file system of a failed `docker build`? Swift: print() vs println() vs NSLog() JavaScript console.log causes error: "Synchronous XMLHttpRequest on the main thread is deprecated..." How to debug Spring Boot application with Eclipse? Unfortunately MyApp has stopped. How can I solve this? 500 internal server error, how to debug Is there a real solution to debug cordova apps Attach IntelliJ IDEA debugger to a running Java process Increment variable value by 1 ( shell programming) how can I debug a jar at runtime? Compile throws a "User-defined type not defined" error but does not go to the offending line of code Console.log not working at all What is a thread exit code? How to debug Angular JavaScript Code How do I get the backtrace for all the threads in GDB? PHP parse/syntax errors; and how to solve them How to detect IE11? Android device is not connected to USB for debugging (Android studio) How to debug a Flask app Step-by-step debugging with IPython Not Able To Debug App In Android Studio How do I view / replay a chrome network debugger har file saved with content? How can I debug a HTTP POST in Chrome? How to debug (only) JavaScript in Visual Studio? Write to rails console What do I do when my program crashes with exception 0xc0000005 at address 0? gdb: how to print the current line or find the current line number? How to display errors on laravel 4? How do I pass a command line argument while starting up GDB in Linux? Android Debug Bridge (adb) device - no permissions How to debug a stored procedure in Toad? How to terminate script execution when debugging in Google Chrome? Paused in debugger in chrome? Unable to open debugger port in IntelliJ Reference - What does this error mean in PHP? Maven build debug in Eclipse The thread has exited with code 0 (0x0) with no unhandled exception What does status=canceled for a resource mean in Chrome Developer Tools? Chrome javascript debugger breakpoints don't do anything? Unable to simultaneously satisfy constraints, will attempt to recover by breaking constraint Error: Cannot access file bin/Debug/... because it is being used by another process How to debug Google Apps Script (aka where does Logger.log log to?) How can I get the full object in Node.js's console.log(), rather than '[Object]'? Javascript Debugging line by line using Google Chrome How can I see the entire HTTP request that's being sent by my Python application? How to have PHP display errors? (I've added ini_set and error_reporting, but just gives 500 on errors)