If you find yourself running the same code in the Console repeatedly, consider saving the code as a snippet instead. Snippets have access to the page's JavaScript context. They are an alternative to bookmarklets.
You can author snippets in the Sources panel and run them on any page and in incognito mode.
For example, the screenshot below shows the DevTools documentation homepage on the left and some snippet source code in the Sources > Snippets pane on the right.
Here's the snippet source code that logs some message and replaces the homepage's HTML body with a <p>
element that contains the message:
console.log('Hello, Snippets!');document.body.innerHTML='';constp=document.createElement('p');p.textContent='Hello, Snippets!';document.body.appendChild(p);
When you click the Run button, the Console drawer pops up to display the
Hello, Snippets!
message that the snippet logs, and the page's content changes.
The Snippets pane lists your snippets. To edit a snippet, open it in one of two ways:
Navigate to Sources >> Snippets.
From the Command Menu:
Snippets
, select Show Snippets, and press Enter.The Sources>Snippets pane shows you a list of snippets you saved, empty in this example.
You can create snippets in the Snippets pane or by running the corresponding command from the Command Menu anywhere in DevTools.
The Snippets pane sorts your snippets in alphabetical order.
Enter a name for your snippet and press Enter to save.
Start typing Snippet
, select Create new snippet, then press Enter to run the command.
See Rename snippets if you'd like to give your new snippet a custom name.
In the Snippets pane, click the name of the snippet that you want to edit. The Sources panel opens it in the Code Editor.
Use the Code Editor to edit code in your snippet. An asterisk next to the snippet name means that you haven't saved your changes yet.
Press Control+S (Windows/Linux) or Command+S (Mac) to save.
Similar to creating a snippet, you can run it both in the Snippets pane and from the Command Menu.
Click Run in the action bar at the bottom of the editor, or press Control+Enter (Windows/Linux) or Command+Enter (Mac).
Type the !
character followed by the name of the snippet that you want to run.
Press Enter to run the snippet.
Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For details, see the Google Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.
Last updated 2015-10-12 UTC.