Chapter 03 Chapter 3: Understanding the Anatomy of a Userscript
Header Metadata
Header Metadata is a crucial component of userscripts that provides important information about the script. It includes details such as the script's name, version, author, description, and the websites where it can be applied. Essentially, it serves as an introduction and overview of your userscript, allowing users and developers to quickly grasp its purpose and usage.
For instance, let's consider a userscript called "Emoji Enchanter" that adds emojis to social media platforms. Here's an example of how Header Metadata can be used:
// ==UserScript==
// @name Emoji Enchanter
// @version 1.0.0
// @description Adds emojis to social media platforms.
// @author Your Name
// @match https://example.com/*
// @match https://socialnetwork.com/*
// ==/UserScript==
In the above example, the Header Metadata provides a concise description of the userscript's purpose, stating that it adds emojis to social media platforms. It also includes the script's name, version, and author for identification. The @match lines specify the websites where the userscript is intended to work.
Header Metadata also allows for additional information to be included, such as the script's homepage, update URL, or the minimum browser version required for proper functionality.
Header Metadata plays a vital role in presenting essential details about your userscripts. It enables users and developers to quickly understand and utilize your scripts effectively. So, make the most of Header Metadata to enhance your userscripting endeavors and provide a clear and concise introduction to your creations.
User Settings
Userscript User Settings, also known as UserScript Configurable Options, are a powerful feature that allows users to customize the behavior and functionality of a userscript according to their preferences. It empowers users with the ability to tweak various settings without directly modifying the userscript's code.
User Settings are typically implemented using a configuration interface that appears when the userscript is executed. This interface presents a set of options or fields that users can modify to personalize their experience. These options can range from simple on/off switches to more complex inputs like text boxes, dropdown menus, or sliders.
Script Variables
Userscript Script Variables, also known as global variables or script-wide variables, are variables defined within a userscript that can be accessed and manipulated across multiple functions or sections of the script. They are used to store data or values that need to be shared and accessed throughout the userscript's execution.
Script Variables provide a way to maintain state or hold information that may change or be referenced in different parts of the userscript. They offer flexibility and allow for the organization and efficient management of data within the script.
Here's an example to illustrate the concept of Script Variables:
// ==UserScript==
// @name Example Userscript
// @version 1.0.0
// @description Demonstrating Script Variables
// ==/UserScript==
// Define a script variable
var counter = 0;
// Function that uses the script variable
function incrementCounter() {
counter++;
console.log('Counter:', counter);
}
// Another function that uses the script variable
function resetCounter() {
counter = 0;
console.log('Counter reset.');
}
// Usage of the script variable and functions
incrementCounter(); // Output: Counter: 1
incrementCounter(); // Output: Counter: 2
resetCounter(); // Output: Counter reset.
incrementCounter(); // Output: Counter: 1
In the example above, the userscript defines a Script Variable called counter and initializes it with a value of 0. The variable is then accessed and modified by two functions: `incrementCounter()` and `resetCounter()`. Each time `incrementCounter()` is called, the value of counter increases by `1` and is logged to the console. Similarly, `resetCounter()` resets the value of counter to `0`.
Script Variables allow the userscript to maintain and update the state of counter across multiple function calls or sections of the script. This enables the script to keep track of information or perform calculations based on the stored value.
Script Variables are variables defined within a userscript that have a global scope, allowing them to be accessed and modified throughout the script's execution. They provide a way to store and manage data that needs to be shared across functions or sections of the userscript. By using Script Variables, userscripts can maintain state and perform operations that require persistent data storage.
Main Function
In userscripts, the Main Function, also known as the entry point or the main execution block, is a crucial part of the script where the primary logic and actions are executed. It serves as the starting point for the userscript's functionality.
The Main Function is typically called when the userscript is loaded or triggered on a specific webpage. It encapsulates the core functionality of the script and orchestrates the sequence of operations or events that need to occur.
Here's an example illustrating the concept of a Main Function in a userscript:
// ==UserScript==
// @name Example Userscript
// @version 1.0.0
// @description Demonstrating the Main Function
// @match https://example.com/*
// ==/UserScript==
// The Main Function
function main() {
// Perform initialization tasks or setup
// Execute the core functionality of the userscript
console.log("Hello from the Main Function!");
// Perform other operations or call additional functions
// ...
}
// Call the Main Function
main();
In the above example, the userscript defines a Main Function called `main()`. Within this function, you can include any necessary initialization tasks, setup procedures, or configuration steps. Following that, the core functionality of the userscript is executed, which in this case is a simple console log statement.
The Main Function can also call other functions, trigger events, manipulate the DOM (Document Object Model), interact with APIs, or perform any other actions required by the userscript. It serves as a central control point for coordinating the script's behavior.
Additionally, the example shows that the Main Function is invoked by calling `main()`. This ensures that the Main Function is executed when the userscript is loaded or triggered on a webpage that matches the specified `@match` URL pattern.
Loaded/Ready
The userscript can take advantage of DOM, and link to existing events, such as, `onload` to let the script know that the web page is loaded and ready.
jQuery
If the web page is using external scripts and resources that may be delayed in loading you can configure a polling script to check if they're ready, such as:
// wait until the window jQuery is loaded
function defer(method) {
if (typeof $ !== 'undefined') {
method();
}
else {
setTimeout(function() { defer(method); }, 100);
}
}
defer(function() {
'use strict';
let el = $(`Hello`);
$("#myel").color('blue');
$('body').append( el );
});
External Scripts
After the browser has loaded and is ready, you can load scripts (both js and css) dynamically on-the-fly, as shown below:
defer(function() {
'use strict';
{
let scripts = document.createElement('script');
scripts.src = 'https://d3js.org/d3.v7.min.js';
document.body.appendChild(scripts);
}
{
let scripts = document.createElement('script');
scripts.src = 'https://cdnjs.cloudflare.com/ajax/libs/tabulator/5.4.4/js/tabulator.min.js';
document.body.appendChild(scripts);
}
{
let link = document.createElement('link');
//link.id = cssId;
link.rel = 'stylesheet';
link.type = 'text/css';
link.href = 'https://cdnjs.cloudflare.com/ajax/libs/tabulator/5.4.4/css/tabulator.min.css';
link.media = 'all';
document.body.appendChild(link);
}
});
Special Cases
There may be occasions when the default events/functions are overwritten or prevented from being called, in these cases you can implement alternative solutions.
For example, if the 'onload' never gets called, as the browser prevents 'propogation' of this event - then your usercript will never get notified. Alternatively, you can pole global flags for state information, as shown below:
// wait until the window is loaded
function mydefer(method)
{
if ( document.readyState === 'complete' )
{
method();
}
else
{
setTimeout(function() { mydefer(method); }, 100);
}
}
// add small delay before userscript starts
setTimeout(function()
{
if ( window.location !== window.parent.location ) {
// The page is in an iframe - window inside a window!
console.log('page is inside an iframe');
return;
}
mydefer( myloaded );
}, 100);
In the above listing, the extra line `window.location !== window.parent.location` is for handling iframes, if a window contains child windows with the same URL (don't want the script getting called again and again).
Helper Functions
Helper Functions in userscripts are auxiliary functions that assist in performing specific tasks or implementing reusable functionality. These functions are designed to simplify and streamline code by encapsulating commonly used operations into modular and reusable units.
Helper Functions can serve a variety of purposes and offer a range of functionalities, depending on the specific needs of the userscript. Here are some examples of commonly used Helper Functions in userscripts:
• DOM Manipulation: Functions that provide convenient methods for interacting with the Document Object Model (DOM) of a webpage. These functions can facilitate tasks such as selecting elements, modifying attributes or content, adding or removing elements, etc.
• API Interactions: Functions that handle communication with external APIs or services. These functions encapsulate the logic for making HTTP requests, parsing responses, and handling errors, making it easier to integrate external data or services into the userscript.
• Utility Functions: General-purpose functions that provide common utility operations. These functions can include string manipulation, array manipulation, date/time formatting, number formatting, and other helpful utilities that simplify common operations within the userscript.
• Event Handling: Functions that streamline the process of adding event listeners or event handlers to specific elements on the webpage. These functions can simplify the process of capturing user interactions, such as clicks, keypresses, or form submissions, and performing corresponding actions.
• Data Storage and Retrieval: Functions that facilitate storing and retrieving data, such as user preferences, settings, or cached information. These functions can utilize browser storage mechanisms like localStorage or IndexedDB to persist data across different browsing sessions.
• User Interface Components: Functions that create or modify user interface elements, such as modals, notifications, or tooltips. These functions can provide a standardized way to display information or interact with users within the userscript.
• The specific Helper Functions utilized in a userscript depend on its purpose and requirements. Userscripts can implement any number of Helper Functions, organizing and modularizing code for better maintainability and reusability.
Leveraging Helper Functions, userscripts can achieve cleaner, more organized code structures, and promote code reuse and readability. They provide a toolkit of specialized functions that simplify common tasks, allowing userscript developers to focus on the unique aspects of their script's functionality.