### Compare Runtime.startupFinished() and Windows.waitWindowLoading() (APIDOC) Source: https://github.com/mrotherguy/fx-autoconfig/blob/master/readme.md Clarifies the distinct behaviors of `Runtime.startupFinished` and `Windows.waitWindowLoading`. `startupFinished` resolves once in *each window that called it* when ALL those windows have been restored, while `waitWindowLoading` resolves whenever the particular window that calls it has started up. ```APIDOC Runtime.startupFinished(): Resolves once in *each window that called it* when ALL those windows have been restored. Windows.waitWindowLoading(): Resolves whenever the particular window that calls it has started up. ``` -------------------------------- ### JavaScript: Promise for Individual Window Readiness with _ucUtils.windowIsReady Source: https://github.com/mrotherguy/fx-autoconfig/blob/master/uc_utils_old.md This function returns a Promise that resolves when the specific window calling it has finished starting up, corresponding to the browser-delayed-startup-finished event. Note that extension-engine initialization code may or may not have run when this promise resolves. This method is deprecated since version 0.9.0; windows.waitWindowLoading() should be used instead. ```JavaScript _ucUtils.windowIsReady(window) .then(()=>{ console.log("this window has finished starting up"); }); ``` -------------------------------- ### Import Specific UC_API Namespaces in JavaScript Source: https://github.com/mrotherguy/fx-autoconfig/blob/master/readme.md This example shows how to selectively import individual namespaces, such as `FileSystem`, from the `uc_api.sys.mjs` module. This approach allows for more granular control over imported dependencies and can improve code readability. ```JavaScript import { FileSystem } from "chrome://userchromejs/content/uc_api.sys.mjs"; ``` -------------------------------- ### Install Firefox Autoconfig with Home Manager Source: https://github.com/mrotherguy/fx-autoconfig/blob/master/readme.md This Home Manager configuration snippet integrates the fx-autoconfig `config.js` file as an extra preference file for Firefox. It ensures the autoconfig setup is applied within a Home Manager managed environment. ```Nix home.packages = with pkgs; [ (firefox.override { extraPrefsFiles = [(builtins.fetchurl { url = "https://raw.githubusercontent.com/MrOtherGuy/fx-autoconfig/master/program/config.js"; sha256 = "1mx679fbc4d9x4bnqajqx5a95y1lfasvf90pbqkh9sm3ch945p40"; })]; }) ]; ``` -------------------------------- ### Troubleshoot fx-autoconfig gBrowser Startup Error (APIDOC) Source: https://github.com/mrotherguy/fx-autoconfig/blob/master/readme.md Provides a comprehensive guide to understanding and resolving the 'fx-autoconfig: Startup is broken' error, which typically occurs when custom scripts attempt to access the `gBrowser` object when it's not available. It explains the cause, the workaround, and alternative solutions to avoid relying on `gBrowser`. ```JavaScript "fx-autoconfig: Startup is broken" "fx-autoconfig: Something was broken in last startup" ``` ```APIDOC Cause of Error: In older versions of the loader script, `boot.sys.mjs` included a hack to make the Firefox internal `gBrowser` object available. This hack is now disabled by default. If your custom scripts (directly or indirectly, e.g., by accessing `gURLBar`) attempt to use `gBrowser` when it's not available, it will break startup. The loader detects this and prompts to enable a workaround. ``` ```APIDOC Workaround (Preference): To enable the `gBrowser` hack, click the 'Enable workaround' button or manually set the preference `userChromeJS.gBrowser_hack.enabled` to `true`. If you later want to disable it, you must set *both* `userChromeJS.gBrowser_hack.enabled` and `userChromeJS.gBrowser_hack.required` to `false`, or simply remove both preferences. ``` ```APIDOC Solutions to Avoid gBrowser Dependency: 1. Wait until windows have been restored before running functions that access `gBrowser`: `UC_API.Runtime.startupFinished().then(myFunctionAccessinggBrowser)` 2. Check if `_gBrowser` is available and assign it to `gBrowser`: ```js if(window._gBrowser){ window.gBrowser = window._gBrowser; } ``` 3. If accessing `gURLBar`, consider getting a direct reference to the urlbar element instead: ```js // Old way gURLBar.someproperty // Replacement document.getElementById("urlbar").someproperty ``` Alternatively, you can simply set `userChromeJS.gBrowser_hack.enabled` to `true` to re-enable the hack. ``` -------------------------------- ### JavaScript: Include Script in Multiple Windows Source: https://github.com/mrotherguy/fx-autoconfig/blob/master/readme.md This example shows how to include a script in multiple document contexts. By listing 'main' (an alias for the main browser window) and 'chrome://browser/content/places/places.xhtml', the script will execute in both the main window and the Library window. ```JavaScript // ==UserScript== // @include main // @include chrome://browser/content/places/places.xhtml // ==/UserScript== ``` -------------------------------- ### Get Loader Version (APIDOC) Source: https://github.com/mrotherguy/fx-autoconfig/blob/master/readme.md Retrieves the version string of the `boot.sys.mjs` loader, indicating the version of the core loading mechanism. ```APIDOC Runtime.loaderVersion: string ``` -------------------------------- ### Install Firefox Autoconfig on NixOS Source: https://github.com/mrotherguy/fx-autoconfig/blob/master/readme.md This NixOS configuration snippet enables the fx-autoconfig functionality for Firefox. It fetches the `config.js` file directly from the GitHub repository and integrates it into the Firefox program configuration. ```Nix programs.firefox = { enable = true; autoConfig = builtins.readFile(builtins.fetchurl { url = "https://raw.githubusercontent.com/MrOtherGuy/fx-autoconfig/master/program/config.js"; sha256 = "1mx679fbc4d9x4bnqajqx5a95y1lfasvf90pbqkh9sm3ch945p40"; }); }; ``` -------------------------------- ### Get Application Variant (APIDOC) Source: https://github.com/mrotherguy/fx-autoconfig/blob/master/readme.md Retrieves a string indicating the application variant, which will be either 'Firefox' or 'Thunderbird'. ```APIDOC Runtime.appVariant: "Firefox" | "Thunderbird" ``` -------------------------------- ### Get FileSystem Entry with UC_API.FileSystem.getEntry Source: https://github.com/mrotherguy/fx-autoconfig/blob/master/readme.md This function retrieves a `FileSystemResult` object for a specified file or directory. It allows you to check if an entry exists and whether it's a file or a directory. The `FileSystemResult` object provides methods to interact with the entry. ```APIDOC /** * Retrieves a FileSystemResult object for a specified file or directory. * @param {string} fileName - The name or path of the file/directory relative to the resources folder. * @returns {FileSystemResult} */ function getEntry(fileName: string): FileSystemResult; ``` ```JavaScript let fsResult = UC_API.FileSystem.getEntry("some.txt"); result.isFile() // true let nonexistent = UC_API.FileSystem.getEntry("nonexistent.txt"); nonexistent.isError() // true let dir = UC_API.FileSystem.getEntry("directory"); dir.isDirectory() // true ``` -------------------------------- ### Get All Firefox Window Handles with _ucUtils.windows.getAll (JS) Source: https://github.com/mrotherguy/fx-autoconfig/blob/master/uc_utils_old.md This method returns an array of window handles for the current Firefox instance. It can be configured to return only browser windows or include other window types like consoles and Picture-in-Picture windows. ```JavaScript // Get only browser windows (default behavior) let browserWindows = _ucUtils.windows.getAll(); console.log(`Number of browser windows: ${browserWindows.length}`); ``` ```JavaScript // Get all windows, including non-browser types let allWindows = _ucUtils.windows.getAll(false); console.log(`Number of all windows: ${allWindows.length}`); ``` -------------------------------- ### JavaScript: Add Preference Listener with _ucUtils.prefs.addListener Source: https://github.com/mrotherguy/fx-autoconfig/blob/master/uc_utils_old.md This function adds a listener for preference changes. The provided callback function will be invoked when any preference starting with `prefName` is changed. The callback receives the new value and a `Pref` object wrapping the changed preference. ```js let callback = (value,pref) => (console.log(`${pref} changed to ${value}`)) let prefListener = _ucUtils.prefs.addListener("userChromeJS",callback); ``` ```APIDOC { "signature": "_ucUtils.prefs.addListener(prefName,callback) -> Object", "parameters": [ {"name": "prefName", "type": "string", "description": "The prefix of the preference name to listen for changes."}, {"name": "callback", "type": "function", "description": "The function to be invoked when a matching preference changes. Signature: `(value, pref) => void`, where `pref` is a `Pref` object."} ], "returns": { "type": "Object", "description": "An object representing the listener, to be used with `removeListener`." } } ``` -------------------------------- ### Get FileSystemResult Entry with _ucUtils.fs.getEntry Source: https://github.com/mrotherguy/fx-autoconfig/blob/master/uc_utils_old.md The `_ucUtils.fs.getEntry(fileName)` method retrieves a `FileSystemResult` object for a given file or directory path. It allows checking if the result is a file, directory, or an error, providing a robust way to handle file system entries. ```JavaScript let fsResult = _ucUtils.fs.getEntry("some.txt"); fsResult.isFile() // true let nonexistent = _ucUtils.fs.getEntry("nonexistent.txt"); nonexistent.isError() // true let dir = _ucUtils.fs.getEntry("directory"); dir.isDirectory() // true ``` -------------------------------- ### Get Profile Chrome Directory with _ucUtils.fs.chromeDir Source: https://github.com/mrotherguy/fx-autoconfig/blob/master/uc_utils_old.md The `_ucUtils.fs.chromeDir()` method returns a `FileSystemResult` object representing the profile's 'chrome' directory. This result is of type `DIRECTORY`, allowing iteration over its contents or retrieval of its file URI. ```JavaScript let fsResult = _ucUtils.fs.chromeDir(); let uri = fsResult.fileURI // a file:/// uri for (let file of fsResult){ // equal to fsResult.entries() console.log(file.leafName); } ``` -------------------------------- ### Understand Firefox Chrome URL Protocol Structure Source: https://github.com/mrotherguy/fx-autoconfig/blob/master/readme.md Explains the structure of `chrome://` URLs used for loading script files and other resources, including the package, provider, and path components. Notes that the `path` part must start with an alphanumeric character, a limitation that applies to all `chrome://` URLs. ```text chrome://// eg. chrome://userscripts/content/my_script.uc.js ``` -------------------------------- ### Get Browser Brand Name (APIDOC) Source: https://github.com/mrotherguy/fx-autoconfig/blob/master/readme.md Retrieves the brand name of the browser, such as 'Firefox' or 'Firefox Nightly'. ```APIDOC Runtime.brandName: string ``` -------------------------------- ### JavaScript: Get profile chrome directory Source: https://github.com/mrotherguy/fx-autoconfig/blob/master/readme.md Returns a `FileSystemResult` object representing the profile's 'chrome' directory. This object provides access to the directory's URI and allows iteration over its entries. ```JavaScript let fsResult = UC_API.FileSystem.chromeDir(); let uri = fsResult.fileURI // a file:/// uri for (let file of fsResult){ // equal to fsResult.entries() console.log(file.leafName); } ``` ```APIDOC Method: FileSystem.chromeDir Parameters: None Returns: - FileSystemResult: An object with type DIRECTORY for the profile 'chrome' directory. Properties: - fileURI (string): A file:/// URI for the directory. Iterable: - Can be iterated over to get file entries (equivalent to fsResult.entries()). ``` -------------------------------- ### JavaScript: Get Preferences with _ucUtils.prefs.get Source: https://github.com/mrotherguy/fx-autoconfig/blob/master/uc_utils_old.md This function retrieves a preference, returning it wrapped in an object. The returned object provides properties like `exists()`, `name`, `value`, `set value()`, `hasUserValue()`, `type`, and `reset()`. The `value` property will be `null` if the preference cannot be read. ```js let myPref = _ucUtils.prefs.get("userChrome.scripts.disabled"); /* * { * exists() // true|false indicating if this pref exists * name // string - the called pref name * value // | `null` - null means pref with this name could not be read * set value() // same as _ucUtils.prefs.set(name,value) * hasUserValue() // true|false indicating if this has user set value * type // "string"|"boolean"|"number"|"invalid" * reset() // resets this pref to its default value * } */ myPref.exists() // false - "userChrome.scripts.disabled" does not exist ``` ```APIDOC { "signature": "_ucUtils.prefs.get(prefName) -> Pref", "parameters": [ {"name": "prefName", "type": "string", "description": "The name of the preference to retrieve."} ], "returns": { "type": "Pref object", "description": "A representation of the preference wrapped into an object.", "properties": [ {"name": "exists()", "type": "boolean", "description": "True if this pref exists."}, {"name": "name", "type": "string", "description": "The name of the pref."}, {"name": "value", "type": "number|string|boolean|null", "description": "The pref's value, or `null` if it could not be read."}, {"name": "set value(newValue)", "type": "function", "description": "Sets the pref's value, same as _ucUtils.prefs.set(name,newValue)."}, {"name": "hasUserValue()", "type": "boolean", "description": "True if this pref has a user-set value."}, {"name": "type", "type": "string", "description": "\"string\"|\"boolean\"|\"number\"|\"invalid\"."}, {"name": "reset()", "type": "function", "description": "Resets this pref to its default value."} ] } } ``` -------------------------------- ### Get Style Metadata (JavaScript, APIDOC) Source: https://github.com/mrotherguy/fx-autoconfig/blob/master/readme.md Functions identically to `getScriptData()`, but retrieves metadata for registered styles instead of scripts. It can return an array of `ScriptInfo` objects, a single `ScriptInfo` by filename, or a filtered array based on a predicate function. ```APIDOC Scripts.getStyleData(): Array Scripts.getStyleData(aFilter: string): ScriptInfo | null Scripts.getStyleData(aFilter: (style: ScriptInfo) => boolean): Array ``` -------------------------------- ### Get Script Control Menu Element (APIDOC) Source: https://github.com/mrotherguy/fx-autoconfig/blob/master/readme.md Returns the `` HTML element that is created for controlling scripts. In Firefox, this menu is typically found inside the Menubar under 'Tools'. Calling this method will cause the menu to be generated if it has not been already, as it is lazily created. ```APIDOC Scripts.getScriptMenuForDocument(): Element ``` -------------------------------- ### JavaScript: Get Last Focused Window with _ucUtils.windows.getLastFocused Source: https://github.com/mrotherguy/fx-autoconfig/blob/master/uc_utils_old.md This function returns the last focused window. If windowType is undefined, it defaults to returning a 'navigator:browser' window on Firefox or 'mail:3pane' window on Thunderbird. This method was introduced in version 0.9.0. ```APIDOC _ucUtils.windows.getLastFocused(?windowType) -> Window ``` -------------------------------- ### JavaScript: Get All Firefox Windows with UC_API.Windows.getAll Source: https://github.com/mrotherguy/fx-autoconfig/blob/master/readme.md This function returns an array of handles for all window objects within the current Firefox instance. It can optionally filter the results to include only browser windows, excluding other types like consoles or Picture-in-Picture windows. By default, it returns only browser windows. ```APIDOC UC_API.Windows.getAll(onlyBrowsers) -> Array Parameters: onlyBrowsers: boolean (optional) - If true, only browser windows are included. If false, includes all window types (consoles, PiP, etc.). Defaults to true. Returns: Array - A list of window object handles. ``` ```javascript let allMyWindows = UC_API.Windows.getAll(false) ``` -------------------------------- ### Get Script Metadata (JavaScript, APIDOC) Source: https://github.com/mrotherguy/fx-autoconfig/blob/master/readme.md Retrieves a copy of metadata for registered scripts, including those not yet running or disabled. When called without arguments, it returns an array of `ScriptInfo` objects. If a string is provided, it returns a single `ScriptInfo` for the matching filename or `null`. A function argument filters the list, returning scripts for which the function returns `true`. Invalid arguments will throw an error. ```JavaScript let scripts = UC_API.Scripts.getScriptData(); for(let script of scripts){ console.log(`${script.filename} - ${script.isEnabled} - ${script.isRunning}`) } let script = UC_API.Scripts.getScriptData("my-script.uc.js"); console.log(`${script.name} - ${script.isRunning}`); let scripts = UC_API.Scripts.getScriptData(s => s.isRunning); console.log(`You have ${scripts.length} running scripts`); ``` ```APIDOC interface ScriptInfo { filename: string isEnabled: boolean isRunning: boolean name: string // ... other metadata properties } Scripts.getScriptData(): Array Scripts.getScriptData(aFilter: string): ScriptInfo | null Scripts.getScriptData(aFilter: (script: ScriptInfo) => boolean): Array ``` -------------------------------- ### Output a Warning to Console in JavaScript Source: https://github.com/mrotherguy/fx-autoconfig/blob/master/test_profile/chrome/tests/test_3.uc.js.txt This snippet demonstrates the use of `console.warn()` to display a warning message in the browser's developer console or Node.js terminal. It's typically used for alerting developers to potential issues that do not halt program execution. No external dependencies are required, and it takes a string as input, producing output directly to the console. ```JavaScript // This file should be ignored by manager console.warn("This isn't supposed to run!"); ``` -------------------------------- ### Get a Preference Object (JavaScript, APIDOC) Source: https://github.com/mrotherguy/fx-autoconfig/blob/master/readme.md Retrieves a representation of a preference wrapped in a `Pref` object. This object provides properties and methods to inspect and manipulate the preference, including checking its existence, name, value, user-set status, type, and allowing it to be reset. ```JavaScript let myPref = UC_API.Prefs.get("userChrome.scripts.disabled"); myPref.exists() // false - "userChrome.scripts.disabled" does not exist ``` ```APIDOC class Pref { exists(): boolean name: string value: number | string | boolean | null set value(newValue: number | string | boolean): void hasUserValue(): boolean type: "string" | "boolean" | "number" | "invalid" reset(): void } Prefs.get(prefName: string): Pref ``` -------------------------------- ### JavaScript: Import ES6 Module in Background Script Source: https://github.com/mrotherguy/fx-autoconfig/blob/master/readme.md This example shows an ES6 module (.sys.mjs file) which is automatically treated as a background module by the loader. It demonstrates how to use static 'import' declarations to bring in functionality from other modules, such as those located in a 'modules' sub-directory. ```JavaScript // ==UserScript== // @name example sys.mjs module // ==UserScript== import { Some } from "chrome://userscripts/content/modules/some.sys.mjs"; // This would import the script from "modules" sub-directory of your scripts folder. // Note that such script would not be loaded by boot.jsm itself. Some.doThing(); ``` -------------------------------- ### Configure TypeScript for chrome:// Imports in fx-autoconfig Source: https://github.com/mrotherguy/fx-autoconfig/blob/master/readme.md This snippet demonstrates how to configure your `tsconfig.json` file to correctly resolve `chrome://` imports to local TypeScript definition files. This setup is crucial for enabling type checking and autocompletion for `fx-autoconfig`'s `uc_api.sys.mjs` module. ```JSON { "compilerOptions": { "paths": { "chrome://userchromejs/content/uc_api.sys.mjs": [ "./node_modules/@types/fx-autoconfig/index.d.ts" ] } } } ``` -------------------------------- ### Add a Preference Change Listener (JavaScript, APIDOC) Source: https://github.com/mrotherguy/fx-autoconfig/blob/master/readme.md Registers a callback function to be invoked when any preference starting with the specified `prefName` changes. The callback receives the new value and a `Pref` object representing the actual preference that was modified. This method returns an object that can be used to remove the listener later. ```JavaScript let callback = (value,pref) => (console.log(`Pref '${pref.name}' changed to ${value}`)); let prefListener = UC_API.Prefs.addListener("userChromeJS",callback); ``` ```APIDOC Prefs.addListener(prefName: string, callback: (value: number | string | boolean | null, pref: Pref) => void): Object ``` -------------------------------- ### _ucUtils.windows API Reference Source: https://github.com/mrotherguy/fx-autoconfig/blob/master/uc_utils_old.md The `_ucUtils.windows` object provides an interface to interact with and manage Firefox window instances. ```APIDOC Object: _ucUtils.windows Properties: (None directly listed, but contains methods) Methods: getAll(onlyBrowsers): Array - See separate documentation for details. ``` -------------------------------- ### Initialize Scripts on Window Creation with @startup (Deprecated) Source: https://github.com/mrotherguy/fx-autoconfig/blob/master/readme.md The @startup header (deprecated in 0.10.0, use Windows.onCreated instead) allowed a script to define a function to be executed on each new window. It required an object with a `_startup` property to be stored in `_ucUtils.sharedGlobal`, which would then be called with the window object as an argument. This enabled global initialization once, followed by per-window execution of the `_startup` function. ```JavaScript // ==UserScript== // @name My Test Script // @onlyonce // @startup myScriptObject // ==/UserScript== _ucUtils.sharedGlobal.myScriptObject = { _startup: function(win){ console.log(win.location) } } ``` -------------------------------- ### JavaScript: Promise for Browser Startup Completion with _ucUtils.startupFinished Source: https://github.com/mrotherguy/fx-autoconfig/blob/master/uc_utils_old.md This function returns a Promise that resolves when all windows have been restored during the session startup process. If all windows are already restored at the time of the call, the Promise will resolve immediately. This is useful for actions that depend on the complete browser environment being ready. ```JavaScript _ucUtils.startupFinished() .then(()=>{ console.log("startup done"); }); ``` -------------------------------- ### _ucUtils.hotkeys.define(details) -> Hotkey API Reference Source: https://github.com/mrotherguy/fx-autoconfig/blob/master/uc_utils_old.md Defines a new hotkey and returns a `Hotkey` instance. The `details` object specifies the hotkey's properties, and the returned `Hotkey` instance provides methods for attaching and managing the hotkey across windows. ```APIDOC Function: _ucUtils.hotkeys.define(details) Returns: Hotkey Parameters: details: Object - Configuration for the hotkey. - id: string - Unique identifier for the hotkey. - modifiers: string - Space-separated string of modifier keys (e.g., "ctrl shift"). - key: string - The key character (e.g., "G", "T"). - command: Function | string - The command to execute. If a function, a new element is created. If a string, it invokes a matching command. Hotkey Instance Properties & Methods: trigger: Object - Description for the to-be-generated element. command: Object - Description for the to-be-generated element. matchingSelector: string - CSS selector for matching elements. attachToWindow(window, opt): Promise - Asynchronously creates and elements in the specified window. - window: Window - The target window object. - opt: Object (optional) - Options dictionary. - suppressOriginalKey: boolean - If true, automatically calls suppressOriginalKey() for the window. autoAttach(opt): void - Adds the hotkey to all current (main) windows and all newly created ones. - opt: Object (optional) - Options dictionary (same as for attachToWindow). suppressOriginalKey(window): void - Disables the original for this hotkey in the specified window. - window: Window - The target window object. restoreOriginalKey(window): void - Re-enables the original if it was disabled in the specified window. - window: Window - The target window object. ``` -------------------------------- ### Filesystem: General Resource Access in fx-autoconfig Source: https://github.com/mrotherguy/fx-autoconfig/blob/master/uc_utils_old.md Scripts should primarily use the `resources` folder as the root for file operations. This folder is registered to the `chrome://` scheme, allowing access via `chrome://userChrome/content/.txt`. The `scripts` folder is accessible via `chrome://userScripts/content/`, and the loader module folder via `chrome://userchromejs/content/`. ```APIDOC Paths:\n- Resources: "chrome://userChrome/content/.txt"\n- Scripts: "chrome://userScripts/content/"\n- Loader Module: "chrome://userchromejs/content/" ``` -------------------------------- ### JavaScript: Differentiating _ucUtils.startupFinished and _ucUtils.windowIsReady Source: https://github.com/mrotherguy/fx-autoconfig/blob/master/uc_utils_old.md This section clarifies the distinction between _ucUtils.startupFinished() and _ucUtils.windowIsReady(). startupFinished resolves once in each window that calls it, but only after ALL windows have been restored. In contrast, windowIsReady resolves when the particular window that calls it has completed its own startup process. ```APIDOC Since scripts run per window, `startupFinished` will be resolved once in *each window that called it* when ALL those windows have been restored. But `windowIsReady` will be resolved whenever the particular window that calls it has started up. ``` -------------------------------- ### _ucUtils.windows.getAll(onlyBrowsers) -> Array API Reference Source: https://github.com/mrotherguy/fx-autoconfig/blob/master/uc_utils_old.md Returns a list of window handles for each window object in the current Firefox instance. This method was renamed from `.get()` to `.getAll()` in version 0.9.0. ```APIDOC Method: _ucUtils.windows.getAll(onlyBrowsers) Returns: Array Parameters: onlyBrowsers: boolean (optional) - If true (default), only includes browser windows. If false, also includes consoles, PiP, non-native notifications, etc. ``` -------------------------------- ### JavaScript: Open Script Directory with _ucUtils.openScriptDir Source: https://github.com/mrotherguy/fx-autoconfig/blob/master/uc_utils_old.md This function attempts to open the user's script directory in the operating system's file manager. Its success depends on the OS, and it has only been tested on Windows 10. It returns `true` on success and `false` otherwise. ```js _ucUtils.openScriptDir(); ``` ```APIDOC { "signature": "_ucUtils.openScriptDir() -> Boolean", "parameters": [], "returns": { "type": "boolean", "description": "True if the script directory was successfully opened in the OS file manager, false otherwise. Depends on OS support." } } ``` -------------------------------- ### JavaScript: Wait for Window Loading with _ucUtils.windows.waitWindowLoading Source: https://github.com/mrotherguy/fx-autoconfig/blob/master/uc_utils_old.md This function returns a Promise that resolves when the specified window has completed its initialization work. While scripts are typically injected on DOMContentLoaded, this method ensures that more extensive initialization has occurred. This method was introduced in version 0.9.0. ```JavaScript _ucUtils.windows.waitWindowLoading(window) .then(win => { console.log(win.document.title + " has finished loading") }) ``` -------------------------------- ### Wait for Startup Completion (JavaScript, APIDOC) Source: https://github.com/mrotherguy/fx-autoconfig/blob/master/readme.md Returns a Promise that resolves once all windows have been restored during the session startup process. If all windows have already been restored at the time of the call, the Promise will resolve immediately. ```JavaScript UC_API.Runtime.startupFinished() .then(()=>{ console.log("startup done"); }); ``` ```APIDOC Runtime.startupFinished(): Promise ``` -------------------------------- ### Import Pref Class Directly (JavaScript) Source: https://github.com/mrotherguy/fx-autoconfig/blob/master/readme.md Demonstrates how the `Pref` class can be directly imported into module scripts, allowing for more granular control and usage outside of the main `UC_API.Prefs` methods. ```JavaScript import { Pref } from "chrome://userchromejs/content/utils.sys.mjs"; ``` -------------------------------- ### JavaScript: Iterate Through Windows with _ucUtils.windows.forEach Source: https://github.com/mrotherguy/fx-autoconfig/blob/master/uc_utils_old.md This method runs a specified function for each open window. The callback receives references to the window's document and window object. It's important to note that _ucUtils might not be available on all target window objects if onlyBrowsers is false, requiring the callback to check for its availability. ```JavaScript _ucUtils.windows.forEach((document,window) => console.log(document.location), false) ``` -------------------------------- ### Interact with Firefox Windows using _ucUtils.windows (JS) Source: https://github.com/mrotherguy/fx-autoconfig/blob/master/uc_utils_old.md This object provides methods for interacting with various Firefox window instances. It serves as an entry point for window-related utilities, such as retrieving lists of open windows. ```JavaScript // Access the windows utility object const windowsUtil = _ucUtils.windows; console.log("Windows utility object available:", windowsUtil); ``` -------------------------------- ### Define Custom Hotkeys with _ucUtils.hotkeys.define (JS) Source: https://github.com/mrotherguy/fx-autoconfig/blob/master/uc_utils_old.md This function defines a new hotkey with specified modifiers, key, and command. It returns a `Hotkey` instance which can then be used to attach the hotkey to windows. The `command` can be a function to execute or a string referencing an existing command. ```JavaScript // description for hotkey Ctrl + Shift + G let details = { id: "myHotkey", modifiers: "ctrl shift", key: "G", command: (window,commandEvent) => console.log("Hello from " + window.document.title) } let myKey = _ucUtils.hotkeys.define(details); // myKey will be a instance of Hotkey description object ``` ```JavaScript let details = { id: "myHotkey", modifiers: "ctrl", key: "T", command: (window,commandEvent) => console.log("Hello from " + window.document.title) } _ucUtils.hotkeys.define(details).autoAttach({suppressOriginalKey: true}); // This defines the key `Ctrl+T`, attaches it to all current and future main browser windows and disables original newtab key. ``` -------------------------------- ### JavaScript: Add Script Description Source: https://github.com/mrotherguy/fx-autoconfig/blob/master/readme.md This simple snippet illustrates the use of the @description header. This header allows developers to store a short, human-readable description directly within the script's metadata, providing quick context about its purpose. ```JavaScript // ==UserScript== // @description simple test script that does nothing // ==/UserScript== ``` -------------------------------- ### _ucUtils.parseStringAsScriptInfo(aName, aString, parseAsStyle) -> ScriptInfo API Reference Source: https://github.com/mrotherguy/fx-autoconfig/blob/master/uc_utils_old.md Constructs a `ScriptInfo` object from a string containing metadata, mimicking the internal loader logic. It can parse the string as either script or style metadata. ```APIDOC Function: _ucUtils.parseStringAsScriptInfo(aName, aString, parseAsStyle) Returns: ScriptInfo Parameters: aName: string - The "filename" to associate with the ScriptInfo object. aString: string - The metadata block content to parse. parseAsStyle: boolean (optional) - If truthy, parses aString as style metadata instead of script metadata. Defaults to false. Note: A newline character is required after the closing `// ==/UserScript==` tag for correct parsing. ``` -------------------------------- ### Wait for Window Initialization (JavaScript) Source: https://github.com/mrotherguy/fx-autoconfig/blob/master/readme.md Returns a `Promise` which resolves when the specified window has finished its initialization work. Scripts are normally injected on `DOMContentLoaded`, but `waitWindowLoading` ensures that more extensive initialization has occurred. ```JavaScript UC_API.Windows.waitWindowLoading(window) .then(win => { console.log(win.document.title + " has finished loading") }) ``` -------------------------------- ### JavaScript: Get Last Focused Window with UC_API.Windows.getLastFocused Source: https://github.com/mrotherguy/fx-autoconfig/blob/master/readme.md This function returns the last focused window object. It can optionally filter by a specific window type. If no type is specified, it defaults to returning the main browser window ('navigator:browser') for Firefox or the 3-pane mail window ('mail:3pane') for Thunderbird. ```APIDOC UC_API.Windows.getLastFocused(windowType) -> Window Parameters: windowType: string (optional) - The type of window to return. If undefined, defaults to "navigator:browser" (Firefox) or "mail:3pane" (Thunderbird). Returns: Window - The last focused window object matching the criteria. ``` -------------------------------- ### Runtime Configuration (APIDOC) Source: https://github.com/mrotherguy/fx-autoconfig/blob/master/readme.md This property currently returns `null`. It is reserved for future use to provide configuration details about the runtime environment. ```APIDOC Runtime.config: null ``` -------------------------------- ### Register Callback for New Window Creation (JavaScript) Source: https://github.com/mrotherguy/fx-autoconfig/blob/master/readme.md Registers the `callback` function to be called when a new window has been opened. The callback is executed on `DOMContentLoaded` event. This can be an easy way for a background-script to do initialization work when a window is created, and also serves as a replacement for the deprecated `@startup` directive in version `0.10.0`. ```JavaScript // ==UserScript== // @name initialization script // @description my filename is background.uc.mjs // @onlyonce // ==/UserScript== import { Windows, Hotkeys } from "chrome://userchromejs/content/uc_api.sys.mjs"; let counter = 0; Hotkeys.define({ id: "myHotkey", modifiers: "ctrl shift", key: "F", command: () => console.log("Windows opened until now:", counter) }).autoAttach(); // autoAttach causes this hotkey to be added to all new windows Windows.onCreated(win => { counter++ }); ``` -------------------------------- ### JavaScript: Register Callback for New Window Creation with _ucUtils.windows.onCreated Source: https://github.com/mrotherguy/fx-autoconfig/blob/master/uc_utils_old.md This method registers a callback function to be invoked when a new window is opened. The callback executes on the DOMContentLoaded event, providing an easy way for background scripts to perform actions upon window creation. This method was introduced in version 0.9.0. ```JavaScript // ==UserScript== // @name background module script // @description my filename is background.sys.mjs // ==/UserScript== import { windowUtils, Hotkey } from "chrome://userchromejs/content/utils/utils.sys.mjs"; let counter = 0; windowUtils.onCreated(win => { counter++ }); Hotkey.define({ id: "myHotkey", modifiers: "ctrl shift", key: "F", command: () => console.log("Windows opened until now:", counter) }).autoAttach() ``` -------------------------------- ### UC_API.FileSystem Namespace Overview and FileSystemResult Source: https://github.com/mrotherguy/fx-autoconfig/blob/master/readme.md The `UC_API.FileSystem` namespace provides helper functions for interacting with the filesystem, primarily within the `resources` folder. This section outlines the `FileSystemResult` object, which encapsulates operation outcomes and offers methods to access underlying data. ```APIDOC namespace UC_API.FileSystem { /** * Represents the result of a filesystem operation. * Can be one of four types: FILE, DIRECTORY, ERROR, or CONTENT. */ interface FileSystemResult { /** * Returns the nsIFile object representing a file or directory. * Throws if called on CONTENT or ERROR types. * @returns {nsIFile} */ entry(): nsIFile; /** * Returns the file's text content as a string. * Throws if called on anything except CONTENT type. * @returns {string} */ content(): string; /** * Returns an iterator over files in a directory. * Individual entries are nsIFile objects, not wrapped FileSystemResults. * Throws when called on anything except DIRECTORY type. * @returns {Iterator} */ entries(): Iterator; /** * The size of read content or the size of the file on disk. * @type {number} */ size: number; /** * Asynchronously reads the content of this FileSystemResult (if it's a FILE type). * Throws if called on non-FILE type. * @returns {Promise} */ read(): Promise; /** * Synchronously reads the content of this FileSystemResult (if it's a FILE type). * Throws if called on non-FILE type. * @returns {string} */ readSync(): string; /** * Returns the file URI for this result. * @type {string} */ fileURI: string; /** * Tries to open a given file entry path in the OS file manager. * Whether this works depends on the OS (tested on Windows 10). * @returns {boolean} True if successful, false otherwise. */ showInFileManager(): boolean; /** * Checks if the result represents a file. * @returns {boolean} */ isFile(): boolean; /** * Checks if the result represents a directory. * @returns {boolean} */ isDirectory(): boolean; /** * Checks if the result represents an error. * @returns {boolean} */ isError(): boolean; /** * Checks if the result represents file content. * @returns {boolean} */ isContent(): boolean; } // Result type constants const RESULT_FILE: string; const RESULT_DIRECTORY: string; const RESULT_ERROR: string; const RESULT_CONTENT: string; } ``` ```JavaScript // return nsIFile object representing either a file a directory // throws if called on CONTENT or ERROR types fsResult.entry() // return the file text content as string // throws if called on anything except CONTENT type fsResult.content() // returns content that was read // return an iterator over files in a directory // Note, the individual entries are nsIFile objects, not wrapped `FileSystemResult`s // throws when called on anything except DIRECTORY type fsResult.entries() // entries() is called internally if you try to iterate over the result: fsResult = FileSystem.getEntry("my_dir"); for(let file of fsResult){ ... } // size of read content or size of the file on disk fsResult.size // Read the content of this FileSystemResult // throws if called on non-FILE type let content = await fsResult.read() // Async read console.log(content); // "Hello world!" // throws if called on non-FILE type let sync_content = fsResult.readSync(); console.log(content); // "Hello world!" // get a file URI for this result console.log(fsResult.fileURI) // file:///c:/temp/things/some.txt // Tries to open a given file entry path in OS file manager. // Returns true or false indicating success. // Whether this works or not probably depends on your OS. // Only tested on Windows 10. fsResult.showInFileManager() ``` -------------------------------- ### Understand Firefox User Script Types and Loading Source: https://github.com/mrotherguy/fx-autoconfig/blob/master/readme.md Explains the different types of user scripts (`.uc.js`, `.uc.mjs`, `.sys.mjs`) loaded by the `boot.sys.mjs` module, their injection methods, and how to configure the script directory. Classic `.uc.js` scripts can be marked as background-module (deprecated in 0.10.0). ```plaintext `.uc.js` - classic script which will be synchronously injected into target documents. `.uc.mjs` (new in 0.8) - script which will be loaded into target documents asynchronously as ES6 module. `.sys.mjs` - module script which will be loaded into global context synchronously once on startup. ``` -------------------------------- ### Launch Firefox with a Specific Test Profile Source: https://github.com/mrotherguy/fx-autoconfig/blob/master/readme.md This command launches the Firefox browser, instructing it to use the specified `test_profile` directory as its user profile. This is essential for running the `fx-autoconfig` tests, as the tests rely on configurations within this profile. Ensure the path to `test_profile` is absolute and correct for your system. ```Shell firefox -profile "C:/things/fx-autoconfig/test_profile" ``` -------------------------------- ### JavaScript: Iterate Through Windows with UC_API.Windows.forEach Source: https://github.com/mrotherguy/fx-autoconfig/blob/master/readme.md This method executes a specified callback function for each window object. The callback receives references to the window's document and the window object itself. Developers should be aware that `UC_API` might not be available on all target window objects if non-browser windows are included. ```APIDOC UC_API.Windows.forEach(callback, onlyBrowsers) Parameters: callback: function(document, window) - The function to execute for each window. document: Document - Reference to the window's document object. window: Window - Reference to the window object itself. onlyBrowsers: boolean (optional) - If true, iterates only over browser windows. Defaults to true. Notes: - UC_API may not be available on all target window objects if 'onlyBrowsers' is false. The callback should check for its availability. ``` ```javascript UC_API.Windows.forEach((document,window) => console.log(document.location), false) ``` -------------------------------- ### JavaScript: Load URI in Browser with _ucUtils.loadURI Source: https://github.com/mrotherguy/fx-autoconfig/blob/master/uc_utils_old.md This function loads a specified URI into the browser, returning a boolean indicating success. The details object requires url and where properties, with optional properties like private for private windows and userContextId for container tabs. Note that private tabs cannot be created in non-private windows. ```JavaScript _ucUtils.loadURI(window,{ url:"about:config", where:"tab", // one of ["current","tab","tabshifted","window"] private: true, // should the window be private userContextId: 2 // numeric identifier for container }); // "tabshifted" means background tab but it does not work for unknown reasons // Private tabs cannot be created in non-private windows ``` -------------------------------- ### Understand Firefox Autoconfig Core Modules Source: https://github.com/mrotherguy/fx-autoconfig/blob/master/readme.md This section details the primary JavaScript modules that constitute the fx-autoconfig loader. It outlines their interdependencies and individual responsibilities within the Firefox browser context. Note that `_ucUtils` is deprecated in favor of `UC_API` as of version 0.10.0. ```APIDOC Module: boot.sys.mjs Description: Implements the main user-script loading and management logic. Dependencies: utils.sys.mjs, fs.sys.mjs, uc_api.sys.mjs Module: utils.sys.mjs Description: Collection of various helper functions available for use in user scripts. Note: Direct import discouraged in 0.10.0+, use uc_api.sys.mjs instead. Module: fs.sys.mjs Description: Provides read and write operations on the file system, used internally by boot.sys.mjs. Module: uc_api.sys.mjs (New in 0.10.0) Description: Interface that user scripts should import to access helper methods, replacing direct imports from utils.sys.mjs. ``` -------------------------------- ### Write UTF8 Content to File with _ucUtils.fs.writeFile Source: https://github.com/mrotherguy/fx-autoconfig/blob/master/uc_utils_old.md The `_ucUtils.fs.writeFile(fileName, content, options)` method asynchronously writes the provided content to a file as UTF8. On success, the promise resolves with the number of bytes written. By default, writes are restricted to the 'resources' directory; writing outside requires setting `userChromeJS.allowUnsafeWrites` to `true`. This method currently replaces existing files. ```JavaScript let some_content = "Hello world!\n"; let bytes = await _ucUtils.fs.writeFile( "hello.txt", some_content ); console.log(bytes); // << 13 ``` -------------------------------- ### Understand Firefox Autoconfig Profile Files Source: https://github.com/mrotherguy/fx-autoconfig/blob/master/readme.md This section describes the essential files located within the Firefox profile's `chrome/utils/` directory. These files are crucial for the user-script loading mechanism and provide helper utilities for script development. ```APIDOC File: chrome.manifest Description: Registers file paths to the chrome:// protocol, enabling access to resources within the chrome folder. File: boot.sys.mjs Description: Implements the core user-script loading logic, responsible for managing and executing additional JavaScript files. File: fs.jsm Description: Provides filesystem-related functions, used internally by boot.sys.mjs for read and write operations. File: utils.sys.mjs Description: Contains various helper functions that can be utilized by user scripts. File: uc_api.sys.mjs (New in 0.10.0) Description: A helper API designed as the primary interface for user scripts to import methods, replacing direct imports from utils.sys.mjs. ``` -------------------------------- ### Firefox Autoconfig API Reference Source: https://github.com/mrotherguy/fx-autoconfig/blob/master/readme.md Overview of the API provided by this user script manager. It is not fully compatible with scripts expecting a global `_uc` object. Version 0.10.0 replaced the `_ucUtils` object with `UC_API` for window objects. ```APIDOC This manager is NOT entirely compatible with all existing userScripts - specifically scripts that expect a global `_uc` object or something similar to be available. `_ucUtils` (Deprecated in 0.10.0): - Object exported to window objects. `UC_API` (From 0.10.0 onwards): - Replaces `_ucUtils`. - Exported to window objects. ``` -------------------------------- ### Understanding FileSystemResult Object in JavaScript Source: https://github.com/mrotherguy/fx-autoconfig/blob/master/uc_utils_old.md The `FileSystemResult` object is central to `_ucUtils.fs` operations, providing a standardized way to handle file system outcomes. It can represent a file, directory, error, or file content, offering specific methods to interact with the underlying data based on its type. ```APIDOC class FileSystemResult { // Possible result types static RESULT_FILE: 'get reference to a file' static RESULT_DIRECTORY: 'get reference to a directory' static RESULT_ERROR: 'non-existent file or other kind of error' static RESULT_CONTENT: 'file read operation results' /** * Returns an nsIFile object representing either a file or a directory. * @throws {Error} If called on RESULT_CONTENT or RESULT_ERROR types. * @returns {nsIFile} */ entry(): nsIFile /** * Returns the file text content as a string. * @throws {Error} If called on anything except RESULT_CONTENT type. * @returns {string} */ content(): string /** * Returns an iterator over files in a directory. * Note: Individual entries are nsIFile objects, not wrapped FileSystemResults. * @throws {Error} If called on anything except RESULT_DIRECTORY type. * @returns {Iterator} */ entries(): Iterator /** * The size of read content or the size of the file on disk. * @type {number} */ size: number /** * Asynchronously reads the content of this FileSystemResult. * @throws {Error} If called on non-RESULT_FILE type. * @returns {Promise} */ read(): Promise /** * Synchronously reads the content of this FileSystemResult. * @throws {Error} If called on non-RESULT_FILE type. * @returns {string} */ readSync(): string /** * Gets a file URI for this result. * @type {string} */ fileURI: string /** * Tries to open a given file entry path in the OS file manager. * Returns true or false indicating success. Tested on Windows 10. * @returns {boolean} */ showInFileManager(): boolean } ``` ```JavaScript // return nsIFile object representing either a file a directory // throws if called on CONTENT or ERROR types fsResult.entry() // return the file text content as string // throws if called on anything except CONTENT type fsResult.content() // returns content that was read // return an iterator over files in a directory // Note, the individual entries are nsIFile objects, not wrapped `FileSystemResult`s // throws when called on anything except DIRECTORY type fsResult.entries() // entries() is called internally if you try to iterate over the result: fsResult = _ucUtils.getEntry("my_dir"); for(let file of fsResult){ // ... } // size of read content or size of the file on disk fsResult.size // Read the content of this FileSystemResult // throws if called on non-FILE type let content = await fsResult.read() // Async read console.log(content); // << "Hello world!" // throws if called on non-FILE type let sync_content = fsResult.readSync(); console.log(content); // << "Hello world!" // get a file URI for this result console.log(fsResult.fileURI) // << file:///c:/temp/things/some.txt // Tries to open a given file entry path in OS file manager. // Returns true or false indicating success. // Whether this works or not probably depends on your OS. // Only tested on Windows 10. fsResult.showInFileManager() ``` -------------------------------- ### JavaScript: Create Cross-Window Firefox UI Widgets Source: https://github.com/mrotherguy/fx-autoconfig/blob/master/uc_utils_old.md This function creates a wrapper object for Firefox UI elements, allowing their placement to be tracked across multiple windows. It supports 'toolbaritem' and 'toolbarbutton' types, enabling customization of labels, tooltips, styles, and images. A callback function can be provided for click events, with options for all click types. ```APIDOC _ucUtils.createWidget(details) -> Parameters: - details: object - An object containing widget configuration. - id: string (required) - Unique identifier for the widget. - type: string (required) - Type of the widget. Must be "toolbaritem" or "toolbarbutton". - label: string (optional) - Text label for the widget (defaults to id if missing). - tooltip: string (optional) - Tooltip text for the widget (defaults to id if missing). - class: string (optional) - Additional CSS class names. Default classes are "toolbarbutton-1 chromeclass-toolbar-additional". - image: string (optional) - Filename of an image from the 'resources' folder. Loaded as background-image for toolbaritems, list-style-image for toolbarbuttons. - style: string (optional) - Additional inline CSS text. - allEvents: boolean (optional, default: false) - If true, the callback is triggered on all clicks, not just left-clicks. - callback: function (optional) - Function to be called when the item is clicked. Receives (event, window) as arguments. Stored in _ucUtils.sharedGlobal. If not a function, the element is passive. Note: Any other keys in the 'details' object are added as attributes to the created element. Returns: - : An object containing information about the widget instances across windows. Throws: - Error: If 'id' is not provided. - Error: If 'type' is not "toolbaritem" or "toolbarbutton". - Error: If a widget with the same 'id' already exists (e.g., from multiple window executions). ``` ```JavaScript _ucUtils.createWidget({ id: "funk-item", type: "toolbaritem", label: "funky2", tooltip: "noiseButton", class: "noiseButton", image: "favicon.png", style: "width:30px;", allEvents: true, callback: function(ev,win){ console.log(ev.target.id) } }) ``` -------------------------------- ### Asynchronously Read File Content with UC_API.FileSystem.readFile Source: https://github.com/mrotherguy/fx-autoconfig/blob/master/readme.md Use this asynchronous function to read the content of a file. It returns a Promise that resolves to a `FileSystemResult` object of type `RESULT_CONTENT`, allowing access to the file's text. Throws an error if the argument is not a string. ```APIDOC /** * Asynchronously reads the content of a file. * @param {string} fileName - The name or path of the file relative to the resources folder. * @returns {Promise} A promise that resolves to a FileSystemResult of type RESULT_CONTENT. * @throws {Error} If the argument is not a string. */ function readFile(fileName: string): Promise; ``` ```JavaScript let fsResult = await UC_API.FileSystem.readFile("some.txt"); fsResult.isFile() // false fsResult.isContent() // true console.log(fsResult.content()) // "Hello world!" ``` -------------------------------- ### Synchronously Read File Content with _ucUtils.fs.readFileSync Source: https://github.com/mrotherguy/fx-autoconfig/blob/master/uc_utils_old.md The `_ucUtils.fs.readFileSync(some)` method synchronously reads the content of a file. The argument can be either a string representing the filename or a reference to an `nsIFile` object. It returns a `FileSystemResult` of type `RESULT_CONTENT` upon successful read. ```JavaScript let fsResult = _ucUtils.fs.readFileSync("some.txt"); fsResult.isContent() // true console.log(fsResult.content()) // "Hello world!" ``` -------------------------------- ### JavaScript: Create a UI Widget with UC_API.Utils.createWidget Source: https://github.com/mrotherguy/fx-autoconfig/blob/master/readme.md This function creates a UI widget (toolbar item or button) that can be positioned across Firefox windows. It requires an ID and type, and supports optional properties for labeling, styling, and event handling. The method throws errors if required parameters are missing or invalid, or if a widget with the same ID already exists. ```APIDOC UC_API.Utils.createWidget(details) -> Parameters: details: Object - Configuration object for the widget. id: string (required) - Unique identifier for the widget. type: string (required) - Type of widget: "toolbaritem" or "toolbarbutton". label: string (optional) - Text label for the widget (defaults to id). tooltip: string (optional) - Tooltip text (defaults to id). class: string (optional) - Additional CSS class names (added to "toolbarbutton-1 chromeclass-toolbar-additional"). image: string (optional) - Filename from resources folder for the widget image. style: string (optional) - Additional inline CSS text. allEvents: boolean (optional) - If true, callback triggers on all clicks (default: false). callback: function(event, window) (optional) - Function called when the item is clicked. event: Event - The click event object. window: Window - Reference to the window object where the instance is. Returns: - An object wrapping the created element. Notes: - Any unmentioned keys in 'details' are added as element attributes. - Widget placements are tracked across windows. - 'image' is loaded as centered background-image for toolbaritems, list-style-image for toolbarbuttons. - 'callback' is stored in _ucUtils.sharedGlobal mapped to 'id'. - If 'callback' is not a function, the widget is passive. Throws: Error - If 'id' is not provided. Error - If 'type' is anything except "toolbaritem" or "toolbarbutton". Error - If a widget with the same 'id' already exists (e.g., from multiple window executions). ``` ```javascript UC_API.Utils.createWidget({ id: "funk-item", // required type: "toolbaritem", // ["toolbaritem","toolbarbutton"] label: "funky2", // opt (uses id when missing) tooltip: "noiseButton", // opt (uses id when missing) class: "noiseButton", // opt additional className (see below for more) image: "favicon.png", // opt image filename from resources folder style: "width:30px;", // opt additional css-text (see below for more) allEvents: true, // opt trigger on all clicks (default false) callback: function(ev,win){ // Function to be called when the item is clicked console.log(ev.target.id) } }) ``` -------------------------------- ### JavaScript: Include Script in All Windows Except Main Source: https://github.com/mrotherguy/fx-autoconfig/blob/master/readme.md This snippet illustrates the use of a wildcard '*' to target all windows, combined with an @exclude header to prevent the script from executing in the 'main' window. This provides fine-grained control over script execution scope. ```JavaScript // ==UserScript== // @include * // @exclude main // ==/UserScript== ``` -------------------------------- ### Asynchronously Read and Parse JSON with _ucUtils.fs.readJSON Source: https://github.com/mrotherguy/fx-autoconfig/blob/master/uc_utils_old.md The `_ucUtils.fs.readJSON(fileName)` method asynchronously attempts to read a file and parse its content as JSON. If the file cannot be read or parsed as valid JSON, the promise resolves to `null`. This is useful for configuration files. ```JavaScript let fsResult = await _ucUtils.fs.readJSON("some.json") ``` -------------------------------- ### _ucUtils.getScriptData(aFilter) -> Array | ScriptInfo API Reference Source: https://github.com/mrotherguy/fx-autoconfig/blob/master/uc_utils_old.md Retrieves metadata for user scripts as `ScriptInfo` objects. It can return all scripts, a specific script by filename, or a filtered subset based on a predicate function. ```APIDOC Function: _ucUtils.getScriptData(aFilter) Returns: Array | ScriptInfo | null Parameters: aFilter: string | Function | undefined (optional) - If string: Returns a single ScriptInfo object for the script with the specified filename, or null if not found. - If function: Returns an array of ScriptInfo objects for which the function returns true. - If undefined: Returns an array of all ScriptInfo objects. ScriptInfo Object Properties (inferred): filename: string isEnabled: boolean isRunning: boolean name: string chromeURI: string ```