### GET Request Example Source: https://github.com/microsoftedge/microsoftedge-documentation/blob/master/_autodocs/08-fetch-xmlhttprequest-api.md Demonstrates how to perform a GET request to fetch JSON data. Sets request headers, response type, and timeout. Includes handlers for load, error, and timeout events. ```javascript const xhr = new XMLHttpRequest(); xhr.open('GET', 'https://api.example.com/users', true); xhr.setRequestHeader('Accept', 'application/json'); xhr.responseType = 'json'; xhr.timeout = 5000; xhr.onload = function() { if (xhr.status === 200) { console.log('Users:', xhr.response); } else { console.error('Error:', xhr.status); } }; xhr.onerror = function() { console.error('Network error'); }; xhr.ontimeout = function() { console.error('Request timed out'); }; xhr.send(); ``` -------------------------------- ### XMLHttpRequest Usage Examples Source: https://github.com/microsoftedge/microsoftedge-documentation/blob/master/_autodocs/08-fetch-xmlhttprequest-api.md Practical examples demonstrating how to use XMLHttpRequest for common scenarios like GET requests, POST requests, and file uploads. ```APIDOC **Example**: ```javascript const xhr = new XMLHttpRequest(); xhr.open('GET', 'https://api.example.com/users', true); xhr.setRequestHeader('Accept', 'application/json'); xhr.responseType = 'json'; xhr.timeout = 5000; xhr.onload = function() { if (xhr.status === 200) { console.log('Users:', xhr.response); } else { console.error('Error:', xhr.status); } }; xhr.onerror = function() { console.error('Network error'); }; xhr.ontimeout = function() { console.error('Request timed out'); }; xhr.send(); ``` #### POST Example: ```javascript const xhr = new XMLHttpRequest(); xhr.open('POST', 'https://api.example.com/users', true); xhr.setRequestHeader('Content-Type', 'application/json'); xhr.onload = function() { if (xhr.status === 201) { console.log('User created:', xhr.response); } }; xhr.send(JSON.stringify({ name: 'Alice', email: 'alice@example.com' })); ``` #### Form Upload Example: ```javascript const xhr = new XMLHttpRequest(); xhr.open('POST', 'https://api.example.com/upload', true); xhr.upload.onprogress = function(event) { if (event.lengthComputable) { const percent = (event.loaded / event.total) * 100; console.log(`Upload progress: ${percent}%`); } }; xhr.onload = function() { if (xhr.status === 200) { console.log('Upload complete'); } }; const formData = new FormData(); formData.append('file', fileInput.files[0]); formData.append('name', 'My File'); xhr.send(formData); ``` ``` -------------------------------- ### Complete Service Worker Example Source: https://github.com/microsoftedge/microsoftedge-documentation/blob/master/_autodocs/10-service-workers-api.md A full service worker implementation demonstrating install, activate, fetch, and message event listeners for caching assets and handling updates. ```javascript // service-worker.js const CACHE_NAME = 'my-app-v1'; const ASSETS_TO_CACHE = [ '/', '/index.html', '/css/style.css', '/js/app.js', '/images/logo.png' ]; // Install: Cache resources self.addEventListener('install', (event) => { event.waitUntil( caches.open(CACHE_NAME).then(cache => { return cache.addAll(ASSETS_TO_CACHE); }) ); self.skipWaiting(); // Activate immediately }); // Activate: Cleanup old caches self.addEventListener('activate', (event) => { event.waitUntil( caches.keys().then(cacheNames => { return Promise.all( cacheNames .filter(name => name !== CACHE_NAME) .map(name => caches.delete(name)) ); }) ); self.clients.claim(); // Claim all pages }); // Fetch: Serve from cache, fallback to network self.addEventListener('fetch', (event) => { const { request } = event; if (request.method !== 'GET') { return; } event.respondWith( caches.match(request) .then(response => { if (response) { return response; } return fetch(request).then(response => { // Cache successful responses if (response.status === 200 && response.type !== 'error') { const cache = caches.open(CACHE_NAME); cache.then(c => c.put(request, response.clone())); } return response; }); }) .catch(() => { // Return offline page if available return caches.match('/offline.html') || new Response('Offline - page not available'); }) ); }); // Message: Handle commands from pages self.addEventListener('message', (event) => { if (event.data.type === 'CLEAR_CACHE') { caches.delete(CACHE_NAME).then(() => { event.ports[0]?.postMessage({ cleared: true }); }); } }); ``` -------------------------------- ### Complete Example Source: https://github.com/microsoftedge/microsoftedge-documentation/blob/master/_autodocs/07-indexeddb-api.md A comprehensive example demonstrating how to open/create an IndexedDB database, define object stores and indexes, insert data, and perform various types of queries. ```javascript // Open/create database const request = window.indexedDB.open('myStore', 1); request.onupgradeneeded = function(event) { const db = event.target.result; // Create object store if (!db.objectStoreNames.contains('users')) { const store = db.createObjectStore('users', { keyPath: 'id', autoIncrement: true }); // Create indexes store.createIndex('email', 'email', { unique: true }); store.createIndex('name', 'name'); } }; request.onsuccess = function(event) { const db = event.target.result; // Insert data const transaction = db.transaction('users', 'readwrite'); const store = transaction.objectStore('users'); store.add({ name: 'Alice', email: 'alice@example.com', age: 30 }); // Query by key const getRequest = store.get(1); getRequest.onsuccess = function(event) { console.log('Retrieved:', event.target.result); }; // Query by index const emailIndex = store.index('email'); const emailRequest = emailIndex.get('alice@example.com'); emailRequest.onsuccess = function(event) { console.log('User by email:', event.target.result); }; // Range query const rangeRequest = store.getAll( IDBKeyRange.bound(1, 10), 5 // limit to 5 results ); rangeRequest.onsuccess = function(event) { console.log('Range results:', event.target.result); }; transaction.oncomplete = function() { console.log('All operations complete'); }; }; ``` -------------------------------- ### Fetch API Example Source: https://github.com/microsoftedge/microsoftedge-documentation/blob/master/_autodocs/08-fetch-xmlhttprequest-api.md Demonstrates how to make a GET request using the Fetch API and process the response. Accesses response status, headers, and JSON data. ```javascript const response = await fetch('https://api.example.com/data'); console.log('Status:', response.status); console.log('Headers:', response.headers.get('content-type')); const data = await response.json(); console.log('Data:', data); ``` -------------------------------- ### Service Worker Cache Example Source: https://github.com/microsoftedge/microsoftedge-documentation/blob/master/_autodocs/10-service-workers-api.md Demonstrates how to use the Cache interface within a service worker to cache assets during installation and handle fetch events. ```javascript // service-worker.js const CACHE_NAME = 'v1'; self.addEventListener('install', (event) => { event.waitUntil( caches.open(CACHE_NAME).then(cache => { return cache.addAll([ '/', '/index.html', '/style.css', '/app.js' ]); }) ); }); self.addEventListener('fetch', (event) => { event.respondWith( caches.match(event.request).then(response => { // Return cached response or fetch new return response || fetch(event.request).then(freshResponse => { // Cache the new response if (event.request.method === 'GET' && freshResponse.status === 200) { const cache = caches.open(CACHE_NAME); cache.then(c => c.put(event.request, freshResponse.clone())); } return freshResponse; }); }) ); }); ``` -------------------------------- ### ExtendableEvent waitUntil Example Source: https://github.com/microsoftedge/microsoftedge-documentation/blob/master/_autodocs/10-service-workers-api.md Demonstrates using waitUntil within an install event to ensure the service worker does not terminate until a promise settles, such as cache population. ```javascript self.addEventListener('install', (event) => { // Service worker won't terminate until cache populated event.waitUntil( caches.open('v1').then(cache => cache.addAll([...])) ); }); ``` -------------------------------- ### Complete Payment Flow Example Source: https://github.com/microsoftedge/microsoftedge-documentation/blob/master/_autodocs/11-payment-request-api.md This example demonstrates a full payment flow using the Payment Request API, including defining payment methods, calculating totals, handling shipping and address changes, and processing the payment. ```javascript // Define supported payment methods const methodData = [ { supportedMethods: ['basic-card'], data: { supportedNetworks: ['visa', 'mastercard', 'amex'], supportedTypes: ['credit', 'debit'] } } ]; // Define payment details function getPaymentDetails(shippingOption = 'standard') { const shippingCosts = { standard: '10.00', express: '25.00', pickup: '0.00' }; const shippingCost = shippingCosts[shippingOption]; const subtotal = '29.99'; const tax = '4.00'; // Simplified const total = ( parseFloat(subtotal) + parseFloat(shippingCost) + parseFloat(tax) ).toFixed(2); return { total: { label: 'Total Amount', amount: { currency: 'USD', value: total } }, displayItems: [ { label: 'Subtotal', amount: { currency: 'USD', value: subtotal } }, { label: 'Shipping', amount: { currency: 'USD', value: shippingCost } }, { label: 'Tax', amount: { currency: 'USD', value: tax } } ], shippingOptions: [ { id: 'standard', label: 'Standard Shipping (5-7 days)', amount: { currency: 'USD', value: shippingCosts.standard }, selected: shippingOption === 'standard' }, { id: 'express', label: 'Express Shipping (2-3 days)', amount: { currency: 'USD', value: shippingCosts.express }, selected: shippingOption === 'express' }, { id: 'pickup', label: 'In-Store Pickup', amount: { currency: 'USD', value: shippingCosts.pickup }, selected: shippingOption === 'pickup' } ] }; } // Create payment request const details = getPaymentDetails(); const options = { requestPayerName: true, requestPayerEmail: true, requestPayerPhone: true, requestShipping: true, shippingType: 'shipping' }; const paymentRequest = new PaymentRequest(methodData, details, options); // Handle shipping option changes paymentRequest.addEventListener('shippingoptionchange', (event) => { const newDetails = getPaymentDetails(event.target.shippingOption); event.updateWith(newDetails); }); // Handle address changes (for tax, shipping rate updates) paymentRequest.addEventListener('shippingaddresschange', (event) => { const address = event.target.shippingAddress; // Validate address if (!address.postalCode) { event.updateWith({ error: 'Postal code is required' }); return; } // Recalculate based on address (state tax, etc.) const newDetails = getPaymentDetails(paymentRequest.shippingOption); event.updateWith(newDetails); }); // Check if user can make payment paymentRequest.canMakePayment().then(canPay => { if (canPay) { document.getElementById('payButton').disabled = false; } }); // Handle payment button click document.getElementById('payButton').addEventListener('click', async () => { try { const paymentResponse = await paymentRequest.show(); // Send to server const result = await fetch('/api/checkout', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ methodName: paymentResponse.methodName, details: paymentResponse.details, payerName: paymentResponse.payerName, payerEmail: paymentResponse.payerEmail, payerPhone: paymentResponse.payerPhone, shippingAddress: paymentResponse.shippingAddress, shippingOption: paymentResponse.shippingOption }) }); if (result.ok) { await paymentResponse.complete('success'); console.log('Payment successful'); // Redirect to confirmation page window.location.href = '/order-confirmation'; } else { await paymentResponse.complete('fail'); console.error('Payment failed'); } } catch (error) { console.error('Payment error:', error); } }); ``` -------------------------------- ### Example Usage Source: https://github.com/microsoftedge/microsoftedge-documentation/blob/master/_autodocs/10-service-workers-api.md Example code demonstrating how to use the ServiceWorkerRegistration interface for checking updates, listening for them, and unregistering. ```APIDOC ## Example ```javascript // Check for updates registration.update(); // Listen for updates registration.onupdatefound = function() { const newWorker = registration.installing; newWorker.onStateChange = function() { if (newWorker.state === 'activated') { console.log('New service worker activated'); // Prompt user to reload page } }; }; // Unregister registration.unregister().then(success => { if (success) { console.log('Service Worker unregistered'); } }); ``` ``` -------------------------------- ### Service Worker Cache Example Source: https://github.com/microsoftedge/microsoftedge-documentation/blob/master/_autodocs/10-service-workers-api.md An example demonstrating how to use the Cache interface within a service worker to cache assets during installation and handle fetch events. ```APIDOC ## Example: ```javascript // service-worker.js const CACHE_NAME = 'v1'; self.addEventListener('install', (event) => { event.waitUntil( caches.open(CACHE_NAME).then(cache => { return cache.addAll([ '/', '/index.html', '/style.css', '/app.js' ]); }) ); }); self.addEventListener('fetch', (event) => { event.respondWith( caches.match(event.request).then(response => { // Return cached response or fetch new return response || fetch(event.request).then(freshResponse => { // Cache the new response if (event.request.method === 'GET' && freshResponse.status === 200) { const cache = caches.open(CACHE_NAME); cache.then(c => c.put(event.request, freshResponse.clone())); } return freshResponse; }); }) ); }); ``` ``` -------------------------------- ### Service Worker install Event Source: https://github.com/microsoftedge/microsoftedge-documentation/blob/master/_autodocs/10-service-workers-api.md Handles the installation of a new service worker. Use waitUntil to ensure asynchronous operations like cache population complete before the installation is finalized. ```javascript // service-worker.js self.addEventListener('install', (event) => { console.log('Service Worker installing...'); // Perform installation setup event.waitUntil( caches.open('v1').then(cache => { return cache.addAll([ '/', '/index.html', '/styles.css', '/app.js' ]); }) ); }); ``` -------------------------------- ### Open/Create IndexedDB Database and Schema Setup Source: https://github.com/microsoftedge/microsoftedge-documentation/blob/master/_autodocs/07-indexeddb-api.md Use this snippet to open or create an IndexedDB database and define its schema, including object stores and indexes. The `onupgradeneeded` event is crucial for schema migrations. ```javascript // Open/create database const request = window.indexedDB.open('myStore', 1); request.onupgradeneeded = function(event) { const db = event.target.result; // Create object store if (!db.objectStoreNames.contains('users')) { const store = db.createObjectStore('users', { keyPath: 'id', autoIncrement: true }); // Create indexes store.createIndex('email', 'email', { unique: true }); store.createIndex('name', 'name'); } }; ``` -------------------------------- ### Form Upload Example with Progress Source: https://github.com/microsoftedge/microsoftedge-documentation/blob/master/_autodocs/08-fetch-xmlhttprequest-api.md Demonstrates uploading a file using FormData and tracking upload progress. Includes an `onprogress` handler for the upload object to display percentage completion. ```javascript const xhr = new XMLHttpRequest(); xhr.open('POST', 'https://api.example.com/upload', true); xhr.upload.onprogress = function(event) { if (event.lengthComputable) { const percent = (event.loaded / event.total) * 100; console.log(`Upload progress: ${percent}%`); } }; xhr.onload = function() { if (xhr.status === 200) { console.log('Upload complete'); } }; const formData = new FormData(); formData.append('file', fileInput.files[0]); formData.append('name', 'My File'); xhr.send(formData); ``` -------------------------------- ### POST Request Example Source: https://github.com/microsoftedge/microsoftedge-documentation/blob/master/_autodocs/08-fetch-xmlhttprequest-api.md Shows how to send data using a POST request. Sets the 'Content-Type' header and sends a JSON string as the request body. Handles successful creation (status 201). ```javascript const xhr = new XMLHttpRequest(); xhr.open('POST', 'https://api.example.com/users', true); xhr.setRequestHeader('Content-Type', 'application/json'); xhr.onload = function() { if (xhr.status === 201) { console.log('User created:', xhr.response); } }; xhr.send(JSON.stringify({ name: 'Alice', email: 'alice@example.com' })); ``` -------------------------------- ### Service Worker Activate and Claim Example Source: https://github.com/microsoftedge/microsoftedge-documentation/blob/master/_autodocs/10-service-workers-api.md Demonstrates how to use self.clients.claim() within the 'activate' event listener of a service worker to take control of clients. It also shows how to notify these clients later. ```javascript // In service worker self.addEventListener('activate', (event) => { event.waitUntil(self.clients.claim()); }); // Later, notify all clients self.clients.matchAll().then(clients => { clients.forEach(client => { client.postMessage({ type: 'UPDATE_AVAILABLE' }); }); }); ``` -------------------------------- ### Cleanup old caches Source: https://github.com/microsoftedge/microsoftedge-documentation/blob/master/_autodocs/10-service-workers-api.md An example of how to iterate through all existing caches, filter out a specific cache (e.g., 'v2'), and delete the rest. ```javascript // Cleanup old caches caches.keys().then(cacheNames => { return Promise.all( cacheNames .filter(name => name !== 'v2') .map(name => caches.delete(name)) ); }); ``` -------------------------------- ### Retrieve User by Email Index Source: https://github.com/microsoftedge/microsoftedge-documentation/blob/master/_autodocs/07-indexeddb-api.md An example demonstrating how to retrieve a user object from an object store using the 'email' index. It shows the typical pattern of making a request and handling the success event. ```javascript const emailIndex = store.index('email'); const request = emailIndex.get('alice@example.com'); request.onsuccess = function(event) { const user = event.target.result; console.log('User by email:', user); }; ``` -------------------------------- ### Display Payment UI and Get Response Source: https://github.com/microsoftedge/microsoftedge-documentation/blob/master/_autodocs/11-payment-request-api.md Use the `show()` method to display the payment UI. It returns a Promise that resolves with payment details upon completion or rejects on error. Process the response by sending it to your backend for final processing. ```javascript paymentRequest.show() .then(paymentResponse => { console.log('Payment method:', paymentResponse.details); console.log('Payer:', { name: paymentResponse.payerName, email: paymentResponse.payerEmail, phone: paymentResponse.payerPhone }); // Process payment with your backend return fetch('/process-payment', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(paymentResponse) }); }) .then(response => { if (response.ok) { paymentResponse.complete('success'); } else { paymentResponse.complete('fail'); } }) .catch(error => { console.error('Payment error:', error); }); ``` -------------------------------- ### Accessing HTMLOptionsCollection by Index Source: https://github.com/microsoftedge/microsoftedge-documentation/blob/master/_autodocs/01-html-elements-api.md Shows how to get a specific option from an HTMLOptionsCollection using its index. ```javascript const selectElement = document.getElementById('mySelect'); const firstOption = selectElement.options.item(0); ``` -------------------------------- ### Open Cursor for Iteration Source: https://github.com/microsoftedge/microsoftedge-documentation/blob/master/_autodocs/07-indexeddb-api.md Opens a cursor to iterate through objects in the store, allowing access to both key and value. Includes an example of iterating and continuing the cursor. ```javascript const request = objectStore.openCursor(IDBKeyRange.lowerBound(10), 'next'); request.onsuccess = function(event) { const cursor = event.target.result; if (cursor) { console.log('Key:', cursor.key, 'Value:', cursor.value); cursor.continue(); // Move to next object } else { console.log('Iteration complete'); } }; ``` -------------------------------- ### StartupTask.requestEnableAsync Source: https://github.com/microsoftedge/microsoftedge-documentation/blob/master/pwa-snippets/tasks/auto-launch.md Requests to enable the startup task for the current app. ```APIDOC ## requestEnableAsync ### Description Requests to enable the startup task for the current app. This may involve user consent. ### Method `IAsyncOperation requestEnableAsync()` ### Remarks This method is asynchronous and returns an `IAsyncOperation` that resolves to a `StartupTaskState` enum value indicating whether the task was enabled. ### Example ```csharp var result = await StartupTask.GetAsync("MyStartupTask").AsTask().Result.requestEnableAsync(); ``` ``` -------------------------------- ### Get Current Geolocation Position Source: https://github.com/microsoftedge/microsoftedge-documentation/blob/master/_autodocs/09-geolocation-api.md Requests the user's current position using `navigator.geolocation.getCurrentPosition`. This example logs detailed coordinate information, including altitude, speed, and heading if available. ```javascript navigator.geolocation.getCurrentPosition(function(position) { const { coords } = position; console.log('Coordinates:'); console.log(` Latitude: ${coords.latitude}°`); console.log(` Longitude: ${coords.longitude}°`); console.log(` Accuracy: ±${coords.accuracy}m`); if (coords.altitude !== null) { console.log(` Altitude: ${coords.altitude}m (±${coords.altitudeAccuracy}m)`); } if (coords.speed !== null) { console.log(` Speed: ${coords.speed} m/s (${(coords.speed * 3.6).toFixed(1)} km/h)`); } if (coords.heading !== null) { console.log(` Heading: ${coords.heading}°`); } }); ``` -------------------------------- ### Instantiate and Navigate WebView Source: https://github.com/microsoftedge/microsoftedge-documentation/blob/master/pwa-snippets/tasks/webview.md Use this snippet to create and navigate an x-ms-webview element. Feature detection is recommended as the WebView is only available in standalone Windows 10 apps. ```JavaScript if (MSHTMLWebViewElement) { var wv = document.createElement('x-ms-webview'); // Use CSS to set width, height and other styles wv.navigate("https://www.bing.com"); document.body.appendChild(wv); } ``` -------------------------------- ### StartupTask.GetAsync Source: https://github.com/microsoftedge/microsoftedge-documentation/blob/master/pwa-snippets/tasks/auto-launch.md Retrieves a StartupTask instance by its instance ID. ```APIDOC ## getAsync ### Description Retrieves a StartupTask instance by its instance ID. ### Method `IAsyncOperation GetAsync(string instanceId)` ### Parameters #### Path Parameters - **instanceId** (string) - Required - The instance ID of the startup task. ### Remarks This method is asynchronous and returns an `IAsyncOperation` that resolves to a `StartupTask` object. ### Example ```csharp var startupTask = await StartupTask.GetAsync("MyStartupTask"); ``` ``` -------------------------------- ### Fetch API: Simple GET Request Source: https://github.com/microsoftedge/microsoftedge-documentation/blob/master/_autodocs/08-fetch-xmlhttprequest-api.md Use this snippet for basic GET requests. It handles response checking and JSON parsing. Ensure the API endpoint is correct and handle potential network errors. ```javascript fetch('https://api.example.com/users') .then(response => { if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); } return response.json(); }) .then(data => console.log(data)) .catch(error => console.error('Error:', error)); ``` -------------------------------- ### Get Current Geolocation Source: https://github.com/microsoftedge/microsoftedge-documentation/blob/master/_autodocs/09-geolocation-api.md Use this method to get the user's current location once. It requires success and optional error callbacks, along with options to control accuracy, timeout, and cache usage. Ensure user permission is granted before calling. ```javascript navigator.geolocation.getCurrentPosition( function(position) { console.log('Latitude:', position.coords.latitude); console.log('Longitude:', position.coords.longitude); console.log('Accuracy:', position.coords.accuracy, 'meters'); console.log('Timestamp:', new Date(position.timestamp)); }, function(error) { if (error.code === error.PERMISSION_DENIED) { console.log('User denied geolocation permission'); } else if (error.code === error.POSITION_UNAVAILABLE) { console.log('Position information unavailable'); } else if (error.code === error.TIMEOUT) { console.log('Location request timed out'); } }, { enableHighAccuracy: true, timeout: 5000, maximumAge: 0 } ); ``` -------------------------------- ### Create IDBKeyRange for Lower Bound Source: https://github.com/microsoftedge/microsoftedge-documentation/blob/master/_autodocs/07-indexeddb-api.md Creates an IDBKeyRange that includes keys greater than or equal to the specified lower bound. If 'open' is true, the range starts strictly greater than the lower bound. Useful for querying records within a specific range starting from a point. ```javascript IDBKeyRange.lowerBound(lower: IDBValidKey, open?: boolean): IDBKeyRange ``` -------------------------------- ### Headers Initialization Source: https://github.com/microsoftedge/microsoftedge-documentation/blob/master/_autodocs/08-fetch-xmlhttprequest-api.md Shows how to create a Headers object and append custom headers for use in a Request. Useful for setting authentication tokens or content types. ```javascript const headers = new Headers(); headers.append('Content-Type', 'application/json'); headers.append('Authorization', 'Bearer token'); const request = new Request('https://api.example.com/data', { headers: headers }); ``` -------------------------------- ### Get Index by Name Source: https://github.com/microsoftedge/microsoftedge-documentation/blob/master/_autodocs/07-indexeddb-api.md Retrieves an IDBIndex object by its name from the object store. ```javascript index(name: string): IDBIndex ``` -------------------------------- ### Get Object Store within Transaction Source: https://github.com/microsoftedge/microsoftedge-documentation/blob/master/_autodocs/07-indexeddb-api.md Retrieves an IDBObjectStore by its name from the current transaction. ```javascript objectStore(name: string): IDBObjectStore ``` -------------------------------- ### Configure PWA for Automatic Launch in AppxManifest Source: https://github.com/microsoftedge/microsoftedge-documentation/blob/master/pwa-snippets/tasks/auto-launch.md Add the uap5 namespace and StartupTask extension to your PWA's Universal Windows app project manifest file. This configures the app to be recognized as a startup task. ```XML ... ... ``` -------------------------------- ### DOM Position/Size Source: https://github.com/microsoftedge/microsoftedge-documentation/blob/master/_autodocs/02-dom-core-api.md Methods for getting an element's position and dimensions, and for controlling scrolling behavior. ```APIDOC ## DOM Position/Size ### Description Retrieve layout information and control scrolling. ### Methods - `getBoundingClientRect(): DOMRect` - Element position and size - `getClientRects(): DOMRectList` - Bounding rectangles for inline elements - `scrollIntoView(options?: boolean|ScrollIntoViewOptions)` - Scroll into view - `scroll(x: number, y: number)` - Set scroll position - `scroll(options: ScrollToOptions)` - Set scroll position with options - `scrollBy(x: number, y: number)` - Adjust scroll position - `scrollBy(options: ScrollToOptions)` - Adjust scroll position with options ``` -------------------------------- ### Attribute Methods Source: https://github.com/microsoftedge/microsoftedge-documentation/blob/master/_autodocs/02-dom-core-api.md Methods for getting, setting, and removing attributes on an element, including support for namespaced attributes. ```APIDOC ## Attribute Methods ### Description Manipulate element attributes using these methods. ### Methods - `getAttribute(qualifiedName: string): string|null` - Get attribute value - `getAttributeNS(namespace: string|null, localName: string): string|null` - Get namespaced attribute - `setAttribute(qualifiedName: string, value: string)` - Set attribute - `setAttributeNS(namespace: string|null, qualifiedName: string, value: string)` - Set namespaced attribute - `removeAttribute(qualifiedName: string)` - Remove attribute - `removeAttributeNS(namespace: string|null, localName: string)` - Remove namespaced attribute - `hasAttribute(qualifiedName: string): boolean` - Check attribute existence - `hasAttributeNS(namespace: string|null, localName: string): boolean` - Check namespaced attribute - `getAttributeNode(qualifiedName: string): Attr|null` - Get attribute node (deprecated) - `setAttributeNode(attr: Attr): Attr|null` - Set attribute node (deprecated) - `removeAttributeNode(attr: Attr): Attr` - Remove attribute node (deprecated) - `toggleAttribute(qualifiedName: string, force?: boolean): boolean` - Toggle attribute ``` -------------------------------- ### WebSocket Subprotocol Negotiation Source: https://github.com/microsoftedge/microsoftedge-documentation/blob/master/_autodocs/05-websocket-api.md Shows how to request specific subprotocols during connection establishment and how to check the negotiated protocol after the connection is opened. ```javascript // Request specific subprotocol(s) const ws = new WebSocket('wss://example.com/socket', ['chat', 'superchat']); ws.onopen = function() { // Check which subprotocol server agreed to console.log('Negotiated protocol:', ws.protocol); if (ws.protocol === 'chat') { // Use chat protocol } else if (ws.protocol === 'superchat') { // Use superchat protocol with extra features } }; ``` -------------------------------- ### Get Multiple Keys Source: https://github.com/microsoftedge/microsoftedge-documentation/blob/master/_autodocs/07-indexeddb-api.md Retrieves the keys of multiple objects, optionally filtering by a query and limiting the count. ```javascript getAllKeys( query?: IDBValidKey | IDBKeyRange, count?: number ): IDBRequest ``` -------------------------------- ### Get Key by Key Source: https://github.com/microsoftedge/microsoftedge-documentation/blob/master/_autodocs/07-indexeddb-api.md Retrieves only the key of an object matching the specified query, without fetching the value. ```javascript getKey(query: IDBValidKey | IDBKeyRange): IDBRequest ``` -------------------------------- ### Get Multiple Objects Source: https://github.com/microsoftedge/microsoftedge-documentation/blob/master/_autodocs/07-indexeddb-api.md Retrieves multiple objects from the store, optionally filtering by a query and limiting the count. ```javascript getAll( query?: IDBValidKey | IDBKeyRange, count?: number ): IDBRequest ``` -------------------------------- ### Get WebGL2 Context Source: https://github.com/microsoftedge/microsoftedge-documentation/blob/master/_autodocs/06-webgl-api.md Retrieves the WebGL2 rendering context for a canvas element. The options are the same as for WebGL 1.0. ```javascript const canvas = document.getElementById('canvas'); const gl = canvas.getContext('webgl2', { // Same options as WebGL 1 }); ``` -------------------------------- ### IDBFactory.open() Source: https://github.com/microsoftedge/microsoftedge-documentation/blob/master/_autodocs/07-indexeddb-api.md Opens or creates a database. It returns an IDBOpenDBRequest object that triggers events for schema upgrades, successful opening, errors, and blocked connections. ```APIDOC ## open() ### Description Opens or creates a database. ### Method ```javascript open(name: string, version?: number): IDBOpenDBRequest ``` ### Parameters #### Path Parameters - **name** (string) - Required - Database name - **version** (number) - Optional - Schema version (positive integer) ### Response Returns `IDBOpenDBRequest` with events: - `onupgradeneeded` - Schema upgrade needed (version mismatch) - `onsuccess` - Database opened - `onerror` - Open failed - `onblocked` - Upgrade blocked by other connections ### Request Example ```javascript const request = window.indexedDB.open('myDB', 1); request.onupgradeneeded = function(event) { const db = event.target.result; if (!db.objectStoreNames.contains('users')) { const store = db.createObjectStore('users', { keyPath: 'id' }); store.createIndex('email', 'email', { unique: true }); } }; request.onsuccess = function(event) { const db = event.target.result; // Use database }; request.onerror = function(event) { console.error('Database open error:', event.target.error); }; ``` ``` -------------------------------- ### Get all cache names Source: https://github.com/microsoftedge/microsoftedge-documentation/blob/master/_autodocs/10-service-workers-api.md Retrieves an array of all currently available cache names. This is useful for managing multiple caches. ```javascript keys(): Promise ``` -------------------------------- ### WebSocket Constructor Source: https://github.com/microsoftedge/microsoftedge-documentation/blob/master/_autodocs/05-websocket-api.md Establishes a new WebSocket connection to the specified URL. Optionally, subprotocols can be requested. ```APIDOC ## WebSocket Constructor ### Description Establishes a persistent connection to a WebSocket server. ### Signature ```javascript new WebSocket(url: string, protocols?: string | string[]): WebSocket ``` ### Parameters #### Path Parameters - **url** (string) - Required - The WebSocket server URL (e.g., `ws://` or `wss://`). - **protocols** (string | string[]) - Optional - Subprotocol(s) to request from the server. ``` -------------------------------- ### show() Source: https://github.com/microsoftedge/microsoftedge-documentation/blob/master/_autodocs/11-payment-request-api.md Displays the payment UI to the user and returns payment details once the user completes the payment process. ```APIDOC ## show() ### Description Display payment UI and return payment details when complete. ### Method Signature ```javascript show(): Promise ``` ### Returns Promise with payment data. ### Example ```javascript paymentRequest.show() .then(paymentResponse => { console.log('Payment method:', paymentResponse.details); console.log('Payer:', { name: paymentResponse.payerName, email: paymentResponse.payerEmail, phone: paymentResponse.payerPhone }); // Process payment with your backend return fetch('/process-payment', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(paymentResponse) }); }) .then(response => { if (response.ok) { paymentResponse.complete('success'); } else { paymentResponse.complete('fail'); } }) .catch(error => { console.error('Payment error:', error); }); ``` ``` -------------------------------- ### Element Properties Source: https://github.com/microsoftedge/microsoftedge-documentation/blob/master/_autodocs/02-dom-core-api.md Access various properties of an Element to get information about its tag name, attributes, dimensions, and styling. ```APIDOC ## Element Properties ### Description Properties provide direct access to an element's characteristics. ### Properties - `tagName` (string) - Element tag name (uppercase) - `localName` (string) - Local tag name (no prefix) - `prefix` (string|null) - Namespace prefix - `namespaceURI` (string|null) - Namespace URI - `id` (string) - Element ID attribute - `className` (string) - CSS class attribute - `classList` (DOMTokenList) - CSS classes (read-only) - `attributes` (NamedNodeMap) - Element attributes - `children` (HTMLCollection) - Child elements (no text nodes) - `childElementCount` (number) - Number of child elements - `firstElementChild` (Element|null) - First child element - `lastElementChild` (Element|null) - Last child element - `previousElementSibling` (Element|null) - Previous element sibling - `nextElementSibling` (Element|null) - Next element sibling - `innerHTML` (string) - Inner HTML serialization - `outerHTML` (string) - Outer HTML serialization - `textContent` (string) - All text content - `clientHeight` (number) - Content height with padding (px) - `clientWidth` (number) - Content width with padding (px) - `clientTop` (number) - Border top width (px) - `clientLeft` (number) - Border left width (px) - `scrollHeight` (number) - Scroll height with hidden overflow - `scrollWidth` (number) - Scroll width with hidden overflow - `scrollTop` (number) - Vertical scroll position (px) - `scrollLeft` (number) - Horizontal scroll position (px) - `offsetHeight` (number) - Element height with border (px) - `offsetWidth` (number) - Element width with border (px) - `offsetTop` (number) - Top offset to offset parent (px) - `offsetLeft` (number) - Left offset to offset parent (px) - `offsetParent` (Element|null) - Offset parent element - `currentStyle` (CSSStyleDeclaration) - Computed styles (IE non-standard) - `runtimeStyle` (CSSStyleDeclaration) - Runtime styles (IE non-standard) - `style` (CSSStyleDeclaration) - Inline styles ``` -------------------------------- ### Fetch API: Request Object Creation Source: https://github.com/microsoftedge/microsoftedge-documentation/blob/master/_autodocs/08-fetch-xmlhttprequest-api.md Demonstrates creating a Request object, which can then be used with fetch. This allows for more complex request configurations or reusing request configurations. ```javascript new Request(input: string | Request, init?: RequestInit) ``` -------------------------------- ### Get Object by Key Source: https://github.com/microsoftedge/microsoftedge-documentation/blob/master/_autodocs/07-indexeddb-api.md Retrieves an object from the store using its key or a key range. Handles success and error cases for the request. ```javascript const request = objectStore.get(1); request.onsuccess = function(event) { const user = event.target.result; if (user) { console.log('User:', user); } else { console.log('User not found'); } }; ``` -------------------------------- ### WebSocket Constructor Source: https://github.com/microsoftedge/microsoftedge-documentation/blob/master/_autodocs/05-websocket-api.md Establishes a new WebSocket connection to the specified URL. Optionally, subprotocols can be requested. ```javascript new WebSocket(url: string, protocols?: string | string[]): WebSocket ``` -------------------------------- ### Get WebGL 1.0 Context Source: https://github.com/microsoftedge/microsoftedge-documentation/blob/master/_autodocs/06-webgl-api.md Retrieves the WebGL rendering context for a canvas element with specified options. Use this for WebGL 1.0. ```javascript const canvas = document.getElementById('canvas'); const gl = canvas.getContext('webgl', { alpha: true, antialias: true, depth: true, stencil: false, preserveDrawingBuffer: false, powerPreference: 'default' }); ``` -------------------------------- ### Start Service Worker Messaging Source: https://github.com/microsoftedge/microsoftedge-documentation/blob/master/_autodocs/10-service-workers-api.md Enable communication with a service worker and send a message. Some browsers require startMessages() to be called before posting messages. ```javascript navigator.serviceWorker.startMessages(); navigator.serviceWorker.controller?.postMessage({ type: 'SYNC_DATA' }); ``` -------------------------------- ### Initialize XMLHttpRequest Source: https://github.com/microsoftedge/microsoftedge-documentation/blob/master/_autodocs/08-fetch-xmlhttprequest-api.md Creates a new XMLHttpRequest object. This is the first step in making an HTTP request. ```javascript new XMLHttpRequest() ``` -------------------------------- ### StartupTask.disable Source: https://github.com/microsoftedge/microsoftedge-documentation/blob/master/pwa-snippets/tasks/auto-launch.md Disables the startup task for the current app. ```APIDOC ## disable ### Description Disables the startup task for the current app. ### Method `void disable()` ### Remarks This method is asynchronous and returns a `Task`. ### Example ```csharp await StartupTask.GetAsync("MyStartupTask").AsTask().Result.disable(); ``` ``` -------------------------------- ### Get Client by ID Source: https://github.com/microsoftedge/microsoftedge-documentation/blob/master/_autodocs/10-service-workers-api.md Retrieves a specific client controlled by the service worker using its unique ID. Returns undefined if no client matches the ID. ```javascript get(id: string): Promise ``` -------------------------------- ### Sending and Receiving Binary Data with WebSocket Source: https://github.com/microsoftedge/microsoftedge-documentation/blob/master/_autodocs/05-websocket-api.md Demonstrates how to configure the WebSocket for binary data reception using 'arraybuffer' and how to send binary data as an ArrayBuffer or a typed array. ```javascript const ws = new WebSocket('wss://example.com/binary'); // Configure for binary data reception ws.binaryType = 'arraybuffer'; ws.onmessage = function(event) { // event.data is ArrayBuffer const view = new Uint8Array(event.data); console.log('Received bytes:', view); }; // Send binary data const buffer = new ArrayBuffer(4); const view = new Uint8Array(buffer); view[0] = 0x00; view[1] = 0x01; view[2] = 0x02; view[3] = 0x03; ws.send(buffer); // Or send typed array directly const arr = new Float32Array([1.0, 2.0, 3.0]); ws.send(arr); ``` -------------------------------- ### Listen for Secondary Tile Activation in JavaScript Source: https://github.com/microsoftedge/microsoftedge-documentation/blob/master/pwa-snippets/tasks/tiles.md Use this code to listen for the 'activated' event and check if the activation was due to a secondary tile launch. This is useful for setting up your app's initial state based on the tile that was clicked. ```JavaScript Windows.UI.WebUI.WebUIApplication.addEventListener("activated", function (activatedEventArgs) { if (activatedEventArgs.kind == Windows.ApplicationModel.Activation.ActivationKind.launch && activatedEventArgs.arguments == "secondary tile arguments") { // Setup app according to specified context } }); ``` -------------------------------- ### Getting WebGL2 Context Source: https://github.com/microsoftedge/microsoftedge-documentation/blob/master/_autodocs/06-webgl-api.md Illustrates how to retrieve a WebGL2 rendering context from an HTML canvas. It highlights that WebGL2 uses the same context options as WebGL 1.0. ```APIDOC ## Getting WebGL2 Context ### Description Retrieve a WebGL2 rendering context from an HTML canvas. This example shows that WebGL2 uses the same context options as WebGL 1.0. ### Code Example ```javascript const canvas = document.getElementById('canvas'); const gl = canvas.getContext('webgl2', { // Same options as WebGL 1 }); ``` ``` -------------------------------- ### Open or Create IndexedDB Database Source: https://github.com/microsoftedge/microsoftedge-documentation/blob/master/_autodocs/07-indexeddb-api.md Use `window.indexedDB.open()` to open an existing database or create a new one. The `onupgradeneeded` event is crucial for defining the database schema, including object stores and indexes, when the version changes. `onsuccess` is called when the database is successfully opened, and `onerror` handles any opening errors. ```javascript const request = window.indexedDB.open('myDB', 1); request.onupgradeneeded = function(event) { const db = event.target.result; if (!db.objectStoreNames.contains('users')) { const store = db.createObjectStore('users', { keyPath: 'id' }); store.createIndex('email', 'email', { unique: true }); } }; request.onsuccess = function(event) { const db = event.target.result; // Use database }; request.onerror = function(event) { console.error('Database open error:', event.target.error); }; ``` -------------------------------- ### Getting WebGL Context Source: https://github.com/microsoftedge/microsoftedge-documentation/blob/master/_autodocs/06-webgl-api.md Demonstrates how to obtain a WebGL rendering context from an HTML canvas element. It shows the use of `getContext` with specific configuration options for WebGL 1.0. ```APIDOC ## Getting WebGL Context ### Description Obtain a WebGL rendering context from an HTML canvas element. This example shows the use of `getContext` with specific configuration options for WebGL 1.0. ### Code Example ```javascript const canvas = document.getElementById('canvas'); const gl = canvas.getContext('webgl', { alpha: true, antialias: true, depth: true, stencil: false, preserveDrawingBuffer: false, powerPreference: 'default' }); ``` ``` -------------------------------- ### Client Query Options Source: https://github.com/microsoftedge/microsoftedge-documentation/blob/master/_autodocs/10-service-workers-api.md Options for filtering clients when using matchAll(). Can include uncontrolled pages or filter by client type. ```javascript { includeUncontrolled?: boolean, type?: 'window' | 'worker' } ``` -------------------------------- ### Configure Web Authentication URIs Source: https://github.com/microsoftedge/microsoftedge-documentation/blob/master/pwa-snippets/tasks/web-authentication-broker.md Specify the start and end URIs for the web authentication broker in a meta tag. This configures the URIs for authentication requests and the redirect endpoint. ```HTML ``` -------------------------------- ### Program Linking Source: https://github.com/microsoftedge/microsoftedge-documentation/blob/master/_autodocs/06-webgl-api.md Functions for creating, attaching shaders, linking, activating, and deleting programs. ```APIDOC ## Program Linking ### Functions - `createProgram(): WebGLProgram`: Create program. - `attachShader(program: WebGLProgram, shader: WebGLShader)`: Attach shader to program. - `linkProgram(program: WebGLProgram)`: Link program. - `useProgram(program: WebGLProgram|null)`: Activate program. - `deleteProgram(program: WebGLProgram)`: Delete program. ``` -------------------------------- ### WebSocket onopen Event Handler Source: https://github.com/microsoftedge/microsoftedge-documentation/blob/master/_autodocs/05-websocket-api.md Handles the 'open' event, which fires when the WebSocket connection is successfully established. This is a good place to send initial data to the server. ```javascript websocket.addEventListener('open', function(event) { console.log('Connected, ready to send data'); websocket.send('Hello, Server!'); }); ``` -------------------------------- ### DOM Node Type Constants Source: https://github.com/microsoftedge/microsoftedge-documentation/blob/master/_autodocs/02-dom-core-api.md These constants represent the different types of nodes within the DOM tree. They are used to identify the nature of a node, for example, when checking its `nodeType` property. ```javascript ELEMENT_NODE = 1 ATTRIBUTE_NODE = 2 TEXT_NODE = 3 CDATA_SECTION_NODE = 4 ENTITY_REFERENCE_NODE = 5 ENTITY_NODE = 6 PROCESSING_INSTRUCTION_NODE = 7 COMMENT_NODE = 8 DOCUMENT_NODE = 9 DOCUMENT_TYPE_NODE = 10 DOCUMENT_FRAGMENT_NODE = 11 NOTATION_NODE = 12 ``` -------------------------------- ### Get Current Location Source: https://github.com/microsoftedge/microsoftedge-documentation/blob/master/_autodocs/09-geolocation-api.md Demonstrates how to retrieve the user's current geographical position once. It includes options for accuracy, timeout, and maximum age, and handles both success and error callbacks. ```javascript function showLocation() { if (!navigator.geolocation) { console.log('Geolocation is not supported by this browser'); return; } const options = { enableHighAccuracy: false, timeout: 5000, maximumAge: 0 }; navigator.geolocation.getCurrentPosition( function(position) { const { latitude, longitude, accuracy } = position.coords; console.log(`Location: ${latitude}, ${longitude}`); console.log(`Accuracy: ${accuracy.toFixed(0)}m`); }, function(error) { console.error('Error getting location:', error.message); }, options ); } ``` -------------------------------- ### Basic WebSocket Connection and Messaging Source: https://github.com/microsoftedge/microsoftedge-documentation/blob/master/_autodocs/05-websocket-api.md Establishes a WebSocket connection, handles connection opening, sends a message, processes incoming messages, and manages connection errors and closures. ```javascript // Connect to WebSocket server const ws = new WebSocket('wss://example.com/socket'); // Handle connection opened ws.onopen = function() { console.log('Connected'); ws.send('Hello Server'); }; // Receive and process messages ws.onmessage = function(event) { const message = event.data; console.log('Received:', message); }; // Handle errors ws.onerror = function(event) { console.error('WebSocket error'); }; // Handle connection closed ws.onclose = function(event) { if (event.wasClean) { console.log('Closed cleanly with code:', event.code); } else { console.log('Connection abruptly closed'); } }; ``` -------------------------------- ### Create WebView in a Separate Process Source: https://github.com/microsoftedge/microsoftedge-documentation/blob/master/pwa-snippets/tasks/webview.md Instantiate a WebView in its own process using MSWebViewProcess. WebViews created with the same MSWebViewProcess object will share the same process. ```JavaScript var wvprocess = new MSWebViewProcess(); // WebViews created with the same MSWebViewProcess object share the same process wvprocess.CreateWebViewAsync().then(function (webview) { webview.navigate("https://www.bing.com"); document.body.appendChild(webview); }); ``` -------------------------------- ### DOMImplementation Methods Source: https://github.com/microsoftedge/microsoftedge-documentation/blob/master/_autodocs/02-dom-core-api.md Methods for creating XML documents, document types, HTML documents, and checking feature support. ```javascript createDocument(namespace, qualifiedName, doctype) createDocumentType(qualifiedName, publicId, systemId) createHTMLDocument(title) hasFeature(feature, version) ```