### Getting Started with WebExtensions Source: https://developer.mozilla.org/fr/docs/Mozilla/Add-ons/WebExtensions/API/webNavigation/getFrame Guides and concepts for beginners looking to develop their first WebExtension. ```APIDOC ## Getting Started with WebExtensions This section covers the initial steps and fundamental concepts for developing WebExtensions. ### What are WebExtensions? WebExtensions are browser extensions that use web technologies like HTML, CSS, and JavaScript to add functionality to the browser. ### Your First WebExtension This guide walks you through creating a simple 'Hello World' WebExtension. ### Your Second WebExtension Build upon your first extension with more advanced features. ### Anatomy of a WebExtension Understand the core components of a WebExtension, including the manifest file, background scripts, content scripts, and UI elements. ### WebExtension Examples Explore practical examples of WebExtensions to learn different techniques and patterns. ### What's Next? Guidance on further learning and resources to deepen your understanding of WebExtensions development. ``` -------------------------------- ### WebExtensions How-to Guides Source: https://developer.mozilla.org/fr/docs/Mozilla/Add-ons/WebExtensions/API/webRequest/CertificateInfo Practical guides and examples for common WebExtension development tasks. ```APIDOC ## WebExtensions How-to Guides This section provides practical guides for implementing various features in your WebExtensions. ### Development Guides - **Intercepting HTTP Requests** - **Modifying a Web Page** - **Safely Injecting External Content into a Page** - **Sharing Objects with Page Scripts** - **Adding a Button to the Toolbar** - **Adding an Options Page** - **Working with the Tabs API** - **Working with the Bookmarks API** - **Working with the Cookies API** - **Working with Contextual Identities** - **Interacting with the Clipboard** - **Extending Developer Tools** - **Building a Cross-Browser Extension** ``` -------------------------------- ### Express 'Hello World' Example Source: https://developer.mozilla.org/fr/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/Introduction A basic Express.js application that responds with 'Hello World!' to GET requests on the root URL. This example requires Node.js and Express to be installed. Save this code as app.js and run it using 'node app.js'. ```javascript const express = require('express'); const app = express(); const port = 3000; app.get('/', (req, res) => { res.send('Hello World!'); }); app.listen(port, () => { console.log(`Example app listening at http://localhost:${port}`); }); ``` -------------------------------- ### WebExtensions How-tos Source: https://developer.mozilla.org/fr/docs/Mozilla/Add-ons/WebExtensions/API/idle/onStateChanged Practical guides and examples for common WebExtensions development tasks. ```APIDOC ## WebExtensions How-tos This section provides step-by-step guides for implementing common features in WebExtensions. ### Common Tasks - **Intercepting HTTP Requests**: Using the `webRequest` API to intercept and modify network requests. - **Modifying a Web Page**: Using content scripts to alter the DOM of a web page. - **Safely Inserting External Content**: Techniques for embedding external resources securely. - **Sharing Objects with Page Scripts**: Methods for passing data between extension scripts and page scripts. - **Adding a Toolbar Button**: Implementing a browser action. - **Adding a Settings Page**: Creating an options page for the extension. ``` -------------------------------- ### WebExtensions How-Tos Source: https://developer.mozilla.org/fr/docs/Mozilla/Add-ons/WebExtensions/API/omnibox This section provides practical guides and examples for common WebExtension development tasks. ```APIDOC ## WebExtensions How-Tos This section provides step-by-step guides for common WebExtension tasks. ### How-To Guides - **Intercept HTTP Requests** - **Modify a Web Page** - **Safely Inject External Content into a Page** - **Share Objects with Page Scripts** - **Add a Button to the Toolbar** - **Add a Settings Page** - **Working with the Tabs API** - **Working with the Bookmarks API** - **Working with the Cookies API** - **Working with Contextual Identities** - **Interacting with the Clipboard** - **Extending Developer Tools** - **Building a Cross-Browser Extension** ``` -------------------------------- ### Get UTC minutes from current date Source: https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Global_Objects/Date/getUTCMinutes This example shows how to get the current UTC minutes. No specific setup or imports are required. ```javascript const now = new Date(); const minutes = now.getUTCMinutes(); console.log(minutes); ``` -------------------------------- ### File Path Examples Source: https://developer.mozilla.org/fr/docs/Learn_web_development/Getting_started/Environment_setup/Dealing_with_files Illustrates different ways to construct file paths for linking resources. These examples demonstrate linking to files in the same directory, a subdirectory, and a parent directory. ```plaintext mon-image.jpg ``` ```plaintext sousdossier/mon-image.jpg ``` ```plaintext ../mon-image.jpg ``` ```plaintext ../sousdossier/autre-sousdossier/mon-image.jpg ``` -------------------------------- ### Example manifest.json Source: https://developer.mozilla.org/fr/docs/Mozilla/Add-ons/WebExtensions/manifest.json This example illustrates the syntax of some of the most frequently used keys. It is not a copy-paste ready example; select the keys you need carefully when developing an extension. ```json { "manifest_version": 2, "name": "My Extension", "version": "1.0", "description": "The description of my extension.", "icons": { "48": "icons/border-48.png" }, "permissions": [ "tabs", "bookmarks" ], "browser_action": { "name": "My Extension", "icons": { "16": "icons/border-16.png", "32": "icons/border-32.png" }, "default_popup": "popup/browser_action.html" }, "content_scripts": [ { "matches": ["*://*.mozilla.org/*"], "js": ["content_scripts/content.js"] } ], "background": { "scripts": ["background_scripts/background.js"] } } ``` -------------------------------- ### Using PerformanceEntry.toJSON() Source: https://developer.mozilla.org/fr/docs/Web/API/PerformanceEntry/toJSON This example demonstrates how to use the toJSON() method to get a JSON representation of a PerformanceEntry object. No specific setup or imports are required beyond having a PerformanceEntry object available. ```javascript const p = performance.getEntries()[0]; console.log(JSON.stringify(p)); // Expected output: {"name":"resource-timing","entryType":"resource","startTime":123.456,"duration":789.012} ``` -------------------------------- ### Syntax example for protocol list Source: https://developer.mozilla.org/fr/docs/Web/HTTP/Reference/Headers/Upgrade Example of the Upgrade header syntax with multiple protocols. ```http Upgrade: HTTP/2.0, SHTTP/1.3, IRC/6.9, RTA/x11 ``` -------------------------------- ### Get All Installed Add-ons Source: https://developer.mozilla.org/fr/docs/Mozilla/Add-ons/WebExtensions/API/management Retrieves information about all installed add-ons. ```APIDOC ## GET /management.getAll ### Description Renvoie des informations sur tous les modules complémentaires installés. ### Method GET ### Endpoint `management.getAll()` ### Parameters None ### Response #### Success Response (200) - **extensions** (array of `management.ExtensionInfo`) - A list of installed add-ons. #### Response Example ```json { "extensions": [ { "id": "extension_id_1", "name": "Example Extension 1", "version": "1.0", "enabled": true }, { "id": "extension_id_2", "name": "Example Extension 2", "version": "2.1", "enabled": false } ] } ``` ``` -------------------------------- ### Example Usage of keyPath Source: https://developer.mozilla.org/fr/docs/Web/API/IDBObjectStore/keyPath Demonstrates how to initialize a transaction, add data to an object store, and log the `keyPath`. ```APIDOC ## Example: Initializing Transaction and Adding Data ### Description This example shows how to set up an IndexedDB transaction, add an object to an object store, and then inspect the `keyPath` property of that store. ### Method POST (implicitly via `add()`) ### Endpoint `IDBObjectStore.add()` and accessing `IDBObjectStore.keyPath` ### Parameters #### Request Body (for `add()`) - **value** (any) - Required - The value to be stored. ### Request Example ```javascript // Assume 'db' is an IDBDatabase instance and 'objectStore' is an IDBObjectStore instance const transaction = db.transaction(['myObjectStore'], 'readwrite'); const objectStore = transaction.objectStore('myObjectStore'); const myObject = { name: 'Example Item', value: 123 }; const request = objectStore.add(myObject); request.onsuccess = (event) => { console.log('Object added successfully:', event.target.result); // Accessing keyPath after adding data console.log('Object store keyPath:', objectStore.keyPath); }; transaction.oncomplete = () => { console.log('Transaction completed.'); }; transaction.onerror = (event) => { console.error('Transaction error:', event.target.error); }; ``` ### Response #### Success Response (200) - **Object added successfully:** (IDBKey) - The key of the newly added object. - **Object store keyPath:** (string | null) - The key path of the object store. ``` -------------------------------- ### WebGL Tutorial Source: https://developer.mozilla.org/fr/docs/Web/API/WebGL_API/Tutorial/Using_textures_in_WebGL A step-by-step tutorial for learning WebGL. ```APIDOC ## WebGL Tutorial This tutorial covers the fundamentals of WebGL and progresses to more advanced topics. ### Tutorial Sections: - Getting started with WebGL - Adding content to WebGL - Adding colors with shaders - Animating objects with WebGL - Creating 3D objects with WebGL - Using textures in WebGL - Lighting in WebGL - Animating textures in WebGL ``` -------------------------------- ### Register extension names on install Source: https://developer.mozilla.org/fr/docs/Mozilla/Add-ons/WebExtensions/API/management/onInstalled Example demonstrating how to log the name of an extension when it is installed. ```javascript browser.management.onInstalled.addListener((info) => { console.log(`Extension installed: ${info.name}`); }); ``` -------------------------------- ### Accessing the database connection within a transaction Source: https://developer.mozilla.org/fr/docs/Web/API/IDBTransaction/db This example demonstrates opening a database connection, starting a read/write transaction, accessing an object store, and using the `db` property to get the database connection associated with the transaction. It also shows how to handle transaction completion and errors. ```javascript let db; const request = indexedDB.open("toDoList"); request.onerror = (event) => { console.error("Unable to open database: " + event.target.errorCode); }; request.onupgradeneeded = (event) => { const database = event.target.result; database.createObjectStore("toDoList", { keyPath: "id" }); }; request.onsuccess = (event) => { db = event.target.result; console.log("Database opened successfully"); // start a transaction const transaction = db.transaction(["toDoList"], "readwrite"); // add record const objectStore = transaction.objectStore("toDoList"); objectStore.add({ id: 1, task: "Sample task", priority: "high" }); // event handler for transaction completion transaction.oncomplete = (event) => { console.log("All done!"); }; // event handler for transaction errors transaction.onerror = (event) => { console.error("Transaction failed: " + event.target.error); }; // Get the connection to the database associated with the transaction const dbConnection = transaction.db; console.log("Database connection from transaction: " + dbConnection); }; ``` -------------------------------- ### Create a bookmark Source: https://developer.mozilla.org/fr/docs/Mozilla/Add-ons/WebExtensions/API/bookmarks/create This example demonstrates how to create a bookmark for a given URL, placing it in the default bookmark folder. ```javascript bookmarks.create({ url: "https://developer.mozilla.org", title: "MDN Web Docs" }); ``` -------------------------------- ### Get element tagName in HTML Source: https://developer.mozilla.org/fr/docs/Web/API/Element/tagName This example demonstrates how to get the tagName of an HTML element. The returned value will always be in uppercase. ```html
This is a paragraph.
``` -------------------------------- ### Resetting list-item counter to start from 3 Source: https://developer.mozilla.org/fr/docs/Web/CSS/Reference/Properties/counter-reset Use `counter-reset` to set the starting value for the implicit `list-item` counter. This example shows how to make an ordered list start numbering from 4. ```css ol { counter-reset: list-item 3; } ``` -------------------------------- ### WebAssembly Example: instantiateStreaming Source: https://developer.mozilla.org/fr/docs/WebAssembly/Reference/JavaScript_interface An example demonstrating how to fetch, compile, and instantiate a WebAssembly module using `instantiateStreaming()`. ```APIDOC ## Example: instantiateStreaming This example shows how to fetch a WebAssembly module via a stream, compile, and instantiate it using `WebAssembly.instantiateStreaming()`. ### Request Example ```javascript fetch('module.wasm') .then(response => WebAssembly.instantiateStreaming(response)) .then(result => { const instance = result.instance; // Call an exported function from the WebAssembly module instance.exports.myFunction(); }); ``` ### Response Example ```json { "module": WebAssembly.Module, "instance": WebAssembly.Instance } ``` ``` -------------------------------- ### Example Usage Source: https://developer.mozilla.org/fr/docs/Web/API/IDBIndex An example demonstrating how to open a transaction, access an object store, and then iterate over an index using `openCursor`. ```APIDOC ## Example This example demonstrates opening a transaction, accessing an object store, and then iterating over an index named `lName` using `IDBIndex.openCursor`. The data from the index records is then inserted into an HTML table. The `IDBIndex.openCursor` method functions similarly to `IDBObjectStore.openCursor`, but the records are returned in the order of the index, not the object store. ```javascript // Assume db is an IDBDatabase instance and 'storeName' is the name of the object store const transaction = db.transaction(storeName, 'readonly'); const store = transaction.objectStore(storeName); const index = store.index('lName'); // Get the index named 'lName' const request = index.openCursor(); request.onsuccess = (event) => { const cursor = event.target.result; if (cursor) { // Process the cursor.value (the record) console.log('Key:', cursor.key, 'Value:', cursor.value); // Insert data into HTML table here... cursor.continue(); // Move to the next record } else { console.log('Finished iterating through index.'); } }; request.onerror = (event) => { console.error('Error opening cursor:', event.target.error); }; ``` **Note:** For a complete working example, refer to our To-do Notifications app (view example live). ``` -------------------------------- ### Example: Getting direct descendants with the :scope pseudo-class Source: https://developer.mozilla.org/fr/docs/Web/API/Element/querySelector This example uses the :scope pseudo-class to retrieve the direct children of a parent element. ```APIDOC ## Example: Getting direct descendants with the :scope pseudo-class ### Description Retrieves the direct children of a specific element using the `:scope` pseudo-class. ### Method `querySelector()` ### Endpoint Called on an `Element` object. ### Parameters #### Arguments - **selectors** (string) - Required - The CSS selector string, e.g., `':scope > div'` ### Request Body N/A ### Response #### Success Response (200) - **Element** - The first direct child matching the selector, or `null` if no match is found. ### Example ```htmlThis domain is for use in illustrative examples in documents. You may use this domain in literature without prior coordination or asking for permission.
``` -------------------------------- ### Example Manifest Configuration Source: https://developer.mozilla.org/fr/docs/Mozilla/Add-ons/WebExtensions/manifest.json/browser_specific_settings An example of a manifest.json file including all possible keys within browser_specific_settings. ```APIDOC { "manifest_version": 2, "name": "My Extension", "version": "1.0", "browser_specific_settings": { "gecko": { "id": "extensionname@example.org", "strict_min_version": "50.0", "strict_max_version": "60.0", "update_url": "https://example.com/updates.json" }, "edge": { "browser_action_next_to_addressbar": true } } } ``` -------------------------------- ### Defer a GET request until the page is exited or closed Source: https://developer.mozilla.org/fr/docs/Web/API/Window/fetchLater This example shows how to defer a GET request. The request will be sent when the page is exited or closed. ```javascript window.fetchLater("/api/data"); ``` -------------------------------- ### Examples of Creating an Int32Array Source: https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Global_Objects/Int32Array Demonstrates various ways to create and initialize an Int32Array. ```APIDOC ## Examples of Creating an Int32Array ### Description This section provides examples of different methods to create an `Int32Array`. ### Method JavaScript Constructor and Methods ### Endpoint N/A ### Parameters N/A ### Request Body N/A ### Response N/A ### Request Example ```javascript // Using the constructor with an array-like object const arrayLike = { 0: 10, 1: 20, length: 2 }; const int32Array1 = new Int32Array(arrayLike); console.log(int32Array1); // Int32Array(2) [ 10, 20 ] // Using the constructor with another typed array const sourceArray = new Int16Array([100, 200, 300]); const int32Array2 = new Int32Array(sourceArray); console.log(int32Array2); // Int32Array(3) [ 100, 200, 300 ] // Using the constructor with an ArrayBuffer and byte offset/length const buffer = new ArrayBuffer(16); const int32Array3 = new Int32Array(buffer, 4, 2); // Creates a view of 2 elements starting at byte offset 4 console.log(int32Array3); // Int32Array(2) [ 0, 0 ] // Creating an Int32Array with a specific length (initialized to zeros) const int32Array4 = new Int32Array(5); console.log(int32Array4); // Int32Array(5) [ 0, 0, 0, 0, 0 ] ``` ``` -------------------------------- ### Get a cookie by name Source: https://developer.mozilla.org/fr/docs/Web/API/Document/cookie To retrieve a specific cookie, you need to parse the `document.cookie` string. This example shows how to get a cookie named 'test2'. ```javascript function getCookie(name) { const value = ((`"${document.cookie}"`).match(new RegExp(`(^|; )("${name}")=([^;]*)`)) || [])[3]; return value; } let test2 = getCookie('test2'); ``` -------------------------------- ### Example URL Structure Source: https://developer.mozilla.org/fr/docs/Learn_web_development/Getting_started/Web_standards/How_the_web_works This example shows the basic structure of a URL, including the protocol, domain name, and path. ```text https://developer.mozilla.org/fr/ ``` -------------------------------- ### Attach Message Handler and Start Port Source: https://developer.mozilla.org/fr/docs/Web/API/MessageEvent This example shows how to attach an onmessage event handler to a MessagePort and then manually start the port using its start() method. This is necessary when using addEventListener for the onmessage event. ```javascript myWorker.port.addEventListener('message', function(e) { console.log('Result: ' + e.data); }); myWorker.port.start(); ``` -------------------------------- ### WebVTT Cue Structure Example Source: https://developer.mozilla.org/fr/docs/Web/API/WebVTT_API This example illustrates the structure of WebVTT cues, showing timestamps and the associated text. Each cue has a start and end time. ```vtt WEBVTT 00:01.000 --> 00:04.000 - Never drink liquid nitrogen. 00:05.000 --> 00:09.000 - It will perforate your stomach. - You could die. ``` -------------------------------- ### JavaScript Window.matchMedia() Example Source: https://developer.mozilla.org/fr/docs/Web/Accessibility/Guides/Seizure_disorders Demonstrates how to use the `Window.matchMedia()` API to check for specific media query conditions, such as color scheme preferences. ```javascript const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)'); function handleColorSchemeChange(e) { if (e.matches) { // Dark mode is active console.log('Dark mode is enabled'); } else { // Light mode is active console.log('Light mode is enabled'); } } mediaQuery.addEventListener('change', handleColorSchemeChange); // Initial check handleColorSchemeChange(mediaQuery); ``` -------------------------------- ### Get all own property names of an object Source: https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertyNames This example demonstrates how to get all own property names of an object, including non-enumerable ones. It shows that inherited properties are not included. ```javascript const object1 = {}; object1.property1 = 42; console.log(Object.getOwnPropertyNames(object1)); // Expected output: ["property1"] ``` ```javascript const array1 = [5, 10, 15]; console.log(Object.getOwnPropertyNames(array1)); // Expected output: ["0", "1", "2", "length"] ``` ```javascript function MyClass() { this.prop1 = 1; this.prop2 = 2; } MyClass.prototype.protoProp = 3; const obj = new MyClass(); obj.prop3 = 4; console.log(Object.getOwnPropertyNames(obj)); // Expected output: ["prop1", "prop2", "prop3"] ``` -------------------------------- ### Example Usage Source: https://developer.mozilla.org/fr/docs/WebAssembly/Reference/JavaScript_interface/Table/length Demonstrates how to create a WebAssembly table and access its length property. ```APIDOC ## Example Usage ### Description This example shows how to create a WebAssembly table with an initial and maximum size, and then how to extend it and check its length. ### Method JavaScript API calls ### Endpoint N/A (JavaScript execution) ### Parameters None ### Request Example ```javascript // Create a table with an initial size of 2 and a maximum size of 10 const table = new WebAssembly.Table({ initial: 2, maximum: 10 }); // Extend the table by one element table.grow(1); // Get the current length of the table const currentLength = table.length; console.log(currentLength); // Output: 3 ``` ### Response #### Success Response (200) - **console.log output** (number) - The current length of the WebAssembly table. #### Response Example ``` 3 ``` ``` -------------------------------- ### Get the root node of an element Source: https://developer.mozilla.org/fr/docs/Web/API/Node/getRootNode This example demonstrates how to get the root node of an element. It returns a reference to the HTML/document node when executed in supporting browsers. ```javascript const root = document.body.getRootNode(); ``` -------------------------------- ### Example of Navigator.getUserMedia() with browser prefix compatibility Source: https://developer.mozilla.org/fr/docs/Web/API/Navigator/getUserMedia This example demonstrates how to use Navigator.getUserMedia() while handling browser prefix compatibility. It is noted as a discouraged approach, and users are directed to examples using MediaDevices.getUserMedia() for best practices. ```javascript var constraints = { audio: false, video: true }; function successCallback(mediaStream) { var video = document.querySelector('video'); // stream the media to the video element video.srcObject = mediaStream; } function errorCallback(mediaError) { console.log('navigator.getUserMedia error: ', mediaError); } navigator.getUserMedia(constraints, successCallback, errorCallback); // Older browsers might need this: // navigator.webkitGetUserMedia(constraints, successCallback, errorCallback); // navigator.mozGetUserMedia(constraints, successCallback, errorCallback); // navigator.msGetUserMedia(constraints, successCallback, errorCallback); // navigator.oGetUserMedia(constraints, successCallback, errorCallback); ``` -------------------------------- ### Get Permission Warnings by Manifest String Source: https://developer.mozilla.org/fr/docs/Mozilla/Add-ons/WebExtensions/API/management/getPermissionWarningsByManifest This example shows how to get permission warnings for a given manifest string. It assumes you have a valid manifest string. ```javascript management.getPermissionWarningsByManifest({ // manifest.json content as a string manifestString: "{\"manifest_version\": 2, \"name\": \"My extension\", \"version\": \"1.0\", \"permissions\": [\"tabs\"]}" }).then(warnings => { console.log(warnings); }); ``` -------------------------------- ### Example Usage Source: https://developer.mozilla.org/fr/docs/Web/API/Headers Demonstrates creating and manipulating Headers objects. ```APIDOC ## Example Usage ### Creating and Appending Headers ```javascript // Create a new Headers object const myHeaders = new Headers(); // Add a new header using append() myHeaders.append('Content-Type', 'application/json'); myHeaders.append('X-Custom-Header', 'value1'); // Get the value of a header console.log(myHeaders.get('Content-Type')); // Output: application/json console.log(myHeaders.get('X-Custom-Header')); // Output: value1 // Check if a header exists console.log(myHeaders.has('Content-Type')); // Output: true // Iterate over headers for (const pair of myHeaders.entries()) { console.log(pair[0] + ": " + pair[1]); } // Output: // Content-Type: application/json // X-Custom-Header: value1 ``` ### Initializing Headers with Data ```javascript // Initialize with an object literal const headersFromObject = new Headers({ "Authorization": "Bearer token123", "Accept": "application/xml" }); console.log(headersFromObject.get('Authorization')); // Output: Bearer token123 // Initialize with an array of arrays const headersFromArray = new Headers([ ['User-Agent', 'MyClient/1.0'], ['Cache-Control', 'no-cache'] ]); console.log(headersFromArray.get('User-Agent')); // Output: MyClient/1.0 ``` ``` -------------------------------- ### SVG