Chrome DevTools: Run predefined snippets of code on any web page
Last updated: 4th March 2021Introduction
A feature called Snippets is present in the DevTools which allows you to inject JavaScript code which can be run on a webpage (it's more convenient than re-typing JavaScript code in the console panel). To try it:
How to use this feature
- Go to Sources > Snippets (it's in the left sidebar).
- Select New Snippet (and optionally enter a file name and your desired snippet).
- Right click on the snippet and select Run (or Ctrl/Cmd + Enter).
You'll also notice it has multi-line editing.
An example
As an example, here's a piece of JavaScript code I wrote for previewing what the different JavaScript date
methods return:
Object.getOwnPropertyNames(Date.prototype)
.filter(name => name.startsWith('to'))
.map(method => `${method}: ${(new Date())[method]()}`)
Try creating a snippet named JavaScript Date Methods and pasting that code in. That snippet will then be available in DevTools in the future.
Extra resource
Here's a great collection of DevTools Snippets. There are a few particularly interesting snippets in this project, such as:
- A snippet for printing out all the colors used on a webpage.
- A snippet which includes jQuery onto a page if it is not already present.
- A snippet to log global variables to the connsole.