How to Write Your First Tampermonkey Userscript

tampermonkeyuserscript tutorialbrowser extensionjavascript scriptinggreasyfork
Published·Modified·

Tampermonkey is a free browser extension and the most popular userscript manager. It is compatible with Chrome, Microsoft Edge, Safari, Opera Next, and Firefox. This guide refers to it as Tampermonkey scripts. The previous article Using Tampermonkey to Upload Images on Any Webpage utilized Tampermonkey scripts.

Install the Tampermonkey Extension

Most browsers come with a built-in extension store. You can generally search for "Tampermonkey" to install it. For Chrome users, you can visit the Chrome Web Store: https://chrome.google.com/webstore/detail/tampermonkey to install (a proxy may be required).

Write Your First Tampermonkey Script

Tampermonkey scripts are essentially JavaScript code. Therefore, you need to master HTML, CSS, and JavaScript before writing scripts. Click the Tampermonkey icon and select "Add a new script."

Upon opening, you will see the following default code:

// ==UserScript==
// @name         New Userscript
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  try to take over the world!
// @author       You
// @match        http://*/*
// @grant        none
// ==/UserScript==

(function() {
    'use strict';

    // Your code here...
})();

Explanation of the Code

  • @name: The name of the script (choose your own).
  • @namespace: The author's homepage.
  • @version: The current script version number.
  • @description: A description of what the script does.
  • @author: The script author's name.
  • @match: The URL address pattern to match (e.g., https://blog.xiaoz.org/*).
  • @grant: Determines which APIs are available; keep the default if unsure.

Start writing your own JavaScript script after // Your code here... (Note: Your custom code must be placed inside this block, not outside). There are also some other common parameters:

  • @license: The script license agreement.
  • @require: Load external .js files (e.g., to load jQuery).

First Hello World

You can copy the code below into the editor to replace the default content, then press Ctrl + S to save:

// ==UserScript==
// @name         hello world
// @namespace    https://blog.xiaoz.org/
// @version      0.1
// @description  First hello world
// @author       xiaoz
// @match        https://www.baidu.com/*
// @grant        none
// ==/UserScript==

(function() {
    'use strict';

     alert('hello,world!');
})();

When you visit Baidu again, a hello,world! alert will pop up.

Summary

Tampermonkey supports almost all PC browsers. Through Tampermonkey, you can write your own scripts to meet customization needs, such as changing CSS styles on specific websites or removing ads.