Writing Your First Tampermonkey Script

Publish: 2018-09-17 | Modify: 2018-09-17

Tampermonkey is a free browser extension and the most popular user script manager. It is compatible with Chrome, Microsoft Edge, Safari, Opera Next, and Firefox, referred to as Tampermonkey scripts. In the previous article "Uploading Images to Any Web Page Using Tampermonkey Scripts", Tampermonkey scripts were used.

Tampermonkey

Installing Tampermonkey Extension

Most browsers come with extension (app) stores. You can search for the keyword "Tampermonkey" and install it. For Chrome, you can visit the Chrome Web Store: https://chrome.google.com/webstore/detail/tampermonkey (requires a VPN).

Writing Your First Tampermonkey Script

Tampermonkey scripts are actually JavaScript code, so you need to have knowledge of HTML/CSS/JavaScript before writing a script. Click on the Tampermonkey script icon - Add a new script.

Add New Script

After opening, you will see the following 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 above:

  • @name: The name of the script (choose your own).
  • @namespace: The author's homepage.
  • @version: The current version number of the script.
  • @description: A description of the script (what it is used for).
  • @author: The script author (your name).
  • @match: The URL address that needs to be matched (e.g. https://blog.xiaoz.org/*).
  • @grant: Not sure what it is used for, you can keep the default value.

Write your own JavaScript script starting from // Your code here... (Note: Your own script must be placed here, do not write it outside). There are also some commonly used parameters:

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

The First Hello World

You can copy the following code and replace it in the editor, then save it with Ctrl + S:

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

(function() {
    'use strict';

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

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

Hello World

Summary

Tampermonkey supports almost all PC browsers. With Tampermonkey, you can write your own scripts to meet customization needs, such as changing the CSS styles of a website or removing ads from certain websites.


Comments