Search completed in 1.15 seconds.
676 results for "Navigator":
Your results are loading. Please wait...
Navigator - Web APIs
Web › API › Navigator
the navigator interface represents the state and the identity of the user agent.
... a navigator object can be retrieved using the read-only window.navigator property.
... properties doesn't inherit any properties, but implements those defined in navigatorid, navigatorlanguage, navigatoronline, navigatorcontentutils, navigatorstorage, navigatorstorageutils, navigatorconcurrenthardware, navigatorplugins, and navigatorusermedia.
...And 57 more matches
WorkerNavigator - Web APIs
Web › API › WorkerNavigator
the workernavigator interface represents a subset of the navigator interface allowed to be accessed from a worker.
... such an object is initialized for each worker and is available via the workerglobalscope.navigator property obtained by calling window.self.navigator.
... properties the workernavigator interface implements properties from the navigatorid, navigatorlanguage, navigatoronline, navigatordatastore, and navigatorconcurrenthardware interfaces.
...And 16 more matches
Source Navigator - Archive of obsolete content
Archive › Misc top level › Source Navigator
;) --kennykaiyinyu 19:04, 10 june 2008 (pdt) what is source-navigator?
... (quoted from the internet) source-navigator is a source code analysis tool which lets users to edit, browse and build their projects.
...you can also build your projects, either with your own makefile, or by using source-navigator's build system to automatically generate a makefile.
...And 10 more matches
NavigatorID - Web APIs
Web › API › NavigatorID
the navigatorid interface contains methods and properties related to the identity of the browser.
... there is no object of type navigatorid, but other interfaces, like navigator or workernavigator, implement it.
... properties the navigatorid interface doesn't inherit any properties.
...And 10 more matches
NavigatorLanguage - Web APIs
Web › API › NavigatorLanguage
navigatorlanguage contains methods and properties related to the language of the navigator.
... there is no object of type navigatorlanguage, but other interfaces, like navigator or workernavigator, implement it.
... properties the navigatorlanguage interface doesn't inherit any property.
...And 5 more matches
NavigatorPlugins.plugins - Web APIs
Web › API › NavigatorPlugins › plugins
in firefox 29 and later, enumeration of the navigator.plugins array may be restricted as a privacy measure.
... applications that must check for the presence of a browser plugin should query navigator.plugins or navigator.mimetypes by exact name instead of enumerating the navigator.plugins array and comparing every plugin's name.
... syntax var plugins = navigator.plugins; plugins is pluginarray object used to access plugin objects either by name or as a list of items.
...And 4 more matches
The navigator.id API - Archive of obsolete content
Archive › Mozilla › Persona › The navigator.id API
for more information, see this guide to migrating your site away from persona: https://wiki.mozilla.org/identity/persona_shutdown_guidelines_for_reliers for full details about the navigator.id api, refer to its reference pages.
... to ask for an assertion, the website uses a javascript api defined by the id object, which is a member of the global navigator object.
...after that, they can work as if id is just a built-in member of navigator.
...And 3 more matches
Adding APIs to the navigator object
Mozilla › Developer guide › Adding APIs to the navigator object
starting with gecko 9.0 (firefox 9.0 / thunderbird 9.0 / seamonkey 2.6), you can easily add new apis to the window.navigator object by using the category manager.
... simply add an entry to the "javascript-navigator-property" category.
...each method below of adding new objects to the navigator object requires that the new object is a registered xpcom component.
...And 3 more matches
Navigator.xr - Web APIs
Web › API › Navigator › xr
the read-only xr property provided by the navigator or workernavigator interface returns an xr object which can be used to access the webxr device api.
... syntax const xr = navigator.xr value the xr object used to interface with the webxr device api in the current context.
... usage notes each window has its own instance of navigator, which can be accessed as window.navigator or simply as navigator.
...And 3 more matches
NavigatorOnLine - Web APIs
Web › API › NavigatorOnLine
the navigatoronline interface contains methods and properties related to the connectivity status of the browser.
... there is no object of type navigatoronline, but other interfaces, like navigator or workernavigator, implement it.
... properties the navigatoronline interface doesn't inherit any property.
...And 3 more matches
NavigatorPlugins - Web APIs
Web › API › NavigatorPlugins
the navigatorplugins mixin adds to the navigator interface methods and properties for discovering and interacting with plugins installed into the browser.
... properties navigatorplugins.mimetypes read only returns an mimetypearray listing the mime types supported by the browser.
... navigatorplugins.plugins read only returns a pluginarray listing the plugins installed in the browser.
...And 3 more matches
WorkerGlobalScope.navigator - Web APIs
Web › API › WorkerGlobalScope › navigator
the navigator read-only property of the workerglobalscope interface returns the workernavigator associated with the worker.
... it is a specific navigator object, mostly a subset of the navigator for browsing scopes, but adapted to workers.
... syntax var navigatorobj = self.navigator; value a workernavigator object.
...And 3 more matches
Navigator.clipboard - Web APIs
Web › API › Navigator › clipboard
the clipboard api adds to the navigator interface the read-only clipboard property, which returns the clipboard object used to read and write the clipboard's contents.
... syntax theclipboard = navigator.clipboard; value the clipboard object used to access the system clipboard.
... examples the following code uses navigator.clipboard to access the system clipboard in order to read the contents of the clipboard.
...And 2 more matches
Navigator.cookieEnabled - Web APIs
Web › API › Navigator › cookieEnabled
navigator.cookieenabled returns a boolean value that indicates whether cookies are enabled or not.
... syntax var cookieenabled = navigator.cookieenabled; cookieenabled is a boolean: true or false.
... note: when the browser is configured to block third-party cookies, and navigator.cookieenabled is invoked inside a third-party iframe, it returns true in safari, edge spartan and ie (while trying to set a cookie in such scenario would fail).
...And 2 more matches
Navigator.share() - Web APIs
Web › API › Navigator › share
the navigator.share() method of the web share api invokes the native sharing mechanism of the device.
... syntax var sharepromise = navigator.share(data); parameters data an object containing data to share.
...the javascript looks like this: const sharedata = { title: 'mdn', text: 'learn web development on mdn!', url: 'https://developer.mozilla.org', } const btn = document.queryselector('button'); const resultpara = document.queryselector('.result'); // must be triggered some kind of "user activation" btn.addeventlistener('click', async () => { try { await navigator.share(sharedata) resultpara.textcontent = 'mdn shared successfully' } catch(err) { resultpara.textcontent = 'error: ' + err } }); sharing files to share files, first test for and call navigator.canshare().
...And 2 more matches
Navigator.canShare() - Web APIs
Web › API › Navigator › canShare
the navigator.canshare() method of the web share api returns true if a call to navigator.share() would succeed.
... syntax var canshare = navigator.canshare(data); parameters data optional an object containing data to share that matches what you would pass to navigator.share().
...true if data can be shared with navigator.share().
... examples if(navigator.canshare(data)) { // we can use share() to share the data!
Navigator.getUserMedia() - Web APIs
Web › API › Navigator › getUserMedia
the deprecated navigator.getusermedia() method prompts the user for permission to use up to one video input device (such as a camera or shared screen) and up to one audio input device (such as a microphone) as the source for a mediastream.
...please use the newer navigator.mediadevices.getusermedia() instead.
... syntax navigator.getusermedia(constraints, successcallback, errorcallback); parameters constraints a mediastreamconstraints object specifying the types of media to request, along with any requirements for each type.
... navigator.getusermedia = navigator.getusermedia || navigator.webkitgetusermedia || navigator.mozgetusermedia; if (navigator.getusermedia) { navigator.getusermedia({ audio: true, video: { width: 1280, height: 720 } }, function(stream) { var video = document.queryselector('video'); video.srcobject = stream; video.onloadedm...
Navigator.mediaDevices - Web APIs
Web › API › Navigator › mediaDevices
the navigator.mediadevices read-only property returns a mediadevices object, which provides access to connected media input devices like cameras and microphones, as well as screen sharing.
... syntax var mediadevices = navigator.mediadevices; return value the mediadevices singleton object.
... usually, you just use this object's members directly, such as by calling navigator.mediadevices.getusermedia().
... specifications specification status comment media capture and streamsthe definition of 'navigatorusermedia.mediadevices' in that specification.
Navigator.mediaSession - Web APIs
Web › API › Navigator › mediaSession
the read-only navigator property mediasession returns a mediasession object that can be used to share with the browser metadata and other information about the current playback state of media being handled by a document.
... syntax let mediasession = navigator.mediasession; value a mediasession object the current document can use to share information about media it's playing and its current playback status.
...note that the code begins by ensuring that the navigator.mediasession property is available before attempting to use it.
... if ("mediasession" in navigator){ navigator.mediasession.metadata = new mediametadata({ title: "podcast episode title", artist: "podcast host", album: "podcast name", artwork: [{src: "podcast.jpg"}] }); } specifications specification status comment media session standardthe definition of 'navigator.mediasession' in that specification.
Navigator.oscpu - Web APIs
Web › API › Navigator › oscpu
the navigator.oscpu property returns a string that identifies the current operating system.
... syntax oscpuinfo = navigator.oscpu value a domstring providing a string which identifies the operating system on which the browser is running.
... windows 32-bit windows nt x.y mac os x (ppc build) powerpc mac os x version x.y mac os x (i386/x64 build) intel mac os x or macos version x.y linux 64-bit (32-bit build) output of uname -s plus "i686 on x86_64" linux output of uname -sm x.y refers to the version of the operating system example function osinfo() { alert(window.navigator.oscpu); } osinfo(); // alerts "windows nt 6.0" for example usage notes unless your code is privileged (chrome or at least has the universalbrowserread privilege), it may get the value of the general.oscpu.override preference instead of the true platform.
... specifications specification status comment html living standardthe definition of 'navigatorid: oscpu' in that specification.
Navigator.productSub - Web APIs
Web › API › Navigator › productSub
the navigator.productsub read-only property returns the build number of the current browser.
... syntax prodsub = window.navigator.productsub prodsub is a string.
... example <script> function prodsub() { var dt = document.getelementbyid("d").childnodes[0]; dt.data = window.navigator.productsub; } </script> <button onclick="prodsub();">productsub</button> // returns: 20010725 notes on ie, this property returns undefined.
... specifications specification status comment html living standardthe definition of 'navigatorid: productsub' in that specification.
Navigator.serviceWorker - Web APIs
Web › API › Navigator › serviceWorker
the navigator.serviceworker read-only property returns the serviceworkercontainer object for the associated document, which provides access to registration, removal, upgrade, and communication with the serviceworker.
... syntax var workercontainerinstance = navigator.serviceworker; value serviceworkercontainer examples this code checks if the browser supports service workers.
... if ('serviceworker' in navigator) { // supported!
... } specifications specification status comment service workersthe definition of 'navigator.serviceworker' in that specification.
NavigatorConcurrentHardware - Web APIs
Web › API › NavigatorConcurrentHardware
the navigatorconcurrenthardware mixin adds to the navigator interface features which allow web content to determine how many logical processors the user has available, in order to let content and web apps optimize their operations to best take advantage of the user's cpu.
...the browser may, however, choose to reduce the number in order to represent more accurately the number of workers that can run at once properties navigatorconcurrenthardware.hardwareconcurrency read only returns the number of logical processors which may be available to the user agent.
... methods the navigatorconcurrenthardware mixin has no methods.
... specifications specification status comment html living standardthe definition of 'navigatorconcurrenthardware' in that specification.
NavigatorID.appVersion - Web APIs
Web › API › NavigatorID › appVersion
syntax window.navigator.appversion value either "4.0" or a string representing version information about the browser.
... example alert('your browser version is reported as ' + navigator.appversion); notes the window.navigator.useragent property may also contain the version number (for example "mozilla/5.0 (windows; u; win98; en-us; rv:0.9.2) gecko/20010725 netscape 6/6.1"), but you should be aware of how easy it is to change the user agent string and "spoof" other browsers, platforms, or user agents, and also how cavalier the browser vendor themselves are with these properties.
... the window.navigator.appversion, window.navigator.appname and window.navigator.useragent properties have been used in "browser sniffing" code: scripts that attempt to find out what kind of browser you are using and adjust pages accordingly.
... specifications specification status comment html living standardthe definition of 'navigatorid.appversion' in that specification.
NavigatorID.userAgent - Web APIs
Web › API › NavigatorID › userAgent
the navigatorid.useragent read-only property returns the user agent string for the current browser.
... syntax var ua = navigator.useragent; value a domstring specifying the complete user agent string the browser provides both in http headers and in response to this and other related methods on the navigator object.
...each of these pieces of info comes from other navigator properties which are also settable by the user.
... gecko-based browsers comply with the following general structure: useragent = appcodename/appversion number (platform; security; os-or-cpu; localization; rv: revision-version-number) product/productsub application-name application-name-version example alert(window.navigator.useragent) // alerts "mozilla/5.0 (windows; u; win98; en-us; rv:0.9.2) gecko/20010725 netscape6/6.1" specifications specification status comment html living standardthe definition of 'navigatorid.useragent' in that specification.
NavigatorLanguage.languages - Web APIs
Web › API › NavigatorLanguage › languages
the navigatorlanguage.languages read-only property returns an array of domstrings representing the user's preferred languages.
... the value of navigator.language is the first element of the returned array.
... the accept-language http header in every http request from the user's browser uses the same value for the navigator.languages property except for the extra qvalues (quality values) field (e.g.
... syntax preferredlanguages = globalobj.navigator.languages examples navigator.language //"en-us" navigator.languages //["en-us", "zh-cn", "ja-jp"] specifications specification status comment html living standardthe definition of 'navigatorlanguage: languages' in that specification.
Navigator.activeVRDisplays - Web APIs
Web › API › Navigator › activeVRDisplays
the activevrdisplays read-only property of the navigator interface returns an array containing every vrdisplay object that is currently presenting (vrdisplay.ispresenting is true).
... syntax var myactivedisplays = navigator.activevrdisplays; value an array of vrdisplay objects.
... examples function showactive() { var displays = navigator.activevrdisplays; for(var i = 0; i < displays.length; i++) { console.log('display ' + displays[i].displayid + ' is active.'); } } specifications specification status comment webvr 1.1the definition of 'activevrdisplays' in that specification.
Navigator.battery - Web APIs
Web › API › Navigator › battery
this interface was introduced in early drafts of the battery status api and but has been replaced with promise-based navigator.getbattery().
... the battery property has been removed in favor of the standard navigator.getbattery() method, which returns a battery promise.
... syntax var battery = navigator.battery; ...
Navigator.connection - Web APIs
Web › API › Navigator › connection
the navigator.connection read-only property returns a networkinformation object containing information about the system's connection, such as the current bandwidth of the user's device or whether the connection is metered.
... syntax networkinformation = navigator.connection value a networkinformation object.
... specifications specification status comment network information apithe definition of 'navigator.connection' in that specification.
Navigator.credentials - Web APIs
Web › API › Navigator › credentials
the credentials property of the navigator interface returns the credentialscontainer interface, which exposes methods to request credentials.
... syntax var credentialscontainer = navigator.credentials value the credentialscontainer interface.
... example if ('credentials' in navigator) { navigator.credentials.get({password: true}) .then(function(creds) { //do something with the credentials.
Navigator.deviceMemory - Web APIs
Web › API › Navigator › deviceMemory
the devicememory read-only property of the navigator interface returns the approximate amount of device memory in gigabytes.
... syntax memoryamount = navigator.devicememory value a floating point number; one of 0.25, 0.5, 1, 2, 4, 8.
... example const memory = navigator.devicememory console.log (`this device has at least ${memory}gib of ram.`) specifications specification status comment device memory 1the definition of 'devicememory' in that specification.
Navigator.getBattery() - Web APIs
Web › API › Navigator › getBattery
syntax var batterypromise = navigator.getbattery(); return value a promise which, when resolved, calls its fulfillment handler with a single parameter: a batterymanager object which you can use to get information about the battery's state.
... let batteryischarging = false; navigator.getbattery().then(function(battery) { batteryischarging = battery.charging; battery.addeventlistener('chargingchange', function() { batteryischarging = battery.charging; }); }); for more examples and details, see battery status api.
... specifications specification status comment battery status apithe definition of 'navigator.getbattery()' in that specification.
Navigator.getVRDisplays() - Web APIs
Web › API › Navigator › getVRDisplays
the getvrdisplays() method of the navigator interface returns a promise that resolves to an array of vrdisplay objects representing any available vr displays connected to the computer.
... syntax navigator.getvrdisplays().then(function(displays) { // do something with the available vr displays }); parameters none.
... examples if(navigator.getvrdisplays) { console.log('webvr 1.1 supported'); // then get the displays attached to the computer navigator.getvrdisplays().then(function(displays) { // if a display is available, use it to present the scene if(displays.length > 0) { vrdisplay = displays[0]; // now we have our vrdisplay object and can do what we want with it } }); } note: you can see this complete code at raw-webgl-example.
Navigator.mediaCapabilities - Web APIs
Web › API › Navigator › mediaCapabilities
the navigator.mediacapabilities read-only property returns a mediacapabilities object that can expose information about the decoding and encoding capabilities for a given format and output capabilities as defined by the media capabilities api.
... syntax mediacapabilitiesobj = globalobj.navigator.mediacapabilities value a mediacapabilities object.
... examples navigator.mediacapabilities.decodinginfo({ type : 'file', audio : { contenttype : "audio/mp3", channels : 2, bitrate : 132700, samplerate : 5200 } }).then(function(result) { console.log('this configuration is ' + (result.supported ?
Navigator.mozIsLocallyAvailable() - Web APIs
Web › API › Navigator › mozIsLocallyAvailable
the navigator.mozislocallyavailable() method allows add-ons to determine whether or not a given resource is available.
... syntax navigator.mozislocallyavailable(uri, ifoffline); parameters uri the uri of the resource whose availability is to be checked, as a string.
... example var available = navigator.mozislocallyavailable("my-image-file.png", true); if (available) { /* the offline resource is present */ } else { console.log("certain needed resources are not available offline"); } specifications not part of any specifications.
Navigator.permissions - Web APIs
Web › API › Navigator › permissions
the navigator.permissions read-only property returns a permissions object that can be used to query and update permission status of apis covered by the permissions api.
... syntax permissionsobj = globalobj.navigator.permissions value a permissions object.
... examples navigator.permissions.query({name:'geolocation'}).then(function(result) { if (result.state === 'granted') { showmap(); } else if (result.state === 'prompt') { showbuttontoenablemap(); } // don't do anything if the permission was denied.
Navigator.presentation - Web APIs
Web › API › Navigator › presentation
the presentation property of navigator serves as the entry point for the presentation api and returns a reference to presentation object.
... syntax const presentation = navigator.presentation value a reference to presentation object.
... specifications specification status comment presentation apithe definition of 'navigator.presentation' in that specification.
Navigator.registerProtocolHandler() - Web APIs
Web › API › Navigator › registerProtocolHandler
the navigator method registerprotocolhandler() lets web sites register their ability to open or handle particular url schemes (aka protocols).
... syntax navigator.registerprotocolhandler(scheme, url, title); note: recently updated to navigator.registerprotocolhandler(scheme, url), but no browsers currently support this version.
... otherwise, the scheme must be one of the following: bitcoin geo im irc ircs magnet mailto mms news nntp openpgp4fpr sip sms smsto ssh tel urn webcal wtai xmpp example if your site is burgers.example.com, you can register a protocol handler for it to handle web+burger: links, like so: navigator.registerprotocolhandler("web+burger", "https://burgers.example.com/?burger=%s", "burger handler"); this creates a handler that lets web+burger: links send the user to your site, inserting the accessed burger url into the %s placeholder.
Navigator.sendBeacon() - Web APIs
Web › API › Navigator › sendBeacon
the navigator.sendbeacon() method asynchronously sends a small amount of data over http to a web server.
... syntax navigator.sendbeacon(url, data); parameters url the url that will receive the data.
... window.addeventlistener("unload", function logdata() { navigator.sendbeacon("/log", analyticsdata); }); the beacon sends an http request via the post method, with all relevant cookies available when called.
Navigator.vendor - Web APIs
Web › API › Navigator › vendor
the value of the navigator vendor property is always either "google inc.", "apple computer, inc.", or (in firefox) the empty string.
... syntax venstring = window.navigator.vendor value either "google inc.", "apple computer, inc.", or (in firefox) the empty string.
... specifications specification status comment html living standardthe definition of 'navigatorid: vendor' in that specification.
Navigator.vibrate() - Web APIs
Web › API › Navigator › vibrate
the navigator.vibrate() method pulses the vibration hardware on the device, if such hardware exists.
... syntax var successbool = window.navigator.vibrate(pattern); pattern provides a pattern of vibration and pause intervals.
... examples window.navigator.vibrate(200); // vibrate for 200ms window.navigator.vibrate([100,30,100,30,100,30,200,30,200,30,200,30,100,30,100,30,100]); // vibrate 'sos' in morse.
Navigator.webdriver - Web APIs
Web › API › Navigator › webdriver
the webdriver read-only property of the navigator interface indicates whether the user agent is controlled by automation.
... the navigator.webdriver property is true when in: chrome the --enable-automation or the --headless flag or the --remote-debugging-port is used.
... syntax var isautomated = navigator.webdriver value a boolean specifications specification status comment webdriverthe definition of 'webdriver' in that specification.
navigator.hardwareConcurrency - Web APIs
Web › API › NavigatorConcurrentHardware › hardwareConcurrency
the navigator.hardwareconcurrency read-only property returns the number of logical processors available to run threads on the user's computer.
... syntax logicalprocessors = window.navigator.hardwareconcurrency value a number indicating the number of logical processor cores.
... let workerlist = []; for (let i = 0; i < window.navigator.hardwareconcurrency; i++) { let newworker = { worker: new worker('cpuworker.js'), inuse: false }; workerlist.push(newworker); } specification specification status comment html living standardthe definition of 'navigator.hardwareconcurrency' in that specification.
NavigatorID.appCodeName - Web APIs
Web › API › NavigatorID › appCodeName
the value of the navigatorid.appcodename property is always "mozilla", in any browser.
... syntax codename = navigator.appcodename value the string "mozilla".
... specifications specification status comment html living standardthe definition of 'navigatorid.appcodename' in that specification.
NavigatorID.appName - Web APIs
Web › API › NavigatorID › appName
the value of the navigatorid.appname property is always "netscape", in any browser.
... syntax appname = navigator.appname value the string "netscape".
... specifications specification status comment html living standardthe definition of 'navigatorid.appname' in that specification.
NavigatorID.platform - Web APIs
Web › API › NavigatorID › platform
syntax platform = navigator.platform value a domstring identifying the platform on which the browser is running, or an empty string if the browser declines to (or is unable to) identify the platform.
... for example: "macintel", "win32", "freebsd i386", "webtv os" example console.log(navigator.platform); usage notes most browsers, including chrome, edge, and firefox 63 and later, return "win32" even if running on a 64-bit version of windows.
... specifications specification status comment html living standardthe definition of 'navigatorid.platform' in that specification.
NavigatorID.product - Web APIs
Web › API › NavigatorID › product
the value of the navigatorid.product property is always "gecko", in any browser.
... syntax productname = navigator.product value the string "gecko".
... specifications specification status comment html living standardthe definition of 'navigatorid.product' in that specification.
NavigatorLanguage.language - Web APIs
Web › API › NavigatorLanguage › language
the navigatorlanguage.language read-only property returns a string representing the preferred language of the user, usually the language of the browser ui.
... syntax const lang = navigator.language value a domstring.
... example if (/^en\b/.test(navigator.language)) { dolangselect(window.navigator.language); } specifications specification status comment html living standardthe definition of 'navigatorlanguage: language' in that specification.
Navigator.onLine - Web APIs
Web › API › NavigatorOnLine › onLine
syntax online = window.navigator.online; value online is a boolean true or false.
... to check if you are online, query window.navigator.online, as in the following example: if (navigator.online) { console.log('online'); } else { console.log('offline'); } if the browser doesn't support navigator.online the above example will always come out as false/undefined.
... the network state, use addeventlistener to listen for the events on window.online and window.offline, as in the following example: window.addeventlistener('offline', function(e) { console.log('offline'); }); window.addeventlistener('online', function(e) { console.log('online'); }); specifications specification status comment html living standardthe definition of 'navigator.online' in that specification.
NavigatorStorage.storage - Web APIs
Web › API › NavigatorStorage › storage
the navigatorstorage.storage read-only property returns the singleton storagemanager object used to access the overall storage capabilities of the browser for the current site or app.
... syntax var storagemanager = navigator.storage; value a storagemanager object you can use to maintain persistence for stored data, as well as to determine roughly how much room there is for data to be stored.
... specifications specification status comment storagethe definition of 'navigator.storage' in that specification.
Window.navigator - Web APIs
Web › API › Window › navigator
the window.navigator read-only property returns a reference to the navigator object, which has methods and properties about the application running the script.
... syntax navigatorobject = window.navigator examples example #1: browser detect and return a string var sbrowser, susrag = navigator.useragent; // the order matters here, and this may report false positives for unlisted browsers.
...dexof("safari") > -1) { sbrowser = "apple safari"; // "mozilla/5.0 (iphone; cpu iphone os 11_4 like mac os x) applewebkit/605.1.15 (khtml, like gecko) version/11.0 mobile/15e148 safari/604.1 980x1306" } else { sbrowser = "unknown"; } alert("you are using: " + sbrowser); specifications specification status comment html living standardthe definition of 'window: navigator' in that specification.
Navigator - Archive of obsolete content
Archive › API › Navigator
features that used to hang off the navigator interface, but have since been removed.
... navigator.moznotificationprovides support for creating notification objects, which are used to display desktop notification alerts to the user.
Navigator.id - Archive of obsolete content
Archive › Navigator-id
summary the browserid protocol defines a new id property on the window.navigator object, through which it exposes the browserid api, that is the identitymanager intreface.
... syntax var id = navigator.id ...
Netscape Navigator - MDN Web Docs Glossary: Definitions of Web-related terms
Glossary › Netscape Navigator
netscape navigator or netscape was a leading browser in the 1990s.
... learn more general knowledge netscape navigator on wikipedia ...
nsIDOMNavigatorDesktopNotification
Mozilla › Tech › XPCOM › Reference › Interface › nsIDOMNavigatorDesktopNotification
dom/interfaces/notification/nsidomnavigatordesktopnotification.idlscriptable property that extends the navigator object.
... 1.0 66 introduced gecko 2.0 inherits from: nsisupports last changed in gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) property that extends the navigator object.
Navigator.buildID - Web APIs
Web › API › Navigator › buildID
syntax buildid = navigator.buildid; value a string representing the build identifier of the application.
... example console.log(window.navigator.buildid); specification not part of any public standard.
Navigator.doNotTrack - Web APIs
Web › API › Navigator › doNotTrack
the navigator.donottrack property returns the user's do not track setting, which indicates whether the user is requesting web sites and advertisers to not track them.
... example console.log(navigator.donottrack); // prints "1" if dnt is enabled; "0" if the user opted-in for tracking; otherwise this is "unspecified" specifications specification status comment tracking preference expression (dnt)the definition of 'navigator.donottrack' in that specification.
Navigator.geolocation - Web APIs
Web › API › Navigator › geolocation
the navigator.geolocation read-only property returns a geolocation object that gives web content access to the location of the device.
... syntax geo = navigator.geolocation specifications specification status comment geolocation apithe definition of 'navigator.geolocation' in that specification.
Navigator.getGamepads() - Web APIs
Web › API › Navigator › getGamepads
the navigator.getgamepads() method returns an array of gamepad objects, one for each gamepad connected to the device.
... syntax var gamepads = navigator.getgamepads(); example window.addeventlistener("gamepadconnected", function(e) { var gp = navigator.getgamepads()[e.gamepad.index]; console.log( "gamepad connected at index %d: %s.
Navigator.keyboard - Web APIs
Web › API › Navigator › keyboard
the keyboard read-only property of the navigator interface returns a keyboard object which provides access to functions that retrieve keyboard layout maps and toggle capturing of key presses from the physical keyboard.
... syntax var keyboard = navigator.keyboard value a keyboard object.
Navigator.locks - Web APIs
Web › API › Navigator › locks
the locks read-only property of the navigator interface returns a lockmanager object which provides methods for requesting a new lock object and querying for an existing lock object.
... syntax var lockmanager = navigator.locks value a lockmanager object.
Navigator.maxTouchPoints - Web APIs
Web › API › Navigator › maxTouchPoints
the maxtouchpoints read-only property of the navigator interface returns the maximum number of simultaneous touch contact points are supported by the current device.
... syntax touchpoints = navigator.maxtouchpoints; example if (navigator.maxtouchpoints > 1) { // browser supports multi-touch } specifications specification status comment pointer events – level 2the definition of 'maxtouchpoints' in that specification.
Navigator.msLaunchUri() - Web APIs
Web › API › Navigator › msLaunchUri
the mslaunchuri() method is a microsoft extension to the navigator interface, which starts a service or app, such as an email client, that handles a given protocol.
... syntax navigator.mslaunchuri(uri, successcallback, nohandlercallback); parameters uri a domstring specifying the url containing including the protocol of the document or resource to be displayed.
Navigator.registerContentHandler() - Web APIs
Web › API › Navigator › registerContentHandler
syntax navigator.registercontenthandler(mimetype, uri, title); mimetype is the desired mime type as a string.
... example navigator.registercontenthandler( "application/vnd.mozilla.maybe.feed", "http://www.example.tld/?foo=%s", "my feed reader" ); notes for firefox 2 and above, only the application/vnd.mozilla.maybe.feed, application/atom+xml, and application/rss+xml mime types are supported.
Navigator.requestMediaKeySystemAccess() - Web APIs
Web › API › Navigator › requestMediaKeySystemAccess
the navigator.requestmediakeysystemaccess() method returns a promise which delivers a mediakeysystemaccess object that can be used to access a particular media key system, which can in turn be used to create keys for decrypting a media stream.
... syntax ​promise = navigator.requestmediakeysystemaccess(keysystem, supportedconfigurations); parameters keysystem a domstring identifying the key system.
Navigator.vendorSub - Web APIs
Web › API › Navigator › vendorSub
the value of the navigator.vendorsub property is always the empty string, in any browser.
... syntax vensub = window.navigator.vendorsub value the empty string specifications specification status comment html living standardthe definition of 'navigatorid: vendorsub' in that specification.
NavigatorID.taintEnabled() - Web APIs
Web › API › NavigatorID › taintEnabled
the navigatorid.taintenabled() method always returns false.
... syntax result = window.navigator.taintenabled() specifications specification status comment html living standardthe definition of 'navigatorid.taintenabled' in that specification.
NavigatorPlugins.javaEnabled() - Web APIs
Web › API › NavigatorPlugins › javaEnabled
syntax result = window.navigator.javaenabled() example if (window.navigator.javaenabled()) { // browser has java } notes the return value for this method indicates whether the preference that controls java is on or off - not whether the browser offers java support in general.
... specifications specification status comment html living standardthe definition of 'navigatorplugins.javaenabled' in that specification.
NavigatorPlugins.mimeTypes - Web APIs
Web › API › NavigatorPlugins › mimeTypes
syntax var mimetypes[] = navigator.mimetypes; mimetypes is a mimetypearray object which has a length property as well as item(index) and nameditem(name) methods.
... example function isjavapresent() { return 'application/x-java-applet' in navigator.mimetypes; } function getjavaplugindescription() { var mimetype = navigator.mimetypes['application/x-java-applet']; if (mimetype === undefined) { // no java plugin present return undefined; } return mimetype.enabledplugin.description; } specifications specification status comment html living standardthe definition of 'navigatorplugins.mimetypes' in that specification.
NavigatorStorage - Web APIs
Web › API › NavigatorStorage
the navigatorstorage mixin adds to the navigator and workernavigator interfaces the navigator.storage property, which provides access to the storagemanager singleton used for controlling the persistence of data stores as well as obtaining information note: this feature is available in web workers.
... methods the navigatorstorage mixin has no methods.
WorkerNavigator.connection - Web APIs
Web › API › WorkerNavigator › connection
the workernavigator.connection read-only property returns a networkinformation object containing information about the system's connection, such as the current bandwidth of the user's device or whether the connection is metered.
... syntax connectioninfo = self.navigator.connection specifications specification status comment network information apithe definition of 'navigator.connection' in that specification.
WorkerNavigator.locks - Web APIs
Web › API › WorkerNavigator › locks
the locks read-only property of the workernavigator interface returns a lockmanager object which provides methods for requesting a new lock object and querying for an existing lock object.
... syntax var lockmanager = navigator.locks value a lockmanager object.
WorkerNavigator.permissions - Web APIs
Web › API › WorkerNavigator › permissions
the workernavigator.permissions read-only property returns a permissions object that can be used to query and update permission status of apis covered by the permissions api.
... examples self.navigator.permissions.query({name:'notifications'}).then(function(result) { if (result.state === 'granted') { shownotification(); } else if (result.state === 'prompt') { requestnotificationpermission() } }); specification specification status comment permissions working draft initial definition.
Navigator.wakeLock - Web APIs
Web › API › Navigator › wakeLock
syntax const wakelock = navigator.wakelock; specifications specification status comment screen wake lock api editor's draft initial definition ...
Index - Web APIs
Web › API › Index
this stream can be used in a similar way as a mediastream obtained via navigator.getusermedia — it can, for example, be sent to a remote peer using the rtcpeerconnection addstream() method.
...the message is received in the "message" event on navigator.serviceworker.
...this triggers a "controllerchange" event on navigator.serviceworker in any clients that become controlled by this service worker.
...And 90 more matches
Browser Detection and Cross Browser Support - Archive of obsolete content
Archive › Web › Browser Detection and Cross Browser Support
quick tip if you must determine if a visitor is using a gecko-based browser, simply test navigator.product == 'gecko' or look for the string 'gecko/' in the navigator.useragent.
...it also includes compatibility features which allow it to reasonably handle legacy content which was developed for earlier generations of browsers such as netscape navigator 4 as well as features which provide compatibility with internet explorer 5 and 6.
... netscape navigator 2 introduced the ability to run javascript in web browsers.
...And 50 more matches
Index - Archive of obsolete content
Archive › Index
5 navigator api, navigator features that used to hang off the navigator interface, but have since been removed.
... 6 navigator.moznotification api, deprecated, mobile, non-standard, property, reference provides support for creating notification objects, which are used to display desktop notification alerts to the user.
...to implement this ui, we'll add a statusbarpanel element to the statusbar element in the navigator.xul file.
...And 18 more matches
Using the Gamepad API - Web APIs
Web › API › Gamepad API › Using the Gamepad API
in addition to these events, the api also adds a gamepad object, which you can use to query the state of a connected gamepad, and a navigator.getgamepads() method which you can use to get a list of gamepads known to the page.
...the index property also functions as the index into the array returned by navigator.getgamepads().
... var gamepads = {}; function gamepadhandler(event, connecting) { var gamepad = event.gamepad; // note: // gamepad === navigator.getgamepads()[gamepad.index] if (connecting) { gamepads[gamepad.index] = gamepad; } else { delete gamepads[gamepad.index]; } } window.addeventlistener("gamepadconnected", function(e) { gamepadhandler(e, true); }, false); window.addeventlistener("gamepaddisconnected", function(e) { gamepadhandler(e, false); }, false); this previous example also demonstrates how the gamepad property can be held after the event has completed — a technique we will use for device state querying later.
...And 14 more matches
Extending a Protocol
Mozilla › IPDL › Extending a Protocol
to make this tutorial less abstract (more fun!), we are going to implement a js method called echo() on the navigator interface.
... the webidl for this will be: partial interface navigator { promise<domstring> echo(domstring somestring); }; learning goals are: extending an existing ipdl protocol.
... implementing the navigator.echo() in your favorite editor, open dom/webidl/navigator.webidl at the end of the file, add: partial interface navigator { [throws] promise<domstring> echo(domstring astring); }; now we need to implement the echo() method in c++, so open up ./dom/base/navigator.h and let's add the method definition, so under public:: already_addrefed<promise> echo(const nsastring& astring, errorresult& arv); we use nsastring& as the domstr...
...And 12 more matches
Implementing a Persona IdP - Archive of obsolete content
Archive › Mozilla › Persona › Implementing a Persona IdP
on the page, you should: include the provisioning api library from the correct server (always login.persona.org, unless you're testing with a pre-release version of persona): <script src="https://login.persona.org/provisioning_api.js"></script> invoke navigator.id.beginprovisioning().
... it takes a callback with two arguments, the user's email address (a string) and a desired certificate duration (a number, in seconds): navigator.id.beginprovisioning(function(email, certduration) { //...
... if the user does not have an active session associated with the given email address, call navigator.id.raiseprovisioningfailure() with an optional, but recommended, error message at its first parameter.
...And 10 more matches
Quick Setup - Archive of obsolete content
Archive › Mozilla › Persona › Quick Setup
once this library is loaded in your page, the persona functions you need (watch(), request(), and logout()) will be available in the global navigator.id object.
... to include the persona javascript library, place this script tag at the bottom of the page body: <script src="https://login.persona.org/include.js"></script> you must include this on every page which uses navigator.id functions.
...to open the persona dialog and prompt the user to log in, you should invoke navigator.id.request().
...And 10 more matches
Gecko Compatibility Handbook - Archive of obsolete content
Archive › Mozilla Gecko Compatibility Handbook
gecko since 1997, much of the web's content has been developed for microsoft internet explorer 4 or netscape navigator 4.
... internet explorer 4 and netscape navigator 4 share support for a large part of the html 3.2 standard and basic javascript.
... neither internet explorer 4 or netscape navigator 4 support the w3 dom.
...And 10 more matches
Writing Skinnable XUL and CSS - Archive of obsolete content
Archive › Mozilla › XUL › Writing skinnable XUL and CSS
mozilla can have any number of installed ui packages, from navigator to sidebar to editor.
...for example, the skin for the navigator package should contain a file called navigator.css that determines the default look of all xul windows posed from this package.
...for example, the sidebar should not import the global skin, since it could appear in messenger and in navigator (which could have two completely different color schemes).
...And 8 more matches
MediaDevices.getUserMedia() - Web APIs
Web › API › MediaDevices › getUserMedia
generally, you will access the mediadevices singleton object using navigator.mediadevices, like this: async function getmedia(constraints) { let stream = null; try { stream = await navigator.mediadevices.getusermedia(constraints); /* use the stream */ } catch(err) { /* handle the error */ } } similarly, using the raw promises directly, the code looks like this: navigator.mediadevices.getusermedia(constraints) .then(function(stream) { /* use the ...
...stream */ }) .catch(function(err) { /* handle the error */ }); note: if the current document isn't loaded securely, navigator.mediadevices will be undefined, and you cannot use getusermedia().
... syntax var promise = navigator.mediadevices.getusermedia(constraints); parameters constraints a mediastreamconstraints object specifying the types of media to request, along with any requirements for each type.
...And 8 more matches
In-Depth - Archive of obsolete content
Archive › Mozilla › Creating a skin for Mozilla › In-Depth
it says that the file is located in chrome://navigator/skin/.
... this is a small problem with the display in mozilla 1.2 what it means is \navigator\navigator.css (most of the time it displays the file correctly, but sometimes, like in this case, it does not).
... go into \myskin\navigator and load navigator.css.
...And 6 more matches
Media Session API - Web APIs
Web › API › Media Session API
rather than creating your own mediasession instance, you access the api using the navigator.mediasession property.
... for example, to set the current state of the media session to playing: navigator.mediasession.playbackstate = "playing"; interfaces mediametadata allows a web page to provide rich media metadata, for display in a platform ui.
...it then instantiates a metadata object for the session, and adds event handlers for the user control actions: if ('mediasession' in navigator) { navigator.mediasession.metadata = new mediametadata({ title: 'unforgettable', artist: 'nat king cole', album: 'the ultimate collection (remastered)', artwork: [ { src: 'https://dummyimage.com/96x96', sizes: '96x96', type: 'image/png' }, { src: 'https://dummyimage.com/128x128', sizes: '128x128', type: 'image/png' }, { src: 'https://dummyimage.com/192x192'...
...And 6 more matches
Making it into a static overlay - Archive of obsolete content
Archive › Mozilla › Creating a Mozilla extension › Making it into a static overlay
to make the file into a static overlay, we need to move all the code we added to navigator.xul into a new file tinderstatusoverlay.xul in the same directory: <?xml version="1.0"?> <?xml-stylesheet href="chrome://navigator/content/tinderstatus.css" type="text/css"?> <overlay id="tinderstatusoverlay" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> <script type="application/javascript" src="chrome://navigator/content/tinderstatus.js" /> ...
...its next line is the stylesheet reference we previously added to navigator.xul.
...within that element is the script reference we previously added to navigator.xul.
...And 5 more matches
A XUL Bestiary - Archive of obsolete content
Archive › Mozilla › XUL › A XUL Bestiary
the navigator is a package defined in mozilla/bin/chrome/navigator, the mail/news component is a package in mozilla/bin/chrome/mailnews/, and so on.
... each package directory typically has three subdirectories, content, skin, and locale, in which the xul, css, and localization information are defined, respectively: navigator/ content/ default/ navigator.xul ...
... skin/ default/ navigator.css nav-icon.gif ...
...And 5 more matches
New in JavaScript 1.2 - Archive of obsolete content
Archive › Web › JavaScript › New in JavaScript › 1.2
the following is a changelog for javascript from netscape navigator 3.0 to 4.0.
...netscape navigator 4.0 was released on june 11, 1997.
... netscape navigator 4.0 was the third major version of the browser with javascript support.
...And 4 more matches
Using the Geolocation API - Web APIs
Web › API › Geolocation API › Using the Geolocation API
the geolocation object the geolocation api is available through the navigator.geolocation object.
...you can test for the presence of geolocation thusly: if('geolocation' in navigator) { /* geolocation is available */ } else { /* geolocation is not available */ } getting the current position to obtain the user's current location, you can call the getcurrentposition() method.
... navigator.geolocation.getcurrentposition((position) => { dosomething(position.coords.latitude, position.coords.longitude); }); the above example will cause the dosomething() function to execute when the location is obtained.
...And 4 more matches
Capabilities, constraints, and settings - Web APIs
Web › API › Media Streams API › Constraints
determining if a constraint is supported if you need to know whether or not a given constriant is supported by the user agent, you can find out by calling navigator.mediadevices.getsupportedconstraints() to get a list of the constrainable properties which the browser knows, like this: let supported = navigator.mediadevices.getsupportedconstraints(); document.getelementbyid("framerateslider").disabled = !supported["framerate"]; in this example, the supported constraints are fetched, and a control that lets the user configure the frame rate is disabled if t...
... let supports = navigator.mediadevices.getsupportedconstraints(); if (!supports["width"] || !supports["height"] || !supports["framerate"] || !supports["facingmode"]) { // we're missing needed properties, so handle that error.
... applying constraints the first and most common way to use constraints is to specify them when you call getusermedia(): navigator.mediadevices.getusermedia({ video: { width: { min: 640, ideal: 1920 }, height: { min: 400, ideal: 1080 }, aspectratio: { ideal: 1.7777777778 } }, audio: { samplesize: 16, channelcount: 2 } }).then(stream => { videoelement.srcobject = stream; }).catch(handleerror); in this example, constraints are applied at getusermedia() time, asking for an ideal set of options wi...
...And 4 more matches
Finding window handles - Archive of obsolete content
Archive › Add-ons › Code snippets › Finding Window Handles
os specific examples using javascript (js-ctypes) nsibasewindow -> nativehandle in all of the examples below, the native handle to the most recent navigator:browser is obtained and then it is focused.
...andle returns the following in the different operating systems: windows - hwnd mac os x - nswindow* linux - gdkwindow* (it will be gdkwindow* no matter what desktop/window manager) is in use, for explanation why see the article: standard os libraries - unix section) windows components.utils.import('resource://gre/modules/services.jsm'); var browserwindow = services.wm.getmostrecentwindow('navigator:browser'); if (!browserwindow) { throw new error('no browser window found'); } var basewindow = browserwindow.queryinterface(ci.nsiinterfacerequestor) .getinterface(ci.nsiwebnavigation) .queryinterface(ci.nsidocshelltreeitem) .treeowner .queryinterface(ci.nsiinterfacereques...
...pes.voidptr_t // hwnd ); var hwnd = ctypes.voidptr_t(ctypes.uint64(hwndstring)); var rez_setforegroundwindow = setforegroundwindow(hwnd); console.log('rez_setforegroundwindow:', rez_setforegroundwindow, rez_setforegroundwindow.tostring()); user32.close(); mac os x objective-c components.utils.import('resource://gre/modules/services.jsm'); var browserwindow = services.wm.getmostrecentwindow('navigator:browser'); if (!browserwindow) { throw new error('no browser window found'); } var basewindow = browserwindow.queryinterface(ci.nsiinterfacerequestor) .getinterface(ci.nsiwebnavigation) .queryinterface(ci.nsidocshelltreeitem) .treeowner .queryinterface(ci.nsiinterfacereques...
...And 3 more matches
Tabbed browser - Archive of obsolete content
Archive › Add-ons › Tabbed browser
your code is running in a dialog opened directly by a browser window, you can use: window.opener.gbrowser.addtab(...); if window.opener doesn't work, you can get the most recent browser window using this code: var wm = components.classes["@mozilla.org/appshell/window-mediator;1"] .getservice(components.interfaces.nsiwindowmediator); var mainwindow = wm.getmostrecentwindow("navigator:browser"); mainwindow.gbrowser.addtab(...); opening a url in a new tab // add tab gbrowser.addtab("http://www.google.com/"); // add tab, then make active gbrowser.selectedtab = gbrowser.addtab("http://www.google.com/"); manipulating content of a new tab if you want to work on the content of the newly opened tab, you'll need to wait until the content has finished loading.
... function openandreuseonetabperurl(url) { var wm = components.classes["@mozilla.org/appshell/window-mediator;1"] .getservice(components.interfaces.nsiwindowmediator); var browserenumerator = wm.getenumerator("navigator:browser"); // check each browser instance for our url var found = false; while (!found && browserenumerator.hasmoreelements()) { var browserwin = browserenumerator.getnext(); var tabbrowser = browserwin.gbrowser; // check each tab of this browser instance var numtabs = tabbrowser.browsers.length; for (var index = 0; index < numtabs; index++) { var currentbrowser ...
... if (!found) { var recentwindow = wm.getmostrecentwindow("navigator:browser"); if (recentwindow) { // use an existing browser window recentwindow.delayedopentab(url, null, null, null, null); } else { // no browser windows are open, so open a new one.
...And 3 more matches
IdentityManager.request() - Archive of obsolete content
Archive › IdentityManager › request
when invoked, navigator.id.request() will ask the user to choose an email address to sign in with, and may ask the user to authenticate with their identity provider if the user's certificate has expired.
... it will then generate a signed assertion containing the user's email address and pass that assertion to the onlogin callback registered with navigator.id.watch().
... this function must be used in conjunction with navigator.id.watch().
...And 3 more matches
Call logout() after a failed login - Archive of obsolete content
Archive › Mozilla › Persona › The implementor s guide › Call logout() after a failed login
for more information, see this guide to migrating your site away from persona: https://wiki.mozilla.org/identity/persona_shutdown_guidelines_for_reliers after your onlogin handler gets called with an assertion, if for any reason you can't use the assertion to log the user in, you must call navigator.id.logout().
... if you don't, then the next time you call navigator.id.watch() persona will immediately call your onlogin handler again, with the same assertion.
... typically this will lead to an endless loop of failed login attempts: the user clicks "sign in" the user interacts with the persona interface, and persona generates an assertion persona delivers the assertion to the page's onlogin handler the onlogin handler rejects the assertion, and redirects the user to the login page the login page loads, calls navigator.id.watch(), and we go back to (3) the reason is that persona tries to remember which email you want to use to log into a particular site.
...And 3 more matches
New in JavaScript 1.1 - Archive of obsolete content
Archive › Web › JavaScript › New in JavaScript › 1.1
the following is a changelog for javascript from netscape navigator 2.0 to 3.0.
...netscape navigator 3.0 was released on august 19, 1996.
... netscape navigator 3.0 was the second major version of the browser with javascript support.
...And 3 more matches
New in JavaScript 1.3 - Archive of obsolete content
Archive › Web › JavaScript › New in JavaScript › 1.3
the following is a changelog for javascript from netscape navigator 4.0 to 4.5.
...netscape navigator 4.5 was released on october 19, 1998.
... javascript versions netscape communicator and navigator 4.06 and 4.5 executes javascript language versions up to 1.3.
...And 3 more matches
Using the Media Capabilities API - Web APIs
Web › API › Media Capabilities API › Using the Media Capabilities API
the mediacapabilities interface the mediacapabilities is available using the mediacapabilities property which is provided by both the navigator object and the workernavigator object; in other words, the media capabilities api is available both on the main thread and from workers.
...you can, therefore, test for the presence of the api like so: if ("mediacapabilities" in navigator) { // mediacapabilities is available } else { // mediacapabilities is not available } taking video as an example, to obtain information about video decoding abilities, you create a video decoding configuration which you pass as a parameter to mediacapabilities.decodinginfo() method.
... var promise = navigator.mediacapabilities.decodinginfo(videoconfiguration); the decodinginfo() and encodinginfo() methods both return promises.
...And 3 more matches
Using VR controllers with WebVR - Web APIs
Web › API › WebVR API › Using VR controllers with WebVR
getting the display information the first notable code is as follows: var initialrun = true; if(navigator.getvrdisplays && navigator.getgamepads) { info.textcontent = 'webvr api and gamepad api supported.' reportdisplays(); } else { info.textcontent = 'webvr api and/or gamepad api not supported by this browser.' } here we first use a tracking variable, initialrun, to note that this is the first time we have loaded the page.
...next, we detect to see if the webvr and gamepad apis are supported by cheking for the existence of the navigator.getvrdisplays() and navigator.getgamepads() methods.
...this function looks like so: function reportdisplays() { navigator.getvrdisplays().then(function(displays) { console.log(displays.length + ' displays'); for(var i = 0; i < displays.length; i++) { var cap = displays[i].capabilities; // cap is a vrdisplaycapabilities object var listitem = document.createelement('li'); listitem.innerhtml = '<strong>display ' + (i+1) + '</strong>' + '<br>vr display id: ' + displays[i].displayid + '<br>vr display name: ' + displays[i].displayname + '<br>display can present content: ' + cap.canpresent + '<br>display is separate from the computer\'s main display: ' + cap.hasexternaldi...
...And 3 more matches
Starting up and shutting down a WebXR session - Web APIs
Web › API › WebXR Device API › Startup and shutdown
there is a global xrsystem object available for use by your document through the the navigator property xr, which returns the xrsystem object if suitable xr hardware is available for your use given the hardware available and your document's environment.
... thus the simplest code that fetches the xrsystem object is: const xr = navigator.xr; the value of xr will be null or undefined if webxr isn't available.
...the navigator.xr property doesn't even exist if the document wasn't loaded securely.
...And 3 more matches
Web Locks API - Web APIs
Web › API › Web Locks API
navigator.locks.request('my_resource', async lock => { // the lock has been acquired.
... the main entry point is navigator.locks.request() which requests a lock.
...await navigator.locks.request('my_resource', async lock => { // the lock has been acquired.
...And 3 more matches
WorkerGlobalScope - Web APIs
Web › API › WorkerGlobalScope
workers have no browsing context; this scope contains the information usually conveyed by window objects — in this case event handlers, the console or the associated workernavigator object.
... standard properties workerglobalscope.navigator read only returns the workernavigator associated with the worker.
... it is a specific navigator object, mostly a subset of the navigator for browsing scopes, but adapted to workers.
...And 3 more matches
Browser detection using the user agent - HTTP
Web › HTTP › Browser detection using the user agent
so, you might have thought to do this: // this code snippet splits a string in a special notation if (navigator.useragent.indexof("chrome") !== -1){ // yes!
...use navigator.maxtouchpoints to detect if the user's device has a touchscreen.
... then, default back to checking the user agent screen only if (!("maxtouchpoints" in navigator)) { /*code here*/}.
...And 3 more matches
Feature-Policy - HTTP
Web › HTTP › Headers › Feature-Policy
when this policy is disabled, the promise returned by navigator.getbattery() will reject with a notallowederror domexception.
...when this policy is disabled, the promise returned by navigator.requestmediakeysystemaccess() will reject with a domexception.
...when this policy is disabled, the promise returned by navigator.requestmidiaccess() will reject with a domexception.
...And 3 more matches
HTTP Index - HTTP
Web › HTTP › Index
126 feature-policy: battery the http feature-policy header battery directive controls whether the current document is allowed to gather information about the acceleration of the device through the batterymanager interface obtained via navigator.getbattery().
...when this policy is enabled, the promise returned by navigator.requestmediakeysystemaccess() will reject with a domexception.
...when this policy is enabled, the promise returned by navigator.requestmidiaccess() will reject with a domexception.
...And 3 more matches
New in JavaScript - Archive of obsolete content
Archive › Web › JavaScript › New in JavaScript
javascript was released as version 1.0 in march 1996 in netscape navigator 2.0 and internet explorer 2.0.
... javascript 1.1 version shipped in netscape navigator 3.0.
... javascript 1.2 version shipped in netscape navigator 4.0-4.05.
...And 2 more matches
Using the Beacon API - Web APIs
Web › API › Beacon API › Using the Beacon API
navigator.sendbeacon() the beacon api's navigator.sendbeacon() method sends a beacon request to the server in the global browsing context.
... window.onload = window.onunload = function analytics(event) { if (!navigator.sendbeacon) return; var url = "https://example.com/analytics"; // create the data to send var data = "state=" + event.type + "&location=" + location.href; // send the beacon var status = navigator.sendbeacon(url, data); // log the data and result console.log("sendbeacon: url = ", url, "; data = ", data, "; status = ", status); }; the following example creates a submit handler a...
... window.onsubmit = function send_analytics() { var data = json.stringify({ location: location.href, time: date() }); navigator.sendbeacon('/analytics', data); }; workernavigator.sendbeacon() the beacon api's workernavigator.sendbeacon() method works identically to the usual method, but is accessible from worker global scope.
...And 2 more matches
LockManager.request() - Web APIs
Web › API › LockManager › request
await navigator.locks.request('my_resource', async lock => { // the lock was granted.
... async function do_read() { await navigator.locks.request('my_resource', {mode: 'shared'}, async lock => { // read code here.
... function do_write() { await navigator.locks.request('my_resource', {mode: 'exclusive'}, async lock => { // write code here.
...And 2 more matches
Screen Wake Lock API - Web APIs
Web › API › Screen Wake Lock API
you acquire a wakelocksentinel object by calling the navigator.wakelock.request() promise based method that resolves if the platform allows it.
... navigator.wakelock returns a wakelock object instance, from which all other functionality can be accessed.
... if ('wakelock' in navigator) { issupported = true; statuselem.textcontent = 'screen wake lock api supported!'; } else { wakebutton.disabled = true; statuselem.textcontent = 'wake lock is not supported by this browser.'; } requesting a wake lock the following example demonstrates how to request a wakelocksentinel object.
...And 2 more matches
Vibration API - Web APIs
Web › API › Vibration API
vibration is controlled with a single method: navigator.vibrate().
... a single vibration you may pulse the vibration hardware one time by specifying either a single value or an array consisting of only one value: window.navigator.vibrate(200); window.navigator.vibrate([200]); both of these examples vibrate the device for 200 ms.
...for example: window.navigator.vibrate([200, 100, 200]); this vibrates the device for 200 ms, then pauses for 100 ms before vibrating the device again for another 200 ms.
...And 2 more matches
Using the WebVR API - Web APIs
Web › API › WebVR API › Using the WebVR API
a typical (simple) webvr app works like this: navigator.getvrdisplays() is used to get a reference to your vr display.
...first of all, we check to see if navigator.getvrdisplays exists — this is the entry point into the api, and therefore good basic feature detection for webvr.
... // webvr: check to see if webvr is supported if(navigator.getvrdisplays) { console.log('webvr 1.1 supported'); inside our if() { ...
...And 2 more matches
WebVR API - Web APIs
Web › API › WebVR API
concepts and usage any vr devices attached to your computer will be returned by the navigator.getvrdisplays() method; each one will be represented by a vrdisplay object.
... a typical (simple) webvr app would work like so: navigator.getvrdisplays() is used to get a reference to your vr display.
...you can easily test for this by checking to see if the navigator method getvrdisplays() is null: if (!navigator.getvrdisplays) { console.error("webvr is not available"); } else { /* use webvr */ } using controllers: combining webvr with the gamepad api many webvr hardware setups feature controllers that go along with the headset.
...And 2 more matches
Movement, orientation, and motion: A WebXR example - Web APIs
Web › API › WebXR Device API › Movement and motion
if false, the polyfill is only used if the browser doesn't implement navigator.xr.
...n onload() { xrbutton = document.queryselector("#enter-xr"); xrbutton.addeventlistener("click", onxrbuttonclick); projectionmatrixout = document.queryselector("#projection-matrix div"); modelmatrixout = document.queryselector("#model-view-matrix div"); cameramatrixout = document.queryselector("#camera-matrix div"); mousematrixout = document.queryselector("#mouse-matrix div"); if (!navigator.xr || enableforcepolyfill) { console.log("using the polyfill"); polyfill = new webxrpolyfill(); } setupxrbutton(); } the load event handler gets a reference to the button that toggles webxr on and off into xrbutton, then adds a handler for click events.
... then we look to see if navigator.xr is defined.
...And 2 more matches
Web Authentication API - Web APIs
Web › API › Web Authentication API
similar to the other forms of the credential management api, the web authentication api has two basic methods that correspond to register and login: navigator.credentials.create() - when used with the publickey option, creates new credentials, either for registering a new account or for associating a new asymmetric key pair credentials with an existing account.
... navigator.credentials.get() - when used with the publickey option, uses an existing set of credentials to authenticate to a service, either logging a user in or as a form of second-factor authentication.
...this interface is accessible from navigator.credentials.
...And 2 more matches
Details of the object model - JavaScript
Web › JavaScript › Guide › Details of the Object Model
so, you could give specific information for mark as follows: mark.name = 'doe, mark'; mark.dept = 'admin'; mark.projects = ['navigator']; adding properties in javascript, you can add properties to any object at run time.
...here's the new definition for the engineer constructor: function engineer(name, projs, mach) { this.base = workerbee; this.base(name, 'engineering', projs); this.machine = mach || ''; } suppose you create a new engineer object as follows: var jane = new engineer('doe, jane', ['navigator', 'javascript'], 'belau'); javascript follows these steps: the new operator creates a generic object and sets its __proto__ property to engineer.prototype.
... the constructor calls the base method, passing as its arguments two of the arguments passed to the constructor ("doe, jane" and ["navigator", "javascript"]) and also the string "engineering".
...And 2 more matches
IdentityManager.getVerifiedEmail() - Archive of obsolete content
Archive › IdentityManager › getVerifiedEmail
note: this function has been deprecated in favor of navigator.id.get(), which has the same behavior, additional options, and a shorter name.
... navigator.id.getverifiedemail() will ask the user to choose an email address to sign in with, and may ask the user for their browserid password if the user's certificate has expired.
... syntax window.navigator.id.getverifiedemail(gotassertion); parameters gotassertion a callback function which will be called with a signed assertion object or null.
... see also browserid navigator.id navigator.id.get() navigator.id.logout() ...
IdentityManager.watch() - Archive of obsolete content
Archive › IdentityManager › watch
syntax navigator.id.watch({ loggedinuser: 'bob@example.org', onlogin: function(assertion) { // a user has logged in!
... example navigator.id.watch({ loggedinuser: currentuser, // this is email of current user logged into your site onlogin: function(assertion) { $.ajax({ // this example uses jquery, but you can use whatever you'd like type: 'post', url: '/auth/login', // this is a url on your website.
... data: {assertion: assertion} success: function(res, status, xhr) { window.location.reload(); }, error: function(xhr, status, err) { navigator.id.logout(); alert("login failure: " + err); } }); }, onlogout: function() { $.ajax({ type: 'post', url: '/auth/logout', // this is a url on your website.
... see also browserid navigator.id navigator.id.logout() navigator.id.request() ...
Getting Started - Archive of obsolete content
Archive › Mozilla › Creating a Skin for SeaMonkey 2.x › Getting Started
skin\classic\navigator navigator contains some icons and styles for all sm components.
...into this directory put a zip archive called my_theme.jar containing navigator, global, communicator, editor, help, messenger, messenger-newsblog and mozapps directories from above.
...skin global my_theme jar:chrome/my_theme.jar!/global/ skin mozapps my_theme jar:chrome/my_theme.jar!/mozapps/ skin messenger my_theme jar:chrome/my_theme.jar!/messenger/ skin messenger-newsblog my_theme jar:chrome/my_theme.jar!/messenger-newsblog/ skin communicator my_theme jar:chrome/my_theme.jar!/communicator/ skin help my_theme jar:chrome/my_theme.jar!/help/ skin navigator my_theme jar:chrome/my_theme.jar!/navigator/ skin editor my_theme jar:chrome/my_theme.jar!/editor/ save the file and exit the text editor.
... you need to do is repackage a jar file with the following directory structure, using your favorite archive manager to create a zip archive: /chrome/my_theme.jar!/communicator/* /chrome/my_theme.jar!/editor/* /chrome/my_theme.jar!/global/* /chrome/my_theme.jar!/help/* /chrome/my_theme.jar!/messenger/* /chrome/my_theme.jar!/messenger-newsblog/* /chrome/my_theme.jar!/mozapps/* /chrome/my_theme.jar!/navigator/* /chrome.manifest /install.rdf /icon.png /preview.png make sure not to just zip up the my_theme parent directory since that will cause the drag and drop install in the next section to fail without error messages.
Adding extra email addresses with Persona - Archive of obsolete content
Archive › Mozilla › Persona › The implementor s guide › Adding extra email addresses with Persona
clarify the context of the request when you request a new assertion using with either the old navigator.id.get() api or the navigator.id.request() api, persona expects that the user is trying to sign into a website, and the user interface it displays reflects that.
... update loggedinuser if you're using the navigator.id.get() api in the rest of your site, then you can just make a new navigator.id.get() call to get the extra email address.
... but if you use navigator.id.request(), then you must also use navigator.id.request() to get the extra email address.
... in this case, when you have verified the assertion inside your onlogin handler, you must update the loggedinuser argument to navigator.id.watch() with the new email address.
Cross Package Overlays - Archive of obsolete content
Archive › Mozilla › XUL › Tutorial › Cross Package Overlays
this value (browser-toolbox) is the same as the identifier of the toolbox in the browser window (navigator.xul).
... the id of the toolbox changed from "<code>navigator-toolbox</code>" to "<code>browser-toolbox</code>" in firefox 3 beta 3.
... <rdf:seq about="urn:mozilla:overlays"> <rdf:li resource="chrome://navigator/content/navigator.xul"/> </rdf:seq> this declares that we are adding a overlay window, a child of the root overlay node (urn:mozilla:overlays).
... <rdf:seq about="chrome://navigator/content/navigator.xul"> <rdf:li>chrome://findfile/content/foverlay.xul</rdf:li> </rdf:seq> mozilla reads this information and builds a list of overlays that are applied to other windows.
Theme changes in Firefox 4 - Archive of obsolete content
Archive › Themes › Theme changes in Firefox 4
the iconsize attribute of the toolbox element in the main browser window (#navigator-toolbox) still reflects the user preference in the toolbar customization palette.
...to do this, use a css rule that depends on the iconsize attribute on the #navigator-toolbox element.
... note: a rule that depends on the user preference cannot be applied to the add-on bar because it is not a child of the #navigator-toolbox element.
...thus, it includes this rule in browser.css: #nav-bar { counter-reset: smallicons; } to use large icons for add-on buttons in the bookmarks toolbar when the related user preference is set: #navigator-toolbox[iconsize="large"] > #personaltoolbar { counter-reset: largeicons; } to use large icons everywhere, including the menu bar, regardless of the user preference: #navigator-toolbox > toolbar, #addon-bar { counter-reset: largeicons; } creating a theme that works for firefox 4 on mac os x create a new directory (for example, my_theme).
Developing cross-browser and cross-platform pages - Archive of obsolete content
Archive › Using Web Standards in your Web Pages › Developing cross-browser and cross-platform pages
the browser identification approach relies on functions that check the browser type string value and browser version string value and that search for certains characters or sub-strings in the navigator.useragent property string.
... // bad sample if (navigator.appversion.charat(0) == "8") { if (navigator.appname == "netscape") { isns8 = true; alert("netscape 8"); }; } else if (navigator.appversion.indexof("msie") != -1) { isie = true; alert("internet explorer"); }; while this kind of checking in the above code can work in a crude sense, sharp readers may wonder what happens when internet explorer 8 is released or when an opera 8.x user visits the page or even when an...
... another major problem with this approach is that the browser identity can be "spoofed" because, in many modern browsers, the navigator.appversion and navigator.useragent string properties are user configurable strings.
... opera 6+ allows users to set the browser identification string via a menu internet explorer uses the windows registry safari, konqueror and icab browsers can mask their browser identity under internet explorer or netscape labels a user or browser distributor can put what they want in the navigator.useragent string and this may trick your code into executing a "wrong" block of code.
Implementing feature detection - Learn web development
Learn › Tools and testing › Cross browser testing › Feature detection
let's recap and look at the example we touched on in our handling common javascript problems — the geolocation api (which exposes available location data for the device the web browser is running on) has the main entry point for its use, a geolocation property available on the global navigator object.
... therefore, you can detect whether the browser supports geolocation or not by using something like the following: if ("geolocation" in navigator) { navigator.geolocation.getcurrentposition(function(position) { // show the location on a map, perhaps using the google maps api }); } else { // give the user a choice of static maps instead perhaps } it is probably better to use an established feature detection library however, rather than writing your own all the time.
... if("geolocation" in navigator) { ...
... finally, add another <script> element at the bottom of the html body (just before the </body> tag), and put the following script inside the tags: if (modernizr.geolocation) { navigator.geolocation.getcurrentposition(function(position) { let latlng = new google.maps.latlng(position.coords.latitude,position.coords.longitude); let myoptions = { zoom: 8, center: latlng, maptypeid: google.maps.maptypeid.terrain, disabledefaultui: true } let map = new google.maps.map(document.getelementbyid("map_canvas"), myoptions); }); } else { const pa...
Handling common JavaScript problems - Learn web development
Learn › Tools and testing › Cross browser testing › JavaScript
as a quick example, the geolocation api (which exposes available location data for the device the web browser is running on) has a main entry point for its use — a geolocation property available on the global navigator object.
... therefore, you can detect whether the browser supports geolocation or not by using something like the following: if("geolocation" in navigator) { navigator.geolocation.getcurrentposition(function(position) { // show the location on a map, perhaps using the google maps api }); } else { // give the user a choice of static maps instead perhaps } you could also write such a test for a css feature, for example by testing for the existence of element.style.property (e.g.
... the code used to look something like this (although this is a simplified example): let ua = navigator.useragent; if(ua.indexof('firefox') !== -1) { // run firefox-specific code } else if(ua.indexof('chrome') !== -1) { // run chrome-specific code } the idea was fairly good — detect what browser is viewing the site, and run code as appropriate to make sure the browser will be able to use your site ok.
... note: try opening up your javascript console now and running navigator.useragent, to see what you get returned.
Clipboard.read() - Web APIs
Web › API › Clipboard › read
syntax var promise = navigator.clipboard.read(); parameters none.
... example after using navigator.permissions.query() to find out if we have (or if the user will be prompted to allow) "clipboard-read" access, this example fetches the data currently on the clipboard.
... navigator.permissions.query({name: "clipboard-read"}).then(result => { // if permission to read the clipboard is granted or if the user will // be prompted to allow it, we proceed.
... if (result.state == "granted" || result.state == "prompt") { navigator.clipboard.read().then(data => { for (let i=0; i<data.items.length; i++) { if (data.items[i].type != "image/png") { alert("clipboard contains non-image data.
ContentIndex - Web APIs
Web › API › ContentIndex
// reference registration const registration = await navigator.serviceworker.ready; // feature detection if ('index' in registration) { // content index api functionality const contentindex = registration.index; } adding to the content index here we're declaring an item in the correct format and creating an asynchronous function which uses the add() method to register it with the content index.
...post-1', url: '/posts/amet.html', title: 'amet consectetur adipisicing', description: 'repellat et quia iste possimus ducimus aliquid a aut eaque nostrum.', icons: [{ src: '/media/dark.png', sizes: '128x128', type: 'image/png', }], category: 'article' }; // our asynchronous function to add indexed content async function registercontent(data) { const registration = await navigator.serviceworker.ready; // feature detect content index if (!registration.index) { return; } // register content try { await registration.index.add(data); } catch (e) { console.log('failed to register content: ', e.message); } } retrieving items within the current index the below example shows an asynchronous function that retrieves items within the content index and iterate...
... async function createreadinglist() { // access our service worker registration const registration = await navigator.serviceworker.ready; // get our index entries const entries = await registration.index.getall(); // create a containing element const readinglistelem = document.createelement('div'); // test for entries if (!array.length) { // if there are no entries, display a message const message = document.createelement('p'); message.innertext = 'you currently have no articles saved for offline reading.' readinglistelem.append(message); } else { // if entries are present, display in a list of links to the content const listelem = document.createelement('ul'); for (const entry of entries) { ...
... async function unregistercontent(article) { // reference registration const registration = await navigator.serviceworker.ready; // feature detect content index if (!registration.index) return; // unregister content from index await registration.index.delete(article.id); } all the above methods are available within the scope of the service worker.
Content Index API - Web APIs
Web › API › Content Index API
// reference registration const registration = await navigator.serviceworker.ready; // feature detection if ('index' in registration) { // content index api functionality const contentindex = registration.index; } adding to the content index here we're declaring an item in the correct format and creating an asynchronous function which uses the add() method to register it with the content index.
...post-1', url: '/posts/amet.html', title: 'amet consectetur adipisicing', description: 'repellat et quia iste possimus ducimus aliquid a aut eaque nostrum.', icons: [{ src: '/media/dark.png', sizes: '128x128', type: 'image/png', }], category: 'article' }; // our asynchronous function to add indexed content async function registercontent(data) { const registration = await navigator.serviceworker.ready; // feature detect content index if (!registration.index) { return; } // register content try { await registration.index.add(data); } catch (e) { console.log('failed to register content: ', e.message); } } retrieving items within the current index the below example shows an asynchronous function that retrieves items within the content index and iterate...
... async function createreadinglist() { // access our service worker registration const registration = await navigator.serviceworker.ready; // get our index entries const entries = await registration.index.getall(); // create a containing element const readinglistelem = document.createelement('div'); // test for entries if (!array.length) { // if there are no entries, display a message const message = document.createelement('p'); message.innertext = 'you currently have no articles saved for offline reading.' readinglistelem.append(message); } else { // if entries are present, display in a list of links to the content const listelem = document.createelement('ul'); for (const entry of entries) { ...
... async function unregistercontent(article) { // reference registration const registration = await navigator.serviceworker.ready; // feature detect content index if (!registration.index) return; // unregister content from index await registration.index.delete(article.id); } all the above methods are available within the scope of the service worker.
Keyboard API - Web APIs
Web › API › Keyboard API
the keyboard interface is accessed through navigator.keyboard.
... if (navigator.keyboard) { var keyboard = navigator.keyboard; keyboard.getlayoutmap() .then(keyboardlayoutmap => { var upkey = keyboardlayoutmap.get('keyw'); window.alert('press ' + upkey + ' to move up.'); }); } else { // do something else.
... to capture the "w", "a", "s", and "d" keys, call lock() with a list that contains the key code attribute value for each of these keys: navigator.keyboard.lock(["keyw", "keya", "keys", "keyd"]); this captures these keys regardless of which modifiers are used with the key press.
... navigator.keyboard read only returns a keyboard object which provides access to functions that retrieve keyboard layout maps and toggle capturing of key presses from the physical keyboard.
MediaDevices.ondevicechange - Web APIs
Web › API › MediaDevices › ondevicechange
let videoelement = document.getelementbyid("video"); let logelement = document.getelementbyid("log"); function log(msg) { logelement.innerhtml += msg + "<br>"; } document.getelementbyid("startbutton").addeventlistener("click", function() { navigator.mediadevices.getusermedia({ video: { width: 160, height: 120, framerate: 30 }, audio: { samplerate: 44100, samplesize: 16, volume: 0.25 } }).then(stream => { videoelement.srcobject = stream; updatedevicelist(); }) .catch(err => log(err.name + ": " + err.message)); }, false); we set up global variables that contain referen...
... function updatedevicelist() { navigator.mediadevices.enumeratedevices() .then(function(devices) { audiolist.innerhtml = ""; videolist.innerhtml = ""; devices.foreach(function(device) { let elem = document.createelement("li"); let [kind, type, direction] = device.kind.match(/(\w+)(input|output)/i); elem.innerhtml = "<strong>" + device.label + "</strong> (" + direction + ")"; if (type === "audio") ...
...{ audiolist.appendchild(elem); } else if (type === "video") { videolist.appendchild(elem); } }); }); } updatedevicelist() consists entirely of a call to the function enumeratedevices() on the mediadevices object referenced in the navigator.mediadevices property, as well as the code that's run when the promise returned by enumeratedevices() is fulfilled.
...the second is in the event handler for devicechange: navigator.mediadevices.ondevicechange = function(event) { updatedevicelist(); } with this code in place, each time the user plugs in a camera, microphone, or other media device, or turns one on or off, we call updatedevicelist() to redraw the list of connected devices.
MediaSession.setActionHandler() - Web APIs
Web › API › MediaSession › setActionHandler
syntax navigator.mediasession.setactionhandler(type, callback) parameters type a domstring representing an action type to listen for.
... let skiptime = 10; // time to skip in seconds navigator.mediasession.setactionhandler('seekforward', evt => { // user clicked "seek forward" media notification icon.
... audio.currenttime = math.min(audio.currenttime + skiptime, audio.duration); }); navigator.mediasession.setactionhandler('seekbackward', evt => { // user clicked "seek backward" media notification icon.
... audio.currenttime = math.max(audio.currenttime - skiptime, 0); }); supporting multiple actions in one handler function you can also, if you prefer, use a single function to handle multiple action types, by checking the value of the mediasessionactiondetails object's action property: let skiptime = 7; navigator.mediasession.setactionhandler("seekforward", handleseek); navigator.mediasession.setactionhandler("seekbackward", handleseek); function handleseek(details) { switch(details.action) { case "seekforward": audio.currenttime = math.min(audio.currenttime + skiptime, audio.duration); break; case "seekbackward": audio.currenttime = math.max(audio.currenttime - skiptime, 0); break; } } here, the handleseek() function handles both seekbackwar...
Network Information API - Web APIs
Web › API › Network Information API
the entire api consists of the addition of the networkinformation interface and a single property to the navigator interface: navigator.connection.
... var connection = navigator.connection || navigator.mozconnection || navigator.webkitconnection; var type = connection.effectivetype; function updateconnectionstatus() { console.log("connection type changed from " + type + " to " + connection.effectivetype); type = connection.effectivetype; } connection.addeventlistener('change', updateconnectionstatus); preload large resources the connection object is useful for deciding whether to preload resources that take large amounts of bandwidth or memory.
... let preloadvideo = true; var connection = navigator.connection || navigator.mozconnection || navigator.webkitconnection; if (connection) { if (connection.effectivetype === 'slow-2g') { preloadvideo = false; } } interfaces networkinformation provides information about the connection a device is using to communicate with the network and provides a means for scripts to be notified if the connection type changes.
...it is instead accessed through the navigator interface.
Permissions.revoke() - Web APIs
Web › API › Permissions › revoke
syntax this method is called on the global permissions object navigator.permissions.
... var revokepromise = navigator.permissions.revoke(descriptor); parameters descriptor an object based on the permissiondescriptor dictionary that sets options for the operation consisting of a comma-separated list of name-value pairs.
...by the user, in the relevant permissions dialog), navigator.permissions.query() will return true for both notifications and push.
... function revokepermission() { navigator.permissions.revoke({name:'geolocation'}).then(function(result) { report(result.state); }); } ...
PluginArray - Web APIs
Web › API › PluginArray
the pluginarray interface is used to store a list of plugin objects describing the available plugins; it's returned by the window.navigator.plugins property.
... var pluginslength = navigator.plugins.length; document.body.innerhtml = pluginslength + " plugin(s)<br>" + '<table id="plugintable"><thead>' +'<tr><th>name</th><th>filename</th><th>description</th><th>version</th></tr>' +'</thead><tbody></tbody></table>'; var table = document.getelementbyid('plugintable'); for(var i = 0; i < pluginslength; i++) { let newrow = table.insertrow(); newrow.insertcell().textcontent = n...
...avigator.plugins[i].name; newrow.insertcell().textcontent = navigator.plugins[i].filename; newrow.insertcell().textcontent = navigator.plugins[i].description; newrow.insertcell().textcontent = navigator.plugins[i].version?navigator.plugins[i].version:""; } the following example displays information about the installed plugin(s).
... var pluginslength = navigator.plugins.length; document.write( pluginslength.tostring() + " plugin(s)<br>" + "name | filename | description<br>" ); for(var i = 0; i < pluginslength; i++) { document.write( navigator.plugins[i].name + " | " + navigator.plugins[i].filename + " | " + navigator.plugins[i].description + " | " + navigator.plugins[i].version + "<br>" ); } specifications specification status comment html living standardthe definition of 'pluginarray' in that specification.
Presentation.receiver - Web APIs
Web › API › Presentation › receiver
syntax receiver = presentation.receiver; receiver = navigator.presentation.receiver; since the presentation interface is typically accessed through navigation.presentation, the second form of the syntax shown above is the more commonly used.
... example determining whether or not the context is receiving a presentation you can easily determine whether or not the context is the receiver for a presentation by checking the value of navigator.receiver.
... if (navigator.receiver) { footer.innerhtml = "receiving presentation"; } else { footer.innerhtml = "(idle)"; } accessing the connection list this example uses receiver to access the list of incoming connections and to build and display a list of those connections' id strings.
... let listelem = document.getelementbyid("connectionview"); navigator.presentation.receiver.connectionlist .then(function(connections) { connections.foreach(function(aconnection)) { listelem.innerhtml += "<li>" + aconnection.id + "</li>"; }); }); after getting access to the output list element in the variable connectionview, navigator.receiver is used to get a reference to the presentationreceiver object for this context, and its connectionlist is used to get a promise which will be called when the list is available.
PublicKeyCredential - Web APIs
Web › API › PublicKeyCredential
it is either of type authenticatorattestationresponse if the publickeycredential was the results of a navigator.credentials.create() call, or of type authenticatorassertionresponse if the publickeycredential was the result of a navigator.credentials.get() call.
... examples creating a new instance of publickeycredential here, we use navigator.credentials.create() to generate a new credential.
... var publickey = { challenge: /* from the server */, rp: { name: "example corp", id : "login.example.com" }, user: { id: new uint8array(16), name: "jdoe@example.com", displayname: "john doe" }, pubkeycredparams: [ { type: "public-key", alg: -7 } ] }; navigator.credentials.create({ publickey }) .then(function (newcredentialinfo) { var response = newcredentialinfo.response; var clientextensionsresults = newcredentialinfo.getclientextensionresults(); }).catch(function (err) { console.error(err); }); getting an existing instance of publickeycredential here, we fetch an existing credential from an authenticator, using navigator.credentials.get().
... var options = { challenge: new uint8array([/* bytes sent from the server */]) }; navigator.credentials.get({ "publickey": options }) .then(function (credentialinfoassertion) { // send assertion response back to the server // to proceed with the control of the credential }).catch(function (err) { console.error(err); }); specifications specification status comment web authentication: an api for accessing public key credentials level 1the definition of 'publickeycredential interface' in that specification.
Using the Screen Capture API - Web APIs
Web › API › Screen Capture API › Using Screen Capture
capturing screen contents capturing screen contents as a live mediastream is initiated by calling navigator.mediadevices.getdisplaymedia(), which returns a promise that resolves to a stream containing the live screen contents.
... starting screen capture: async/await style async function startcapture(displaymediaoptions) { let capturestream = null; try { capturestream = await navigator.mediadevices.getdisplaymedia(displaymediaoptions); } catch(err) { console.error("error: " + err); } return capturestream; } you can write this code either using an asynchronous function and the await operator, as shown above, or using the promise directly, as seen below.
... starting screen capture: promise style function startcapture(displaymediaoptions) { let capturestream = null; return navigator.mediadevices.getdisplaymedia(displaymediaoptions) .catch(err => { console.error("error:" + err); return null; }); } either way, the user agent responds by presenting a user interface that prompts the user to choose the screen area to share.
... async function startcapture() { logelem.innerhtml = ""; try { videoelem.srcobject = await navigator.mediadevices.getdisplaymedia(displaymediaoptions); dumpoptionsinfo(); } catch(err) { console.error("error: " + err); } } after clearing the contents of the log in order to get rid of any leftover text from the previous attempt to connect, startcapture() calls getdisplaymedia(), passing into it the constraints object defined by displaymediaoptions.
ServiceWorkerContainer.register() - Web APIs
Web › API › ServiceWorkerContainer › register
if ('serviceworker' in navigator) { // register a service worker hosted at the root of the // site using the default scope.
... navigator.serviceworker.register('/sw.js').then(function(registration) { console.log('service worker registration succeeded:', registration); }, /*catch*/ function(error) { console.log('service worker registration failed:', error); }); } else { console.log('service workers are not supported.'); } the following code, if included in example.com/index.html, at the root of a site, would apply to exactly the same pages as the example above.
... if ('serviceworker' in navigator) { // declaring scope manually navigator.serviceworker.register('/sw.js', {scope: './'}).then(function(registration) { console.log('service worker registration succeeded:', registration); }, /*catch*/ function(error) { console.log('service worker registration failed:', error); }); } else { console.log('service workers are not supported.'); } there is frequent confusion surrounding the meaning and use of scope.
... if ('serviceworker' in navigator) { // declaring scope manually navigator.serviceworker.register('/sw.js', {scope: '/product/'}).then(function(registration) { console.log('service worker registration succeeded:', registration); }, /*catch*/ function(error) { console.log('service worker registration failed:', error); }); } else { console.log('service workers are not supported.'); } however, servers can remove this restriction by setting a service-worker-allowed header on the service worke...
ServiceWorkerContainer - Web APIs
Web › API › ServiceWorkerContainer
if ('serviceworker' in navigator) { // register a service worker hosted at the root of the // site using the default scope.
... navigator.serviceworker.register('/sw.js').then(function(registration) { console.log('service worker registration succeeded:', registration); // at this point, you can optionally do something // with registration.
... if (navigator.serviceworker.controller) { console.log('this page is currently controlled by:', navigator.serviceworker.controller); } // then, register a handler to detect when a new or // updated service worker takes control.
... navigator.serviceworker.oncontrollerchange = function() { console.log('this page is now controlled by:', navigator.serviceworker.controller); }; } else { console.log('service workers are not supported.'); } specifications specification status comment service workersthe definition of 'serviceworkercontainer' in that specification.
Signaling and video calling - Web APIs
Web › API › WebRTC API › Signaling and video calling
that would be weird."); return; } targetusername = clickedusername; createpeerconnection(); navigator.mediadevices.getusermedia(mediaconstraints) .then(function(localstream) { document.getelementbyid("local_video").srcobject = localstream; localstream.gettracks().foreach(track => mypeerconnection.addtrack(track, localstream)); }) .catch(handlegetusermediaerror); } } this begins with a basic sanity check: is the user already connected?
... once the rtcpeerconnection has been created, we request access to the user's camera and microphone by calling mediadevices.getusermedia(), which is exposed to us through the navigator.mediadevices.getusermedia property.
... note: we could restrict the set of permitted media inputs to a specific device or set of devices by calling navigator.mediadevices.enumeratedevices() to get a list of devices, filtering the resulting list based on our desired criteria, then using the selected devices' deviceid values in the deviceid field of the the mediaconstraints object passed into getusermedia().
... function handlevideooffermsg(msg) { var localstream = null; targetusername = msg.name; createpeerconnection(); var desc = new rtcsessiondescription(msg.sdp); mypeerconnection.setremotedescription(desc).then(function () { return navigator.mediadevices.getusermedia(mediaconstraints); }) .then(function(stream) { localstream = stream; document.getelementbyid("local_video").srcobject = localstream; localstream.gettracks().foreach(track => mypeerconnection.addtrack(track, localstream)); }) .then(function() { return mypeerconnection.createanswer(); }) .then(function(answer) { return mypeerconnection.setl...
WebXR Device API - Web APIs
Web › API › WebXR Device API
accessing the webxr api to gain access to the webxr api within the context of a given window, use the navigator.xr property, which returns an xrsystem object through which the entire webxr device api is then exposed.
... navigator.xr read only this property, added to the navigator interface, returns the xrsystem object through which the webxr api is exposed.
... webxr interfaces xr the navigator.xr property returns the window's instance of xrsystem, which is the mechanism by which your code accesses the webxr api.
...once an xrsession is obtained from navigator.xr.requestsession(), the session can be used to check the position and orientation of the viewer, query the device for environment information, and present the virtual or augmented world to the user.
IdentityManager.get() - Archive of obsolete content
Archive › IdentityManager › get
navigator.id.get() will ask the user to choose an email address to sign in with, and may ask the user for their persona password if the user's certificate has expired.
... syntax navigator.id.get(gotassertion); navigator.id.get(gotassertion, {privacypolicy: "/privacy.html", termsofservice: "/tos.html"}); parameters gotassertion a function which will be called with a signed assertion object or null.
... see also browserid navigator.id navigator.id.logout() ...
IdentityManager - Archive of obsolete content
Archive › IdentityManager
the identitymanager of the browserid protocol exposes the browserid api, via navigator.id.
...it improved upon the initial api by allowing options to be passed to navigator.id.get() and offering experimental support for browserid-managed persistent sessions.
...this method is deprecated; navigator.id.get() is backwards compatible and can be used instead.
Index of archived content - Archive of obsolete content
Archive › Index of archived content
.htaccess ( hypertext access ) 2015 mdn fellowship program api navigator navigator.moznotification add-ons add-on sdk builder guides content scripts communicating with other scripts communicating using "port" communicating using "postmessage" cross-domain content scripts interacting with page scripts loading content scripts reddit example port self ...
... adding extra email addresses with persona call logout() after a failed login call request() only from a click handler enabling users to change their email address problems integrating with crsf protection supporting users without javascript testing the navigator.id api user interface guidelines why persona for mozilla?
...onment variables affecting crash reporting io guide images, tables, and mysterious gaps installing plugins to gecko embedding browsers on windows mcd, mission control desktop, aka autoconfig monitoring wifi access points no proxy for configuration notes on html reflow same-origin policy for file: uris source navigator source code directories overview using xml data islands in mozilla using content preferences visualizing an audio spectrum working with bfcache cert_override.txt mozilla release faq navigator.id newsgroup summaries format mozilla.dev.apps.firefox-2006-09-2...
Enabling the behavior - updating the status periodically - Archive of obsolete content
Archive › Mozilla › Creating a Mozilla extension › Enabling the behavior - updating the status periodically
to enable its functionality, we have to add a reference to our javascript code into navigator.xul, just as we put a reference to our css code into that file back in specifying the appearance.
... put the javascript code into a file called tinderstatus.js in the same directory as navigator.xul and reference it in navigator.xul where other javascript scripts are referenced: ...
... <!-- navigator --> <script type="application/javascript" src="chrome://navigator/content/browser.js"/> <script type="application/javascript" src="chrome://navigator/content/navigator.js"/> <script type="application/javascript" src="chrome://navigator/content/navigatordd.js"/> <script type="application/javascript" src="chrome://navigator/content/sessionhistoryui.js"/> <script type="application/javascript" src="chrome://navigator/content/tinderstatus.js"/> <!-- hook for stringbundle overlays --> ...
Getting Started - Archive of obsolete content
Archive › Mozilla › Creating a skin for Mozilla › Getting Started
<rdf:li resource="urn:mozilla:skin:myskin/1.0:communicator"/> <rdf:li resource="urn:mozilla:skin:myskin/1.0:editor"/> <rdf:li resource="urn:mozilla:skin:myskin/1.0:global"/> <rdf:li resource="urn:mozilla:skin:myskin/1.0:messenger"/> <rdf:li resource="urn:mozilla:skin:myskin/1.0:navigator"/> finally, in the last section of the contents.rdf file we need to tell mozilla what version this skin is compliant with.
...n="1.0" about="urn:mozilla:skin:myskin/1.0:communicator"/> <rdf:description chrome:skinversion="1.0" about="urn:mozilla:skin:myskin/1.0:editor"/> <rdf:description chrome:skinversion="1.0" about="urn:mozilla:skin:myskin/1.0:global"/> <rdf:description chrome:skinversion="1.0" about="urn:mozilla:skin:myskin/1.0:messenger"/> <rdf:description chrome:skinversion="1.0" about="urn:mozilla:skin:myskin/1.0:navigator"/> save the file and exit the text editor.
...once the zip is created, rename it to myskin.jar contents of myskin.jar contents.rdf preview.png \navigator\...
jspage - Archive of obsolete content
Archive › Mozilla › Jetpack › jspage
e{if(a.item){return"collection";}}}}return typeof a;}function $unlink(c){var b;switch($type(c)){case"object":b={};for(var e in c){b[e]=$unlink(c[e]); }break;case"hash":b=new hash(c);break;case"array":b=[];for(var d=0,a=c.length;d<a;d++){b[d]=$unlink(c[d]);}break;default:return c;}return b;}var browser=$merge({engine:{name:"unknown",version:0},platform:{name:(window.orientation!=undefined)?"ipod":(navigator.platform.match(/mac|win|linux/i)||["other"])[0].tolowercase()},features:{xpath:!!(document.evaluate),air:!!(window.runtime),query:!!(document.queryselector)},plugins:{},engines:{presto:function(){return(!window.opera)?false:((arguments.callee.caller)?960:((document.getelementsbyclassname)?950:925)); },trident:function(){return(!window.activexobject)?false:((window.xmlhttprequest)?((document.query...
...selectorall)?6:5):4);},webkit:function(){return(navigator.taintenabled)?false:((browser.features.xpath)?((browser.features.query)?525:420):419); },gecko:function(){return(!document.getboxobjectfor&&window.mozinnerscreenx==null)?false:((document.getelementsbyclassname)?19:18);}}},browser||{});browser.platform[browser.platform.name]=true; browser.detect=function(){for(var b in this.engines){var a=this.engines[b]();if(a){this.engine={name:b,version:a};this.engine[b]=this.engine[b+a]=true; break;}}return{name:b,version:a};};browser.detect();browser.request=function(){return $try(function(){return new xmlhttprequest();},function(){return new activexobject("msxml2.xmlhttp"); },function(){return new activexobject("microsoft.xmlhttp");});};browser.features.xhr=!!(browser.request());browser.plugins.flash=(f...
...unction(){var a=($try(function(){return navigator.plugins["shockwave flash"].description; },function(){return new activexobject("shockwaveflash.shockwaveflash").getvariable("$version");})||"0 r0").match(/\d+/g);return{version:parseint(a[0]||0+"."+a[1],10)||0,build:parseint(a[2],10)||0}; })();function $exec(b){if(!b){return b;}if(window.execscript){window.execscript(b);}else{var a=document.createelement("script");a.setattribute("type","text/javascript"); a[(browser.engine.webkit&&browser.engine.version<420)?"innertext":"text"]=b;document.head.appendchild(a);document.head.removechild(a);}return b;}native.uid=1; var $uid=(browser.engine.trident)?function(a){return(a.uid||(a.uid=[native.uid++]))[0];}:function(a){return a.uid||(a.uid=native.uid++);};var window=new native({name:"window",legacy:(browser.e...
Persona Hosted Services - Archive of obsolete content
Archive › Mozilla › Persona › Bootstrapping Persona
web browsers must implement the navigator.id apis.
... a cross-browser, javascript implementation of the navigator.id apis for browsers without native support.
... cross-browser api library for persona to work, the user's browser must support the navigator.id api.
Call request() only from a click handler - Archive of obsolete content
Archive › Mozilla › Persona › The implementor s guide › Call request() only from a click handler
this means that your call to navigator.id.request() or navigator.id.get() must be made directly from a click or keypress handler.
...if you implement this by calling navigator.id.request() in response to a focus event on the text field, then the popup will be blocked.
... you can still implement sign-in on focus as follows: on the focus event, display a dialog with a "sign in" button, and have that button call navigator.id.request() in its click handler.
Installer Script - Archive of obsolete content
Archive › Mozilla › XPInstall › Scripting by example › Installer Script
registerchrome(content | delayed_chrome, getfolder(cf,"browser.xpi"),"content/navigator/"); 47.
... registerchrome(skin | delayed_chrome, getfolder(cf,"modern.jar"),"skin/modern/navigator/"); 52.
... registerchrome(skin | delayed_chrome, getfolder(cf,"classic.jar"),"skin/classic/navigator/"); 58.
Adobe Flash - Archive of obsolete content
Archive › Plugins › Scripting Plugins Adobe Flash
<script type="text/javascript">identifyflash();</script> typically, javascript code that determines what version of the plugin is installed looks at the mimetypes array that is part of the navigator object.
...an algorithmic approach to detecting flash plugin version might be: var plugin = navigator.mimetypes["application/x-shockwave-flash"].enabledplugin; var description = plugin.description; // 1.
...if the browser is a mach-o browser, determine whether the version of the plugin // is greater than 12, a hypothetical version when flash will fix the plugin to be // scriptable on mach-o browsers also var flashversionosxscriptable = 12; if(navigator.useragent.indexof("mach-o")!=-1) { if(flashversion < flashversionosxscriptable) // flash version is less than version 12, thus not scriptable on os x } // 6.
Gecko FAQ - Gecko Redirect 1
Gecko › FAQ
netscape released its own version of the browser branded as netscape navigator.
... the original mozilla browser, first released as navigator 1.0, was developed rapidly by a small team that was passionate about creating the next killer app, and they succeeded.
... gecko includes the following components: document parser (handles html and xml) layout engine with content model style system (handles css, etc.) javascript runtime (spidermonkey) image library networking library (necko) platform-specific graphics rendering and widget sets for win32, x, and mac user preferences library mozilla plug-in api (npapi) to support the navigator plug-in interface open java interface (oji), with sun java 1.2 jvm rdf back end font library security library (nss) original document information author(s): angus other contributors: ekrock, vidur, hidday, drunclear copyright information: portions of this content are © 1998–2006 by individual mozilla.org contributors; content available under a creative commons license ...
nsIDragDropHandler
Mozilla › Tech › XPCOM › Reference › Interface › nsIDragDropHandler
last changed in gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0) inherits from: nsisupports method overview void detach(); void hookupto(in nsidomeventtarget attachpoint, in nsiwebnavigation navigator); methods detach() unregisters all handlers related to drag and drop.
...void hookupto( in nsidomeventtarget attachpoint, in nsiwebnavigation navigator ); parameters attachpoint the receiver to which to attach drag handlers.
... navigator the nsiwebnavigation object to handle the dropped urls.
XUL Overlays
Mozilla › Tech › XUL › Overlays
the installation of a media plug-in, for example, may add new icons and menu items to the interface: in the navigatoroverlay.xul file or in a separate navigatorsspoverlay.xul file (where navigator.xul defines the basic ui for the navigator package), these new plug-in elements would be defined as a collection of elements or subtrees: <menuitem name="super stream player"/> <menupopup name="ss favorites"> <menuitem name="wave" src="mavericks.ssp"/> <menuitem name="soccer" src="brazil_soccer.ssp"/> </menupopup> ...
...inserting the following processing instruction before the doctype declaration in a base file tells the layout engine to load the named overlay file: <?xul-overlay href="chrome://component/content/componentoverlay.xul"?> where component is the name of the package being overlayed (e.g., chrome://navigator/content/navigatoroverlay.xul).
...the navigatoroverlay.xul file, for example, does not and should never load the navigator.css file that defines the master skin for the navigator package.
WebIDL bindings
Mozilla › WebIDL bindings
[navigatorproperty="propname"] setting this extended attribute to propname on an interface causes window.navigator.propname to be an instance of the interface.
... if you want an instance of the class to be added to window.navigator, add an extended attribute navigatorproperty="propertyname" which will make the instance available as window.navigator.propertyname.
... note that adding or removing navigatorproperty requires a clobber.
Plug-in Basics - Plugins
Plugins › Guide › Plug-in Basics
note: plug-in api calls and callbacks use the main navigator thread.
...var mimetype = navigator.mimetypes["application/x-shockwave-flash"]; if (mimetype) { // yes, so can we display with a plug-in?
...navigator uses either the value of the type attribute or the suffix of the filename given as the source to determine which plug-in to use.
Version, UI, and Status Information - Plugins
Plugins › Guide › Version, UI, and Status Information
to do so, it must find the major and minor version numbers, which are determined when the plug-in and navigator are compiled, and compare them.
...*/ if (netscape_minor < npvers_has_windowless) { /* plug-in is running in a version of the navigator */ /* that does not support windowless plug-ins.
... */ return false; } else /* plug-in is running in a navigator version */ /* that has windowless support */ return true; } detecting windowless support on other platforms browser implementations on other platforms did not have windowless plug-in support at the time it was added to ms windows and mac os x, so a different method must be used to detect whether the browser provides support.
Clipboard.write() - Web APIs
Web › API › Clipboard › write
syntax var promise = navigator.clipboard.write(data) parameters data an array of clipboarditem objects containing data to be written to the clipboard.
... function setclipboard(text) { let data = [new clipboarditem({ "text/plain": text })]; navigator.clipboard.write(data).then(function() { /* success */ }, function() { /* failure */ }); } the code begins by creating a new clipboarditem object into which the text will be placed for sending to the clipboard.
... example of copying canvas contents to the clipboard function copycanvascontentstoclipboard(canvas, ondone, onerror) { canvas.toblob(function (blob) { let data = [new clipboarditem({ [blob.type]: blob })]; navigator.clipboard.write(data).then(function () { ondone(); }, function (err) { onerror(err); }) }); } note: you can only pass in one clipboard item at a time.
Geolocation API - Web APIs
Web › API › Geolocation API
the geolocation api is accessed via a call to navigator.geolocation; this will cause the user's browser to ask them for permission to access their location data.
... navigator.geolocation the entry point into the api.
...tion) { const latitude = position.coords.latitude; const longitude = position.coords.longitude; status.textcontent = ''; maplink.href = `https://www.openstreetmap.org/#map=18/${latitude}/${longitude}`; maplink.textcontent = `latitude: ${latitude} °, longitude: ${longitude} °`; } function error() { status.textcontent = 'unable to retrieve your location'; } if(!navigator.geolocation) { status.textcontent = 'geolocation is not supported by your browser'; } else { status.textcontent = 'locating…'; navigator.geolocation.getcurrentposition(success, error); } } document.queryselector('#find-me').addeventlistener('click', geofindme); result specifications specification status comment geolocation api recommendation ...
MediaDeviceInfo.groupId - Web APIs
Web › API › MediaDeviceInfo › groupId
const getdevicegroup = maindevinfo => { let devlist = []; navigator.mediadevices.enumeratedevices() .then(devices => { devices.foreach(device => { if (device.groupid === maindevinfo.groupid) { devlist.push(device); } }); }); return devlist; }; the getdevicegroup() function takes as input the mediadeviceinfo object describing the device for which a group list is to be built.
... then navigator.mediadevices.enumeratedevices() is called to get the list of all media devices.
... this version of the example puts the passed-in device at the top of the result list, then adds any other members of the group that are found: const getdevicegroup = maindevinfo => { let devlist = [maindevinfo]; navigator.mediadevices.enumeratedevices() .then(devices => { devices.foreach(device => { if ((device.groupid === maindevinfo.groupid) && (device.deviceid !== maindevinfo.deviceid)) { devlist.push(device); } }); }); return devlist; }; ...
MediaDeviceInfo - Web APIs
Web › API › MediaDeviceInfo
the list of devices obtained by calling navigator.mediadevices.enumeratedevices() is an array of mediadeviceinfo objects, one per media device.
... if (!navigator.mediadevices || !navigator.mediadevices.enumeratedevices) { console.log("enumeratedevices() not supported."); return; } // list cameras and microphones.
... navigator.mediadevices.enumeratedevices() .then(function(devices) { devices.foreach(function(device) { console.log(device.kind + ": " + device.label + " id = " + device.deviceid); }); }) .catch(function(err) { console.log(err.name + ": " + err.message); }); this might produce: videoinput: id = cso9c0ypaf274oucpua53cne0yhlir2yxci+sqfbzz8= audioinput: id = rkxxbyjnabbadgqnnzqlvldmxls0yketycibg+xxnvm= audioinput: id = r2/xw1xupiyzunfv1lgrkoma5wtovckwfz368xcndm0= or if one or more media streams are active, or if persistent permissions have been granted: videoinput: facetime hd camera (built-in) id=cso9c0ypaf274oucpua53cne0yhlir2yxci+sqfbzz8= audioinput: default (built-in microphone) id=rkxxbyjnabbadgqnnzqlvldmxls0yketycibg+xxnvm= audioinput: built-in microphone id=r2/xw...
MediaDevices.enumerateDevices() - Web APIs
Web › API › MediaDevices › enumerateDevices
syntax var enumeratorpromise = navigator.mediadevices.enumeratedevices(); return value a promise that receives an array of mediadeviceinfo objects when the promise is fulfilled.
... if (!navigator.mediadevices || !navigator.mediadevices.enumeratedevices) { console.log("enumeratedevices() not supported."); return; } // list cameras and microphones.
... navigator.mediadevices.enumeratedevices() .then(function(devices) { devices.foreach(function(device) { console.log(device.kind + ": " + device.label + " id = " + device.deviceid); }); }) .catch(function(err) { console.log(err.name + ": " + err.message); }); this might produce: videoinput: id = cso9c0ypaf274oucpua53cne0yhlir2yxci+sqfbzz8= audioinput: id = rkxxbyjnabbadgqnnzqlvldmxls0yketycibg+xxnvm= audioinput: id = r2/xw1xupiyzunfv1lgrkoma5wtovckwfz368xcndm0= or if one or more mediastreams are active or persistent permissions are granted: videoinput: facetime hd camera (built-in) id=cso9c0ypaf274oucpua53cne0yhlir2yxci+sqfbzz8= audioinput: default (built-in microphone) id=rkxxbyjnabbadgqnnzqlvldmxls0yketycibg+xxnvm= audioinput: built-in microphone id=r2/xw1xupiyzunf...
MediaPositionState.duration - Web APIs
Web › API › MediaPositionState › duration
for example, a browser might use this information along with the position property and the navigator.mediasession.playbackstate, as well as the session's metadata to provide an integrated common user interface showing the currently playing media as well as standard pause, play, forward, reverse, and other controls.
... example in this example, an app performing a live stream provides information to the browser by preparing a mediapositionstate object and submitting it by calling navigator.mediasession.setpositionstate().
... let positionstate = { duration: infinity; playbackrate: 1.0; position: 0.0; }; navigator.mediasession.setpositionstate(positionstate); specifications specification status comment media session standardthe definition of 'mediapositionstate.duration' in that specification.
MediaPositionState.playbackRate - Web APIs
Web › API › MediaPositionState › playbackRate
for example, a browser might use this information along with the position property and the navigator.mediasession.playbackstate, as well as the session's metadata to provide an integrated common user interface showing the currently playing media as well as standard pause, play, forward, reverse, and other controls.
...it begins by creating a mediapositionstate object, then submits it to the browser it by calling navigator.mediasession.setpositionstate().
... let positionstate = { duration: mymediaduration; playbackrate: 2.0; position: mymediaposition; }; navigator.mediasession.setpositionstate(positionstate); note the value 2.0 as the playbackrate.
MediaSession.setPositionState() - Web APIs
Web › API › MediaSession › setPositionState
call this method on the navigator object's mediasession object.
... syntax navigator.mediasession.setpositionstate(statedict); parameters statedict optional an object conforming to the mediapositionstate dictionary, providing updated information about the playback position and speed of the document's ongoing media.
... let positioninterval = window.setinterval(() => { if (mymedia.isplaying) { navigator.mediasession.setpositionstate({ duration: mymedia.trackdurationinseconds, playbackrate: mymedia.playbackrate, position: mymedia.trackplaypositioninseconds }); } else { window.clearinterval(positioninterval); } }, 1000); specifications specification status comment media session standardthe definition of 'mediasession.setpositionstate()' ...
Media Session action types - Web APIs
Web › API › MediaSessionAction
let skiptime = 10; // time to skip in seconds navigator.mediasession.setactionhandler('seekforward', evt => { // user clicked "seek forward" media notification icon.
... audio.currenttime = math.min(audio.currenttime + skiptime, audio.duration); }); navigator.mediasession.setactionhandler('seekbackward', evt => { // user clicked "seek backward" media notification icon.
... audio.currenttime = math.max(audio.currenttime - skiptime, 0); }); supporting multiple actions in one handler function you can also, if you prefer, use a single function to handle multiple action types, by checking the value of the mediasessionactiondetails object's action property: let skiptime = 7; navigator.mediasession.setactionhandler("seekforward", handleseek); navigator.mediasession.setactionhandler("seekbackward", handleseek); function handleseek(details) { switch(details.action) { case "seekforward": audio.currenttime = math.min(audio.currenttime + skiptime, audio.duration); break; case "seekbackward": audio.currenttime = math.max(audio.currenttime - skiptime, 0); break; } } here, the handleseek() function handles both seekbackwar...
MediaSessionActionDetails - Web APIs
Web › API › MediaSessionActionDetails
let skiptime = 10; // time to skip in seconds navigator.mediasession.setactionhandler('seekforward', evt => { // user clicked "seek forward" media notification icon.
... audio.currenttime = math.min(audio.currenttime + skiptime, audio.duration); }); navigator.mediasession.setactionhandler('seekbackward', evt => { // user clicked "seek backward" media notification icon.
... audio.currenttime = math.max(audio.currenttime - skiptime, 0); }); supporting multiple actions in one handler function you can also, if you prefer, use a single function to handle multiple action types, by checking the value of the mediasessionactiondetails object's action property: let skiptime = 7; navigator.mediasession.setactionhandler("seekforward", handleseek); navigator.mediasession.setactionhandler("seekbackward", handleseek); function handleseek(details) { switch(details.action) { case "seekforward": audio.currenttime = math.min(audio.currenttime + skiptime, audio.duration); break; case "seekbackward": audio.currenttime = math.max(audio.currenttime - skiptime, 0); break; } } here, the handleseek() function handles both seekbackwar...
Recording a media element - Web APIs
Web › API › MediaStream Recording API › Recording a media element
while the article using the mediastream recording api demonstrates using the mediarecorder interface to capture a mediastream generated by a hardware device, as returned by navigator.mediadevices.getusermedia(), you can also use an html media element (namely <audio> or <video>) as the source of the mediastream to be recorded.
... getting an input stream and setting up the recorder now let's look at the most intricate piece of code in this example: our event handler for clicks on the start button: startbutton.addeventlistener("click", function() { navigator.mediadevices.getusermedia({ video: true, audio: true }).then(stream => { preview.srcobject = stream; downloadbutton.href = stream; preview.capturestream = preview.capturestream || preview.mozcapturestream; return new promise(resolve => preview.onplaying = resolve); }).then(() => startrecording(preview.capturestream(), recordingtimems)) .then (recordedchunks => { ...
... blob(recordedchunks, { type: "video/webm" }); recording.src = url.createobjecturl(recordedblob); downloadbutton.href = recording.src; downloadbutton.download = "recordedvideo.webm"; log("successfully recorded " + recordedblob.size + " bytes of " + recordedblob.type + " media."); }) .catch(log); }, false); when a click event occurs, here's what happens: lines 2-4 navigator.mediadevices.getusermedia() is called to request a new mediastream that has both video and audio tracks.
msSaveBlob - Web APIs
Web › API › Navigator › msSaveBlob
the navigator.mssaveblob() method saves the file or blob to disk.
... this method behaves in the same way as navigator.mssaveoropenblob() except that this disables the file open option.
... syntax navigator.mssaveblob(blob, defaultname); parameters blob a blob to be saved.
msSaveOrOpenBlob - Web APIs
Web › API › Navigator › msSaveOrOpenBlob
the navigator.mssaveoropenblob() method saves the file or blob to disk.
... this method behaves in the same way as navigator.mssaveblob() except that this enables the file open option.
... syntax navigator.mssaveoropenblob(blob, defaultname); parameters blob a blob to be saved.
Web-based protocol handlers - Web APIs
Web › API › Navigator › registerProtocolHandler › Web-based protocol handlers
for example: navigator.registerprotocolhandler("web+burger", "http://www.google.co.uk/?uri=%s", "burger handler"); where the parameters are: the protocol.
... example <!doctype html public "-//w3c//dtd html 4.01//en"> <html lang="en"> <head> <title>web protocol handler sample - register</title> <script type="text/javascript"> navigator.registerprotocolhandler("web+burger", "http://www.google.co.uk/?uri=%s", "burger handler"); </script> </head> <body> <h1>web protocol handler sample</h1> <p>this web page will install a web protocol handler for the <code>web+burger:</code> protocol.</p> </body> </html> activating now, anytime the user activates a link th...
...the data sent:</p> <textarea> <?php echo(htmlspecialchars($value, ent_quotes, 'utf-8')); ?> </textarea> </body> </html> references http://www.w3.org/tr/2011/wd-html5-20110525/timers.html#custom-handlers see also window.navigator.registercontenthandler nsiprotocolhandler (xul only) registerprotocolhandler enhancing the federated web at mozilla webdev register a custom protocolhandler at google developers.
Online and offline events - Web APIs
Web › API › NavigatorOnLine › Online and offline events
api navigator.online navigator.online is a property that maintains a true/false value (true for online, false for offline).
...according to the specification: the navigator.online attribute must return false if the user agent will not contact the network when the user follows links or when a script requests a remote page (or knows that such an attempt would fail)...
... here's the javascript part: window.addeventlistener('load', function() { var status = document.getelementbyid("status"); var log = document.getelementbyid("log"); function updateonlinestatus(event) { var condition = navigator.online ?
Permissions.query() - Web APIs
Web › API › Permissions › query
syntax navigator.permissions.query(permissiondescriptor).then(function(permissionstatus) { ...
...by the user, in the relevant permissions dialog), navigator.permissions.query() will return true for both notifications and push.
... example navigator.permissions.query({name:'geolocation'}).then(function(result) { if (result.state == 'granted') { showlocalnewswithgeolocation(); } else if (result.state == 'prompt') { showbuttontoenablelocalnews(); } // don't do anything if the permission was denied.
Using the Permissions API - Web APIs
Web › API › Permissions API › Using the Permissions API
accessing the permissions api the navigator.permissions property has been added to the browser to allow access to the global permissions object.
... function handlepermission() { navigator.permissions.query({name:'geolocation'}).then(function(result) { if (result.state == 'granted') { report(result.state); geobtn.style.display = 'none'; } else if (result.state == 'prompt') { report(result.state); geobtn.style.display = 'none'; navigator.geolocation.getcurrentposition(revealposition,positiondenied,geosettings); } else if (result.state == 'de...
... function revokepermission() { navigator.permissions.revoke({name:'geolocation'}).then(function(result) { report(result.state); }); } the revoke() function has been disabled by default starting in firefox 51, since its design has been brought into question in the web applications security working group.
PushManager.registrations() - Web APIs
Web › API › PushManager › registrations
syntax var request = navigator.push.registrations(); return a domrequest object to handle the success or failure of the method call.
... example var req = navigator.push.registrations(); req.onsuccess = function(e) { if (req.result.length > 0) { for (var i = 0, l = req.result.length; i < l; i++) { console.log("existing registration", req.result[i].pushendpoint, req.result[i].version); } // reuse existing endpoints.
... var register = navigator.push.register(); register.onsuccess = function(e) { console.log("registered new endpoint", register.result); } } } specification specification status comment push api working draft defines the pushmanager interface.
RTCPeerConnection.addTrack() - Web APIs
Web › API › RTCPeerConnection › addTrack
here's an example showing a function that uses getusermedia() to obtain a stream from a user's camera and microphone, then adds each track from the stream to the peer connection, without specifying a stream for each track: async opencall(pc) { const gumstream = await navigator.mediadevices.getusermedia( {video: true, audio: true}); for (const track of gumstream.gettracks()) { pc.addtrack(track); } } the result is a set of tracks being sent to the remote peer, with no stream associations.
... for example, consider this function that an application might use to begin streaming a device's camera and microphone input over an rtcpeerconnection to a remote peer: async opencall(pc) { const gumstream = await navigator.mediadevices.getusermedia( {video: true, audio: true}); for (const track of gumstream.gettracks()) { pc.addtrack(track, gumstream); } } the remote peer might then use a track event handler that looks like this: pc.ontrack = ({streams: [stream]} => videoelem.srcobject = stream; this sets the video element's current stream to the one that contains the track that...
... var mediaconstraints = { audio: true, // we want an audio track video: true // ...and we want a video track }; var desc = new rtcsessiondescription(sdp); pc.setremotedescription(desc).then(function () { return navigator.mediadevices.getusermedia(mediaconstraints); }) .then(function(stream) { previewelement.srcobject = stream; stream.gettracks().foreach(track => pc.addtrack(track, stream)); }) this code takes sdp which has been received from the remote peer and constructs a new rtcsessiondescription to pass into setremotedescription().
ServiceWorkerContainer.controller - Web APIs
Web › API › ServiceWorkerContainer › controller
syntax var mycontroller = navigator.serviceworker.controller; value a serviceworker object.
... example if ('serviceworker' in navigator) { // do a one-off check to see if a service worker's in control.
... if (navigator.serviceworker.controller) { console.log(`this page is currently controlled by: ${navigator.serviceworker.controller}`); } else { console.log('this page is not currently controlled by a service worker.'); } } else { console.log('service workers are not supported.'); } specifications specification status comment service workersthe definition of 'serviceworkerregistration.controller' in that specification.
ServiceWorkerContainer.startMessages() - Web APIs
Web › API › ServiceWorkerContainer › startMessages
examples if('serviceworker' in navigator) { navigator.serviceworker .register('/sw.js') .then(function() { console.log('service worker registered'); }); } // ...
... navigator.serviceworker.addeventlistener('message', (e) => { // ...
... }); navigator.serviceworker.startmessages(); specifications specification status comment service workersthe definition of 'serviceworkercontainer: startmessages()' in that specification.
WebXR application life cycle - Web APIs
Web › API › WebXR Device API › Lifecycle
make sure the webxr api is available; if navigator.xr is undefined, you can assume the user's browser and/or device doesn't support webxr.
... call navigator.xr.issessionsupported(), specifying the webxr experience mode you want to provide: inline, immersive-vr, or immersive-ar, in order to determine whether or not the type of session you wish to provide is available.
...this is done by calling navigator.xr.requestsession(), again specifying the string indicating the mode you want to enable: inline, immersive-vr, or immersive-ar.
Window - Web APIs
Web › API › Window
window.navigator read only returns a reference to the navigator object.
... connection events offline fired when the browser has lost access to the network and the value of navigator.online has switched to false.
... online fired when the browser has gained access to the network and the value of navigator.online has switched to true.
XRPermissionStatus - Web APIs
Web › API › XRPermissionStatus
the xrpermissionstatus interface defines the object returned by calling navigator.permissions.query() for the xr permission name; it indicates whether or not the app or site has permission to use webxr, an may be monitored over time for changes to that permissions tate.
... granted an array of strings listing the names of the features for which permission has been granted as of the time at which navigator.permissions.query() was called.
... any feature which was specified in either the optionalfeatures or requiredfeatures when calling navigator.permissions.query() are listed in granted if and only if permission to use them is granted.
XRSystem: requestSession() - Web APIs
Web › API › XRSystem › requestSession
navigator.xr.requestsession("immersive-vr") .then((xrsession) => { xrsession.addeventlistener('end', onxrsessionended); // do necessary session setup here.
...first, it checks to see if webxr is available by verifying the existence of navigator.xr.
... if (navigator.xr) { navigator.xr.issessionsupported('immersive-vr') .then((issupported) => { if (issupported) { immersivebutton.addeventlistener('click', onbuttonclicked); immersivebutton.innerhtml = 'enter xr'; immersivebutton.disabled = false; } else { console.log("webxr doesn't support immersive-vr mode!"); } }); } else { console.log("webxr is not available!"); } function onbuttonclicked() { if (!xrsession) { navigator.xr.request...
Index - HTTP
Web › HTTP › Headers › Index
when this policy is enabled, the promise returned by navigator.requestmediakeysystemaccess() will reject with a domexception.
...when this policy is enabled, the promise returned by navigator.requestmidiaccess() will reject with a domexception.
...when this policy is enabled, the promise returned by navigator.getvrdisplays() will reject with a domexception.
How to convert an overlay extension to restartless - Archive of obsolete content
Archive › Add-ons › How to convert an overlay extension to restartless
ome-flush-caches", null); } function install(data,reason) { } function uninstall(data,reason) { } function loadintowindow(window) { /* call/move your ui construction function here */ } function unloadfromwindow(window) { /* call/move your ui tear down function here */ } function foreachopenwindow(todo) // apply a function to all open browser windows { var windows = services.wm.getenumerator("navigator:browser"); while (windows.hasmoreelements()) todo(windows.getnext().queryinterface(components.interfaces.nsidomwindow)); } var windowlistener = { onopenwindow: function(xulwindow) { var window = xulwindow.queryinterface(components.interfaces.nsiinterfacerequestor) .getinterface(components.interfaces.nsidomwindow); function onwindow...
...load() { window.removeeventlistener("load",onwindowload); if (window.document.documentelement.getattribute("windowtype") == "navigator:browser") loadintowindow(window); } window.addeventlistener("load",onwindowload); }, onclosewindow: function(xulwindow) { }, onwindowtitlechange: function(xulwindow, newtitle) { } }; as mentioned above, components.utils.unload() will not work properly if the jsm file it is unloading is in a jar.
Chapter 4: Using XPCOM—Implementing advanced processes - Archive of obsolete content
Archive › Add-ons › Overlay Extensions › Firefox addons developer guide › Using XPCOM—Implementing advanced processes
listing 4: get active browser window netscape.security.privilegemanager .enableprivilege('universalxpconnect'); var windowmediator = components .classes['@mozilla.org/appshell/window-mediator;1'] .getservice(components.interfaces.nsiwindowmediator); var browser = windowmediator.getmostrecentwindow('navigator:browser'); alert(browser.gbrowser.mtabs.length); get overview of all windows with a certain type use the nsiwindowmediator.getenumerator() method to get an overview of all windows that have a certain type.
... listing 5: closing all browser windows var browsers = windowmediator.getenumerator('navigator:browser'); var browser; while (browsers.hasmoreelements()) { browser = browsers.getnext().queryinterface(components.interfaces.nsidomwindowinternal); browser.browsertrytoclosewindow(); } this method returns an overview of the specified window type in the form of an iterator pattern object called nsisimpleenumerator.
Extensions support in SeaMonkey 2 - Archive of obsolete content
Archive › Add-ons › SeaMonkey 2
some urls are listed below: url in firefox url in seamonkey overlays chrome://browser/content/browser.xul chrome://navigator/content/navigator.xul main browser window chrome://browser/content/pageinfo/pageinfo.xul chrome://navigator/content/pageinfo/pageinfo.xul page info window chrome://browser/content/preferences/permissions.xul chrome://communicator/content/permis...onsmanager.xul permissions manager dialog urls added in 2.1 ...
...you can use the application flag to select which overlay should be used with which application: overlay chrome://browser/content/browser.xul chrome://myaddon/content/ffoverlay.xul application={ec8030f7-c20a-464f-9b0e-13a3a9e97384} overlay chrome://messenger/content/mailwindowoverlay.xul chrome://myaddon/content/tboverlay.xul application={3550f703-e582-4d05-9a08-453d09bdfdc6} overlay chrome://navigator/content/navigator.xul chrome://myaddon/content/smoverlay.xul application={92650c4d-4b8e-4d2a-b7eb-24ecf4f6b63a} ...
Underscores in class and ID Names - Archive of obsolete content
Archive › Beginner tutorials › Underscores in class and ID Names
navigator 4.x honored the restriction against underscores, and so any class or id name with an underscore will be ignored by navigator 4.x, so the associated styles will never be applied.
... opera 3.x through 5.x does not recognize underscores or escaped underscores, and so acts the same as navigator 4.x in this regard.
chargingchange - Archive of obsolete content
Archive › Events › chargingchange
general info specification battery interface event bubbles no cancelable no target batterymanager default action none properties the event callback doesn't receive any event objects, but properties can be read from the batterymanager object received from the navigator.getbattery method.
... example navigator.getbattery().then(function(battery) { console.log("battery charging?
chargingtimechange - Archive of obsolete content
Archive › Events › chargingtimechange
general info specification battery interface event bubbles no cancelable no target batterymanager default action none properties the event callback doesn't receive any event objects, but properties can be read from the batterymanager object received from the navigator.getbattery method.
... example navigator.getbattery().then(function(battery) { console.log("battery charging time: " + battery.chargingtime + " seconds"); battery.addeventlistener('chargingtimechange', function() { console.log("battery charging time: " + battery.chargingtime + " seconds"); }); }); related events chargingchange dischargingtimechange levelchange ...
dischargingtimechange - Archive of obsolete content
Archive › Events › dischargingtimechange
general info specification battery interface event bubbles no cancelable no target batterymanager default action none properties the event callback doesn't receive any event objects, but properties can be read from the batterymanager object received from the navigator.getbattery method.
... example navigator.getbattery().then(function(battery) { console.log("battery discharging time: " + battery.dischargingtime + " seconds"); battery.addeventlistener('dischargingtimechange', function() { console.log("battery discharging time: " + battery.dischargingtime + " seconds"); }); }); related events chargingchange dischargingtimechange levelchange ...
levelchange - Archive of obsolete content
Archive › Events › levelchange
general info specification battery interface event bubbles no cancelable no target batterymanager default action none properties the event callback doesn't receive any event objects, but properties can be read from the batterymanager object received from the navigator.getbattery method.
... example navigator.getbattery().then(function(battery) { console.log("battery level: " + battery.level * 100 + " %"); battery.addeventlistener('levelchange', function() { console.log("battery level: " + battery.level * 100 + " %"); }); }); related events chargingchange chargingtimechange dischargingtimechange ...
IdentityManager.logout() - Archive of obsolete content
Archive › IdentityManager › logout
syntax navigator.id.logout(); example // execute navigator.id.logout(); when the user clicks "sign out" var signoutlink = document.getelementbyid('signout'); if (signoutlink) { signoutlink.onclick = function(event) { event.preventdefault(); navigator.id.logout(); }; }; specification not included in any specification.
... see also browserid navigator.id navigator.id.watch() navigator.id.logout() ...
Finding the file to modify - Archive of obsolete content
Archive › Mozilla › Creating a Mozilla extension › Finding the file to modify
the dom inspector will display the url of the xul file that defines the mozilla browser window, which is chrome://navigator/content/navigator.xul.
...in this case the chrome url refers to the file located at mozilla-installation-directory/chrome/content/navigator/navigator.xul.
Specifying the appearance - Archive of obsolete content
Archive › Mozilla › Creating a Mozilla extension › Specifying the appearance
for this we have to first create four icons, one for each tinderbox state (none, success, test failed, and busted), then create a set of css rules that displays the icon corresponding to the current tinderbox state: statusbarpanel#tinderbox-status { list-style-image: url("chrome://navigator/content/tb-nostatus.png"); } statusbarpanel#tinderbox-status[status="success"] { list-style-image: url("chrome://navigator/content/tb-success.png"); } statusbarpanel#tinderbox-status[status="testfailed"] { list-style-image: url("chrome://navigator/content/tb-testfailed.png"); } statusbarpanel#tinderbox-status[status="busted"] { list-style-image: url("chrome://navigator/content/tb-busted.p...
...ng"); } mozilla can have multiple sets of stylesheets that govern its appearance, and we don't want to have to add these rules to each set (and have our extension break when a new set gets installed), so we'll put this stylesheet in a file called tinderstatus.css in the same directory as navigator.xul and reference it at the top of that file right under the global stylesheet reference: <?xml-stylesheet href="chrome://navigator/skin/" type="text/css"?> <?xml-stylesheet href="chrome://navigator/content/tinderstatus.css" type="text/css"?> our css rules use the list-style-image property to define an image to appear when our status bar panel, identified by its id attribute, has a given value for its status attribute.
contents.rdf - Archive of obsolete content
Archive › Mozilla › Creating a skin for Mozilla › contents.rdf
<chrome:packages> <rdf:seq about="urn:mozilla:skin:myskin/1.0:packages"> <rdf:li resource="urn:mozilla:skin:myskin/1.0:communicator"/> <rdf:li resource="urn:mozilla:skin:myskin/1.0:editor"/> <rdf:li resource="urn:mozilla:skin:myskin/1.0:global"/> <rdf:li resource="urn:mozilla:skin:myskin/1.0:messenger"/> <rdf:li resource="urn:mozilla:skin:myskin/1.0:navigator"/> </rdf:seq> </chrome:packages> </rdf:description> <!-- version information.
...about="urn:mozilla:skin:myskin/1.0:communicator"/> <rdf:description chrome:skinversion="1.0" about="urn:mozilla:skin:myskin/1.0:editor"/> <rdf:description chrome:skinversion="1.0" about="urn:mozilla:skin:myskin/1.0:global"/> <rdf:description chrome:skinversion="1.0" about="urn:mozilla:skin:myskin/1.0:messenger"/> <rdf:description chrome:skinversion="1.0" about="urn:mozilla:skin:myskin/1.0:navigator"/> </rdf:rdf> ...
Security considerations - Archive of obsolete content
Archive › Mozilla › Persona › Security Considerations
essential practices verify assertions on your server when using persona, identity assertions are passed into the onlogin function passed to navigator.id.watch().
... you should always pass the assertion to your server for verification, and only your server should decide to grant the user additional permissions based on the verification result: // inside navigator.id.watch({ ...
Persona - Archive of obsolete content
Archive › Mozilla › Persona
api reference the navigator.id api the browser api.
... the persona website to get persona going, we're hosting three services at https://login.persona.org: a fallback identity provider, an implementation of the navigator.id apis, and a verification service.
List of commands - Archive of obsolete content
Archive › Mozilla › XUL › List of commands
d_scrollpagedown cmd_scrolllineup cmd_scrolllinedown cmd_movepageup cmd_movepagedown cmd_selectpageup cmd_selectpagedown other commands the following list other commands (prefixed by cmd_ or browser:) which have not been categorized here yet (though they are in the alphabetical list below): http://lxr.mozilla.org/seamonkey/sou...baroverlay.xul http://lxr.mozilla.org/seamonkey/sou...t/navigator.js http://lxr.mozilla.org/seamonkey/sou...toroverlay.xul http://lxr.mozilla.org/seamonkey/sou...onaltoolbar.js http://lxr.mozilla.org/seamonkey/sou...rceoverlay.xul http://lxr.mozilla.org/seamonkey/sou...extoverlay.xul http://lxr.mozilla.org/seamonkey/sou...lityoverlay.js http://lxr.mozilla.org/seamonkey/sou...oomoverlay.xul http://lxr.mozilla.org/seamonkey/sou...toroverlay.xul http://lxr...
...tnewsearchfolder cmd_bm_setpersonaltoolbarfolder cmd_bm_sortfolder cmd_bm_sortfolderbyname cmd_close cmd_closeothertabs cmd_closewindow cmd_copy cmd_copyimage cmd_copylink cmd_cut cmd_delete cmd_editpage cmd_findtypelinks cmd_findtypetext cmd_gotoline cmd_handlebackspace cmd_handleshiftbackspace cmd_minimizewindow cmd_neweditor cmd_neweditordraft cmd_neweditortemplate cmd_newnavigator cmd_newnavigatortab cmd_newtabwithtarget cmd_openhelp cmd_paste - paste a selection from the clipboard cmd_printsetup cmd_quit cmd_redo cmd_savepage cmd_scrollpagedown cmd_scrollpageup cmd_selectall cmd_switchdocumentdirection cmd_switchtextdirection cmd_textzoomenlarge cmd_textzoomreduce cmd_textzoomreset cmd_undo cmd_viewcomponentbar cmd_viewlinktoolbar cmd_viewlinktoolbar_f...
SeaMonkey - making custom toolbar (SM ver. 1.x) - Archive of obsolete content
Archive › Mozilla › XUL › Toolbars › Custom toolbar button › SeaMonkey
open the file in seamonkey (for example, by dragging it and dropping it in the navigator window, or by choosing file – open file...
...iption rdf:about="urn:mozilla:package:custombutton" chrome:displayname="custom button" chrome:description="my custom toolbar button" chrome:author="my name" chrome:name="custombutton" chrome:localeversion="1.8" chrome:skinversion="1.5" chrome:extension="true"/> <rdf:seq about="urn:mozilla:overlays"> <!-- browser --> <rdf:li> <rdf:seq about="chrome://navigator/content/navigator.xul"> <rdf:li>chrome://custombutton/content/button.xul</rdf:li> </rdf:seq> </rdf:li> <!-- address book --> <rdf:li> <rdf:seq about="chrome://messenger/content/addressbook/addressbook.xul"> <rdf:li>chrome://custombutton/content/button.xul</rdf:li> </rdf:seq> </rdf:li> <!-- message --> <rdf:li> <rdf:seq about="chrom...
Mozilla release FAQ - Archive of obsolete content
Archive › Mozilla release FAQ
gemini was a previous rendering engine project, renamed nglayout aurora is the navigation center in mozilla and navigator5 seamonkey refers to versions of mozilla based on xpfe and nglayout normandy refers to the mail/news branch of mozilla what are all these acronyms people are using in the newsgroup?
...terface be = back end -- the part of mozilla that does all the behind-the-scenes stuff nspr = netscape portable runtime -- an abstraction layer over the local os gtk = a free gui toolkit native to unix qt = another gui toolkit xp = cross platform xpfe = cross-platform frontend based on nglayout m[number] = milestone release [number] (no longer used) i'm wondering how to do xxx with navigator 3.x...
Building a Theme - Archive of obsolete content
Archive › Themes › Building a Theme
the element itself is of id navigator-toolbox, with no idea.
...search this file for the #navigator-toolbox selector, and add a background: orange; rule to it.
Windows Media in Netscape - Archive of obsolete content
Archive › Windows Media in Netscape
below, some of the salient points are illustrated in a code snippet: if (window.activexobject && navigator.useragent.indexof('windows') != -1) { // ie for windows object instantiation -- use of activexobject } else if(window.geckoactivexobject) { // netscape 7.1 object instantiation --use of geckoactivexobject } else if(navigator.mimetypes) { // plugin architecture, such as in netscape 4x - 7.02 and opera browsers } since ie for mac also exposes window.activexobject it is wise to determine if th...
...here is a code snippet that shows this: var player; try { if (window.activexobject) { player = new activexobject("mediaplayer.mediaplayer.1"); } else if (window.geckoactivexobject) { player = new geckoactivexobject("mediaplayer.mediaplayer.1"); } else { // plugin code using navigator.mimetypes player = navigator.mimetypes["application/x-mplayer2"].enabledplugin; } } catch(e) { // handle error -- no wmp control // download: http://www.microsoft.com/windows/windowsmedia/download/default.asp } if (player) { // windows media player control exists } currently, dynamically writing out markup using document.write after using detection mechanisms won't work owing to a...
Archive of obsolete content
Archive
identitymanager the identitymanager of the browserid protocol exposes the browserid api, via navigator.id.
... navigator.id the browserid protocol defines a new id property on the window.navigator object, through which it exposes the browserid api, that is the identitymanager intreface.
Plug-in Development Overview - Gecko Plugin API Reference
Gecko Plugin API Reference › Plug-in Development Overview
this information will then appear in the navigator.mimetypes dom object.
... npp_getvalue is called after the plug-in is initialized to get the scripting interface while np_getvalue is called during initialization to retrieve the plug-in's name and description, which will appear in the navigator.plugins dom object which is used to populate about:plugins.
Effective connection type - MDN Web Docs Glossary: Definitions of Web-related terms
Glossary › Effective connection type
effectivetype is a property of the network information api, exposed to javascript via the navigator.connection object.
... to see your effective connection type, open the console of the developer tools of a supporting browser and enter the following: navigator.connection.effectivetype; see also: network information api networkinformation networkinformation.effectivetype ...
Index - MDN Web Docs Glossary: Definitions of Web-related terms
Glossary › Index
126 effective connection type glossary, navigator, network information api, networkinformation, performance, reference, web performance, connect, effective connection type, effectivetype effective connection type (ect) refers to the measured network performance, returning a cellular connection type, like 3g, even if the actual connection is tethered broadband or wifi, based on the time between the browser requesting a page and effective ty...
... 285 netscape navigator browser, glossary, navigation, netscape, netscape navigator netscape navigator or netscape was a leading browser in the 1990s.
User agent - MDN Web Docs Glossary: Definitions of Web-related terms
Glossary › user agent
the user agent string can be accessed with javascript on the client side using the navigator.useragent property.
... learn more general knowledge user agent on wikipedia technical reference navigator.useragent browser detection using the user agent rfc 2616: 14.43: the user-agent header ...
Client-side storage - Learn web development
Learn › JavaScript › Client-side web APIs › Client-side storage
first we do a feature detection test to see if the serviceworker member is available in the navigator object.
... // register service worker to control making site work offline if('serviceworker' in navigator) { navigator.serviceworker .register('/learning-area/javascript/apis/client-side-storage/cache-sw/video-store-offline/sw.js') .then(function() { console.log('service worker registered'); }); } note: the given path to the sw.js file is relative to the site origin, not the javascript file that contains the code.
Manipulating documents - Learn web development
Learn › JavaScript › Client-side web APIs › Manipulating documents
the navigator represents the state and identity of the browser (i.e.
...in javascript, this is represented by the navigator object.
CustomizableUI.jsm
Mozilla › JavaScript code modules › CustomizableUI.jsm
customizableui.createwidget({ id: 'navigator-throbber', //id in cui.jsm // should match id of that in dom (line #11) type: 'custom', defaultarea: customizableui.area_navbar, onbuild: function(adocument) { var toolbaritem = adocument.createelementns('http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul', 'toolbaritem'); var image = adocument.createelementns('http://www.mozilla.org/keymaster/gatekeeper/the...
...re.is.only.xul', 'image'); image.setattribute('src', 'chrome://branding/content/icon16.png'); var props = { id: 'navigator-throbber', //id in dom // should match id of that in cui.jsm (line #2) title: 'activity indicator', align: 'center', pack: 'center', mousethrough: 'always', removable: 'true', sdkstylewidget: 'true', overflows: false }; for (var p in props) { toolbaritem.setattribute(p, props[p]); } toolbaritem.appendchild(image); return toolbaritem; } }); when you want to remove this widget run this code: customizableui.destroywidget('navigator-throbber-id-within-customizableui-object'); custom type - involved the browser...
Localization Use Cases
Mozilla › Projects › L20n › Localization Use Cases
0 : 1; var sizeinfo = filesizeformatter.getreadablefilesize(size, fixeddigits); var _ = navigator.mozl10n.get; element.textcontent = _(l10nid, { size: sizeinfo.size, unit: _('byteunit-' + sizeinfo.unit) }); } the function is used like so: // application storage updateappfreespace: function storage_updateappfreespace() { var self = this; this.getfreespace(this.appstorage, function(freespace) { devicestoragehelper.showformatedsize(self.appstoragedesc, 'availablesize...
... you'll notice that devicestoragehelper.showformatedsize passes a localized name of the unit to availablesize: function showformatedsize(element, l10nid, size) { // … var _ = navigator.mozl10n.get; element.textcontent = _(l10nid, { size: sizeinfo.size, unit: _('byteunit-' + sizeinfo.unit) }); } problem definition even though there's no need to localize the units in english at all, we still need to do it, because in other languages we might need to use localized names.
The Publicity Stream API
Mozilla › Tech › The Publicity Stream API
[is this still doable?] the javascript library should be included from: https://myapps.mozillalabs.com/jsapi/publicity.js all apis related to open web applications are accessed under the navigator.apps object.
... publicity stream api (navigator.apps.publicity.*) the publicity api is exposed as properties on the navigator.apps.publicity object.
Building the WebLock UI
Mozilla › Tech › XPCOM › Guide › Creating components › Building the WebLock UI
here is that xul file in its entirety: the weblock overlay <?xml version="1.0"?> <?xml-stylesheet href="chrome://navigator/content/weblock.css" type="text/css"?> <overlay id="weblockoverlay" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> <script type="application/javascript" src="chrome://weblock/content/weblock.js"/> <statusbar id="status-bar"> <statusbarpanel class="statusbarpanel-iconic" id="weblock-status" insertbefore="...
...this id is the same one used by the <statusbar/> in navigator.xul, which means that the overlay mechanism will merge the new ui here (i.e., the weblock statusbarpanel) and the ui already defined within that browser <statusbar/> at runtime.
Index
Mozilla › Tech › XPCOM › Index
473 nsidomdesktopnotificationcenter interfaces, interfaces:scriptable, xpcom, xpcom interface reference the nsidomdesktopnotificationcenter interface implements the dom navigator.moznotification interface.
... 507 nsidomnavigatordesktopnotification interfaces, interfaces:scriptable, xpcom, xpcom interface reference property that extends the navigator object.
nsIDOMMozNetworkStatsManager
Mozilla › Tech › XPCOM › Reference › Interface › nsIDOMMozNetworkStatsManager
to create an instance, use: var networkstatsmanager = components.classes["@mozilla.org/networkstatsmanager;1"] .createinstance(components.interfaces.nsidomnetworkstatsmanager); furthermore, the networkstatsmanager is published through a moznetworkstats child object within the navigator object.
...you can test for the presence of the service as follows, for example: if ("moznetworkstats" in navigator) { /* networkstats is available */ } else { alert("i'm sorry, but networkstats services are not supported."); } method overview nsidomdomrequest getsamples(in nsisupports network, in jsval start, in jsval end, [optional] in jsval options /* networkstatsgetoptions */); nsidomdomrequest addalarm(in nsisupports network, in long threshold, [optional] in jsval options /* networkstatsalarmoptions */); nsidomdomrequest getallalarms([optional] in nsi...
nsIPropertyBag
Mozilla › Tech › XPCOM › Reference › Interface › nsIPropertyBag
the window scope is not always accessible so the window.navigator cannot be accessed.
... goodies obtained from window.navigator are: appcodename:"mozilla" appname:"netscape" appversion:"5.0 (windows)" battery:batterymanager buildid:"20140529161749" cookieenabled:true donottrack:"yes" geolocation:geolocation language:"en-us" mimetypes:mimetypearray mozalarms:null mozapps:xpcwrappednative_nohelper mozcameras:cameramanager mozconnection:mozconnection mozcontacts:contactmanager mozid:null mozkeyboard:xpcwrappednative_nohelper mozpay:null mozpermissionsettings:null mozphonenumberservice:phonenumberservice mozpower:mozpowermanager moztcpsocket:null online:true oscpu:"windows nt 5.1" platform:"win32" plugins:pluginarray product:"gecko" productsub:"20100101" useragent:"mozilla/5.0 (windows nt 5.1; rv:30.0) gecko/20100101 firefox/30.0" vendor:"" vendorsub:"" __proto__:navigatorprototype from...
nsIWebContentHandlerRegistrar
Mozilla › Tech › XPCOM › Reference › Interface › nsIWebContentHandlerRegistrar
ent-handler-registrar;1"] .getservice(ci.nsiwebcontenthandlerregistrar); var allowregisterfromdifferenthost = services.prefs.getboolpref('gecko.handlerservice.allowregisterfromdifferenthost'); if (!allowregisterfromdifferenthost) { services.prefs.setboolpref('gecko.handlerservice.allowregisterfromdifferenthost', true); } var htmlcontentwindow = services.wm.getmostrecentwindow('navigator:browser'); //because we set the preference to true above, we need any window that has a browser, just pass the domwindow and the registerprotocolhandler will get the contentwindow from it nsiwchr.registerprotocolhandler("mailto", "http://mail.live.com/secure/start?action=compose&to=%s", "outlook.com live mail", htmlcontentwindow); if (!allowregisterfromdifferenthost) { //it this variable is f...
...to take from: http://mxr.mozilla.org/mozilla-release/source/browser/components/feeds/src/webcontentconverter.js#372 and http://stackoverflow.com/questions/24900655/use-registerprotocolhandler-without-contentwindow place holder see also nsiwebcontentsonverterservice (under construction: page doesnt exist yet) registerprotocolhandler from non-privelaged scope web api interfaces > navigator.registercontenthandler() web api interfaces > navigator.registerprotocolhandler() ...
nsIWindowMediator
Mozilla › Tech › XPCOM › Reference › Interface › nsIWindowMediator
browser windows have a window type of navigator:browser.
...if, for example, you wish to enumerate all browser windows, you would specify "navigator:browser".
Plug-in Development Overview - Plugins
Plugins › Guide › Plug-in Development Overview
this information will then appear in the navigator.mimetypes dom object.
... npp_getvalue is called after the plug-in is initialized to get the scripting interface while np_getvalue is called during initialization to retrieve the plug-in's name and description, which will appear in the navigator.plugins dom object which is used to populate about:plugins.
AudioContext.createMediaStreamSource() - Web APIs
Web › API › AudioContext › createMediaStreamSource
example in this example, we grab a media (audio + video) stream from navigator.getusermedia, feed the media into a <video> element to play then mute the audio, but then also feed the audio into a mediastreamaudiosourcenode.
... var pre = document.queryselector('pre'); var video = document.queryselector('video'); var myscript = document.queryselector('script'); var range = document.queryselector('input'); // getusermedia block - grab stream // put it into a mediastreamaudiosourcenode // also output the visuals into a video element if (navigator.mediadevices) { console.log('getusermedia supported.'); navigator.mediadevices.getusermedia ({audio: true, video: true}) .then(function(stream) { video.srcobject = stream; video.onloadedmetadata = function(e) { video.play(); video.muted = true; }; // create a mediastreamaudiosourcenode // feed the htmlmediaelement into i...
AuthenticatorAssertionResponse.authenticatorData - Web APIs
Web › API › AuthenticatorAssertionResponse › authenticatorData
this is only present during a navigator.credentials.create() call.
... examples var options = { challenge: new uint8array(26), // will be another value, provided by the relying party server timeout: 60000 }; navigator.credentials.get({ publickey: options }) .then(function (assertionpkcred) { var authenticatordata = assertionpkcred.response.authenticatordata; // maybe try to convert the authenticatordata to see what's inside // send response and client extensions to the server so that it can // go on with the authentication }).catch(function (err) { console.error(err); }); specificatio...
AuthenticatorAssertionResponse.signature - Web APIs
Web › API › AuthenticatorAssertionResponse › signature
note: an authenticatorassertionresponse instance is available on publickeycredential.response after calling navigator.credentials.get().
... examples var options = { challenge: new uint8array(26), // will be another value, provided by the relying party server timeout: 60000 }; navigator.credentials.get({ publickey: options }) .then(function (assertionpkcred) { var signature = assertionpkcred.response.signature; // send response and client extensions to the server so that it can // go on with the authentication }).catch(function (err) { console.error(err); }); specifications specification status comment web authentication: an api...
AuthenticatorAssertionResponse.userHandle - Web APIs
Web › API › AuthenticatorAssertionResponse › userHandle
note: an authenticatorassertionresponse instance is available on publickeycredential.response after calling navigator.credentials.get().
...username, e-mail, phone number, etc.) examples var options = { challenge: new uint8array(26), // will be another value, provided by the relying party server timeout: 60000 }; navigator.credentials.get({ publickey: options }) .then(function (assertionpkcred) { var userhandle = assertionpkcred.response.userhandle; // send response and client extensions to the server so that it can // go on with the authentication }).catch(function (err) { console.error(err); }); specifications specification status comment web authentication: an a...
AuthenticatorAssertionResponse - Web APIs
Web › API › AuthenticatorAssertionResponse
the assertion signature is created with the private key of keypair that was created during the navigator.credentials.create() call and verified using the public key of that same keypair.
... examples var options = { challenge: new uint8array([/* bytes sent from the server */]) }; navigator.credentials.get({ "publickey": options }) .then(function (credentialinfoassertion) { var assertionresponse = credentialinfoassertion.response; // do something specific with the response // send assertion response back to the server // to proceed with the control of the credential }).catch(function (err) { console.error(err); }); specifications specification status comment web authentication: an api for accessing public key credentials level 1the definition of 'authenticatorassertionresponse interface'...
AuthenticatorAttestationResponse.getTransports() - Web APIs
Web › API › AuthenticatorAttestationResponse › getTransports
note: an authenticatorattestationresponse instance is available on publickeycredential.response after calling navigator.credentials.create().
... examples var publickey = { challenge: /* from the server */, rp: { name: "example corp", id : "login.example.com" }, user: { id: new uint8array(16), name: "jdoe@example.com", displayname: "john doe" }, pubkeycredparams: [ { type: "public-key", alg: -7 } ] }; navigator.credentials.create({ publickey }) .then(function (newcredentialinfo) { var transports = newcredentialinfo.response.gettransports(); console.table(transports); // may be something like ["internal", "nfc", "usb"] }).catch(function (err) { console.error(err); }); specifications specification status comment web authentication: an api for accessing publ...
AuthenticatorResponse - Web APIs
Web › API › AuthenticatorResponse
examples getting an authenticatorassertionresponse var options = { challenge: new uint8array([/* bytes sent from the server */]) }; navigator.credentials.get({ "publickey": options }) .then(function (credentialinfoassertion) { var assertionresponse = credentialinfoassertion.response; // send assertion response back to the server // to proceed with the control of the credential }).catch(function (err) { console.error(err); }); getting an authenticatorattestationresponse var publickey = { challenge: /* from the...
... server */, rp: { name: "example corp", id : "login.example.com" }, user: { id: new uint8array(16), name: "jdoe@example.com", displayname: "john doe" }, pubkeycredparams: [ { type: "public-key", alg: -7 } ] }; navigator.credentials.create({ publickey }) .then(function (newcredentialinfo) { var attestationresponse = newcredentialinfo.response; }).catch(function (err) { console.error(err); }); specifications specification status comment web authentication: an api for accessing public key credentials level 1the definition of 'authenticatorresponse interface' in that specification.
BatteryManager.onlevelchange - Web APIs
Web › API › BatteryManager › onlevelchange
syntax navigator.battery.onlevelchange = funcref where battery is a batterymanager object, and funcref is a function to be called when the levelchange event occurs.
... example html <div id="level">(battery level unknown)</div> <div id="statebaterry">(charging state unknown)</div> javascript navigator.getbattery().then(function(battery) { battery.onlevelchange = function(){ document.queryselector('#level').textcontent = battery.level; if(battery.charging) { document.queryselector('#statebaterry').textcontent = "charging time: " + (battery.chargingtime / 60); } else { document.queryselector('#statebaterry').textcontent = "discharging time: " + (battery.dischargingtime / 60); } }; }); specifications specification status comment battery status api candidate recommendation initial definition ...
Battery Status API - Web APIs
Web › API › Battery Status API
the battery status api extends window.navigator with a navigator.getbattery() method returning a battery promise, which is resolved in a batterymanager object providing also some new events you can handle to monitor the battery status.
... navigator.getbattery().then(function(battery) { function updateallbatteryinfo(){ updatechargeinfo(); updatelevelinfo(); updatecharginginfo(); updatedischarginginfo(); } updateallbatteryinfo(); battery.addeventlistener('chargingchange', function(){ updatechargeinfo(); }); function updatechargeinfo(){ console.log("battery charging?
Beacon API - Web APIs
Web › API › Beacon API
global context the beacon api's navigator.sendbeacon() method is used to send a beacon of data to the server in the global browsing context.
... worker context the beacon api's navigator.sendbeacon() method is used to send a beacon of data to the server from the worker global scope.
Bluetooth.getAvailability() - Web APIs
Web › API › Bluetooth › getAvailability
note: user might not allow use of web bluetooth api, even if getavailability() returned true (navigator.bluetooth.requestdevice() might not resolve with a bluetoothdevice).
... examples the following snippet prints out a message in the console specifying wheter or not bluetooth is supported: navigator.bluetooth.getavailability().then(available => { if (available) console.log("this device supports bluetooth!"); else console.log("doh!
BluetoothRemoteGATTCharacteristic - Web APIs
Web › API › BluetoothRemoteGATTCharacteristic
bluetoothremotegattcharacteristic.startnotifications() returns a promise when navigator.bluetooth is added to the active notification context.
... bluetoothremotegattcharacteristic.stopnotifications() returns a promise when navigator.bluetooth is removed from the active notification context.
Client.postMessage() - Web APIs
Web › API › Client › postMessage
the message is received in the "message" event on navigator.serviceworker.
... client.postmessage({ msg: "hey i just got a fetch from you!", url: event.request.url }); }()); }); receiving that message: navigator.serviceworker.addeventlistener('message', event => { console.log(event.data.msg, event.data.url); }); specifications specification status comment service workersthe definition of 'postmessage()' in that specification.
Clipboard.readText() - Web APIs
Web › API › Clipboard › readText
syntax var promise = navigator.clipboard.readtext() parameters none.
... navigator.clipboard.readtext().then( cliptext => document.getelementbyid("outbox").innertext = cliptext); specifications specification status comment clipboard api and eventsthe definition of 'readtext()' in that specification.
Clipboard.writeText() - Web APIs
Web › API › Clipboard › writeText
syntax var promise = navigator.clipboard.writetext(newcliptext) parameters newcliptext the domstring to be written to the clipboard.
... navigator.clipboard.writetext("<empty clipboard>").then(function() { /* clipboard successfully set */ }, function() { /* clipboard write failed */ }); specifications specification status comment clipboard api and eventsthe definition of 'writetext()' in that specification.
ClipboardItem - Web APIs
Web › API › ClipboardItem
async function writeclipimg() { try { const imgurl = '/myimage.png'; const data = await fetch(imgurl); const blob = await data.blob(); await navigator.clipboard.write([ new clipboarditem({ [blob.type]: blob }) ]); console.log('fetched image copied.'); } catch(err) { console.error(err.name, err.message); } } reading from the clipboard here we're returning all items on the clipboard via the clipboard.read() method.
... async function getclipboardcontents() { try { const clipboarditems = await navigator.clipboard.read(); for (const clipboarditem of clipboarditems) { for (const type of clipboarditem.types) { const blob = await clipboarditem.gettype(type); // we can now use blob here } } } catch (err) { console.error(err.name, err.message); } } specifications specification status comment clipboard api and eventsthe definition of 'clipboarditem' in that specification.
DedicatedWorkerGlobalScope - Web APIs
Web › API › DedicatedWorkerGlobalScope
workerglobalscope.navigator read only returns the workernavigator associated with the worker.
... workernavigator is a specific navigator object, mostly a subset of the navigator for browsing scopes, but adapted to workers.
Gamepad.buttons - Web APIs
Web › API › Gamepad › buttons
syntax readonly attribute gamepadbutton[] buttons; example the following code is taken from my gamepad api button demo (you can view the demo live, and find the source code on github.) note the code fork — in chrome navigator.getgamepads needs a webkit prefix and the button values are stores as an array of double values, whereas in firefox navigator.getgamepads doesn't need a prefix, and the button values are stored as an array of gamepadbutton objects; it is the gamepadbutton.value or gamepadbutton.pressed properties of these we need to access, depending on what type of buttons they are.
... function gameloop() { if(navigator.webkitgetgamepads) { var gp = navigator.webkitgetgamepads()[0]; if(gp.buttons[0] == 1) { b--; } else if(gp.buttons[1] == 1) { a++; } else if(gp.buttons[2] == 1) { b++; } else if(gp.buttons[3] == 1) { a--; } } else { var gp = navigator.getgamepads()[0]; if(gp.buttons[0].value > 0 || gp.buttons[0].pressed == true) { b--; } else if(gp.buttons[1].value > 0 || gp.buttons[1].pressed == true) { a++; } else if(gp.buttons[2].value > 0 || gp.buttons[2].pressed == true) { b++; } else if(gp.buttons[3].value > 0 || gp.buttons[3].pressed == true) { a--; } } ball.style.left = a*2 + "px"; ball.style.top = b*2 + "px"; va...
GamepadButton - Web APIs
Web › API › GamepadButton
example the following code is taken from my gamepad api button demo (you can view the demo live, and find the source code on github.) note the code fork — in chrome navigator.getgamepads needs a webkit prefix and the button values are stored as an array of double values, whereas in firefox navigator.getgamepads doesn't need a prefix, and the button values are stored as an array of gamepadbutton objects; it is the gamepadbutton.value or gamepadbutton.pressed properties of these we need to access, depending on what type of buttons they are.
... function gameloop() { if(navigator.webkitgetgamepads) { var gp = navigator.webkitgetgamepads()[0]; if(gp.buttons[0] == 1) { b--; } else if(gp.buttons[1] == 1) { a++; } else if(gp.buttons[2] == 1) { b++; } else if(gp.buttons[3] == 1) { a--; } } else { var gp = navigator.getgamepads()[0]; if(gp.buttons[0].value > 0 || gp.buttons[0].pressed == true) { b--; } else if(gp.buttons[1].value > 0 || gp.buttons[1].pressed == true) { a++; } else if(gp.buttons[2].value > 0 || gp.buttons[2].pressed == true) { b++; } else if(gp.buttons[3].value > 0 || gp.buttons[3].pressed == true) { a--; } } ball.style.left = a*2 + "px"; ball.style.top = b*2 + "px"; va...
Geolocation.clearWatch() - Web APIs
Web › API › Geolocation › clearWatch
syntax navigator.geolocation.clearwatch(id); parameters id the id number returned by the geolocation.watchposition() method when installing the handler you wish to remove.
... example var id, target, option; function success(pos) { var crd = pos.coords; if (target.latitude === crd.latitude && target.longitude === crd.longitude) { console.log('congratulation, you reach the target'); navigator.geolocation.clearwatch(id); } }; function error(err) { console.warn('error(' + err.code + '): ' + err.message); }; target = { latitude : 0, longitude: 0, } options = { enablehighaccuracy: false, timeout: 5000, maximumage: 0 }; id = navigator.geolocation.watchposition(success, error, options); specifications specification status comment geolocation api recommendation initial specification.
Geolocation.getCurrentPosition() - Web APIs
Web › API › Geolocation › getCurrentPosition
syntax navigator.geolocation.getcurrentposition(success[, error[, [options]]) parameters success a callback function that takes a geolocationposition object as its sole input parameter.
...r options = { enablehighaccuracy: true, timeout: 5000, maximumage: 0 }; function success(pos) { var crd = pos.coords; console.log('your current position is:'); console.log(`latitude : ${crd.latitude}`); console.log(`longitude: ${crd.longitude}`); console.log(`more or less ${crd.accuracy} meters.`); } function error(err) { console.warn(`error(${err.code}): ${err.message}`); } navigator.geolocation.getcurrentposition(success, error, options); specifications specification status comment geolocation api recommendation initial specification.
Geolocation.watchPosition() - Web APIs
Web › API › Geolocation › watchPosition
syntax navigator.geolocation.watchposition(success[, error[, options]]) parameters success a callback function that takes a geolocationposition object as an input parameter.
... examples var id, target, options; function success(pos) { var crd = pos.coords; if (target.latitude === crd.latitude && target.longitude === crd.longitude) { console.log('congratulations, you reached the target'); navigator.geolocation.clearwatch(id); } } function error(err) { console.warn('error(' + err.code + '): ' + err.message); } target = { latitude : 0, longitude: 0 }; options = { enablehighaccuracy: false, timeout: 5000, maximumage: 0 }; id = navigator.geolocation.watchposition(success, error, options); specifications specification status comment geolocation ap...
HTMLMediaElement.srcObject - Web APIs
Web › API › HTMLMediaElement › srcObject
const mediastream = await navigator.mediadevices.getusermedia({video: true}); const video = document.createelement('video'); video.srcobject = mediastream; in this example, a new mediasource is assigned to a newly-created <video> element.
... const mediastream = await navigator.mediadevices.getusermedia({video: true}); const video = document.createelement('video'); if ('srcobject' in video) { video.srcobject = mediastream; } else { // avoid using this in new browsers, as it is going away.
The HTML DOM API - Web APIs
Web › API › HTML DOM API
barprop navigator window deprecated web app and browser integration interfaces external obsolete web app and browser integration interfaces applicationcache plugin pluginarray form support interfaces these interfaces provide structure and functionality required by the elements used to create and manage forms, including the <form> and <input> elements.
... broadcastchannel dedicatedworkerglobalscope messagechannel messageevent messageport sharedworker sharedworkerglobalscope worker workerglobalscope workerlocation workernavigator websocket interfaces these interfaces, defined by the html specification, are used by the websockets_api.
Keyboard.lock() - Web APIs
Web › API › Keyboard › lock
navigator.keyboard.lock(); capturing specific keys the following example captures the "w", "a", "s", and "d" keys.
... navigator.keyboard.lock(["keyw", "keya", "keys", "keyd"]); specifications specification status comment keyboard lockthe definition of 'lock()' in that specification.
Locks.mode - Web APIs
Web › API › Lock › mode
lockmanager is the object returned by navigator.locks.
... // should show "exclusive" (the default) navigator.locks.request("my_resource", show_lock_properties); // should show "exclusive" navigator.locks.request("my_resource", {mode: "exclusive"}, show_lock_properties); // should show "shared" navigator.locks.request("my_resource", {mode: "shared"}, show_lock_properties); function show_lock_properties(lock) { console.log(`the lock name is: ${lock.name}`); console.log(`the lock mode is: ${lock.mode}`); } specifications specification status comment web locks apithe definition of 'mode' in that specification.
Locks.name - Web APIs
Web › API › Lock › name
lockmanager is the object returned by navigator.locks.
... navigator.locks.request("net_db_sync", show_lock_properties); function show_lock_properties(lock) { console.log(`the lock name is: ${lock.name}`); console.log(`the lock mode is: ${lock.mode}`); } specifications specification status comment web locks apithe definition of 'name' in that specification.
Lock - Web APIs
Web › API › Lock
lockmanager is the object returned by navigator.locks.
... navigator.locks.request("net_db_sync", show_lock_properties); navigator.locks.request("another_lock", {mode: "shared"}, show_lock_properties); function show_lock_properties(lock) { console.log(`the lock name is: ${lock.name}`); console.log(`the lock mode is: ${lock.mode}`); } specifications specification status comment web locks apithe definition of 'lock' in that specification.
MediaDevices.getDisplayMedia() - Web APIs
Web › API › MediaDevices › getDisplayMedia
syntax var promise = navigator.mediadevices.getdisplaymedia(constraints); parameters constraints optional an optional mediastreamconstraints object specifying requirements for the returned mediastream.
... async function startcapture(displaymediaoptions) { let capturestream = null; try { capturestream = await navigator.mediadevices.getdisplaymedia(displaymediaoptions); } catch(err) { console.error("error: " + err); } return capturestream; } this uses await to asynchronously wait for getdisplaymedia() to resolve with a mediastream which contains the display contents as requested by the specified options.
MediaDevices.getSupportedConstraints() - Web APIs
Web › API › MediaDevices › getSupportedConstraints
syntax var supportedconstraints = navigator.mediadevices.getsupportedconstraints(); parameters none.
... html <p>the following media constraints are supported by your browser:</p> <ul id="constraintlist"> </ul> css body { font: 15px arial, sans-serif; } javascript let constraintlist = document.getelementbyid("constraintlist"); let supportedconstraints = navigator.mediadevices.getsupportedconstraints(); for (let constraint in supportedconstraints) { if (supportedconstraints.hasownproperty(constraint)) { let elem = document.createelement("li"); elem.innerhtml = "<code>" + constraint + "</code>"; constraintlist.appendchild(elem); } } result specifications specification status comment media capture and streamsthe...
MediaMetadata.MediaMetadata() - Web APIs
Web › API › MediaMetadata › MediaMetadata
example the following example creates a new media session and assigns action handlers to it: if ('mediasession' in navigator){ navigator.mediasession.metadata = new mediametadata({ title: "podcast episode title", artist: "podcast host", album: "podcast name", artwork: [{src: "podcast.jpg"}] }); navigator.mediasession.setactionhandler('play', function() {}); navigator.mediasession.setactionhandler('pause', function() {}); navigator.mediasession.setactionhandler('seekbackward', function() {}); ...
... navigator.mediasession.setactionhandler('seekforward', function() {}); navigator.mediasession.setactionhandler('previoustrack', function() {}); navigator.mediasession.setactionhandler('nexttrack', function() {}); } specifications specification status comment media session standardthe definition of 'mediametadata()' in that specification.
MediaPositionState.position - Web APIs
Web › API › MediaPositionState › position
for example, a browser might use this information along with the position property and the navigator.mediasession.playbackstate, as well as the session's metadata to provide an integrated common user interface showing the currently playing media as well as standard pause, play, forward, reverse, and other controls.
... let positioninterval = window.setinterval(() => { if (mymedia.isplaying) { navigator.mediasession.setpositionstate({ duration: mymedia.trackdurationinseconds, playbackrate: mymedia.playbackrate, position: mymedia.trackplaypositioninseconds }); } else { window.clearinterval(positioninterval); } }, 1000); specifications specification status comment media session standardthe definition of 'mediapositionstate.position' in th...
MediaRecorder() - Web APIs
Web › API › MediaRecorder › MediaRecorder
this source media can come from a stream created using navigator.mediadevices.getusermedia() or from an <audio>, <video> or <canvas> element.
...if (navigator.mediadevices.getusermedia) { var constraints = { audio: true, video: true }; var chunks = []; var onsuccess = function(stream) { var options = { audiobitspersecond : 128000, videobitspersecond : 2500000, mimetype : 'video/mp4' } var mediarecorder = new mediarecorder(stream,options); m = mediarecorder; ...
MediaSession.metadata - Web APIs
Web › API › MediaSession › metadata
syntax var mediametadata = navigator.mediasession.metadata; navigator.mediasession.metadata = mediametadata; value an instance of mediametadata containing information about the media currently being played.
... example the following example creates a new media session and assigns action handlers to it: if ('mediasession' in navigator){ navigator.mediasession.metadata = new mediametadata({ title: "podcast episode title", artist: "podcast host", album: "podcast name", artwork: [{src: "podcast.jpg"}] }); navigator.mediasession.setactionhandler('play', function() {}); navigator.mediasession.setactionhandler('pause', function() {}); navigator.mediasession.setactionhandler('seekbackward', function() {}); navigator.mediasession.setactionhandler('seekforward', function() {}); navigator.mediasession.setactionhandler('previoustrack', function() {}); navigator.mediasession.setactionhandler('nexttrack', function() {}); } specifications specification status comment ...
MediaSession - Web APIs
Web › API › MediaSession
examples the following example creates a new media session and assigns action handlers to it: if ('mediasession' in navigator){ navigator.mediasession.metadata = new mediametadata({ title: "podcast episode title", artist: "podcast host", album: "podcast name", artwork: [{src: "podcast.jpg"}] }); navigator.mediasession.setactionhandler('play', function() {}); navigator.mediasession.setactionhandler('pause', function() {}); navigator.mediasession.setactionhandler('seekbackward', function() {}); ...
... navigator.mediasession.setactionhandler('seekforward', function() {}); navigator.mediasession.setactionhandler('previoustrack', function() {}); navigator.mediasession.setactionhandler('nexttrack', function() {}); } the following example sets up event handlers for pausing and playing: var audio = document.queryselector("#player"); audio.src = "song.mp3"; navigator.mediasession.setactionhandler('play', play); navigator.mediasession.setactionhandler('pause', pause); function play() { audio.play(); navigator.mediasession.playbackstate = "playing"; } function pause() { audio.pause(); navigator.mediasession.playbackstate = "paused"; } specifications specification status comment media session standardthe definition of 'mediasession' in that specification.
MediaStreamAudioSourceNode - Web APIs
Web › API › MediaStreamAudioSourceNode
example in this example, we grab a media (audio + video) stream from navigator.getusermedia, feed the media into a <video> element to play then mute the audio, but then also feed the audio into a mediastreamaudiosourcenode.
... var pre = document.queryselector('pre'); var video = document.queryselector('video'); var myscript = document.queryselector('script'); var range = document.queryselector('input'); // getusermedia block - grab stream // put it into a mediastreamaudiosourcenode // also output the visuals into a video element if (navigator.mediadevices) { console.log('getusermedia supported.'); navigator.mediadevices.getusermedia ({audio: true, video: true}) .then(function(stream) { video.srcobject = stream; video.onloadedmetadata = function(e) { video.play(); video.muted = true; }; // create a mediastreamaudiosourcenode // feed the htmlmediaelement into i...
MediaStreamConstraints.audio - Web APIs
Web › API › MediaStreamConstraints › audio
font-size: 16px; text-align: center; padding-top: 2px; padding-bottom: 4px; color: white; background-color: darkgreen; } javascript content let audioelement = document.getelementbyid("audio"); let logelement = document.getelementbyid("log"); function log(msg) { logelement.innerhtml += msg + "<br>"; } document.getelementbyid("startbutton").addeventlistener("click", function() { navigator.mediadevices.getusermedia({ audio: true }).then(stream => audioelement.srcobject = stream) .catch(err => log(err.name + ": " + err.message)); }, false); here we see an event handler for a click event which uses getusermedia() to obtain an audio-only stream with no specific constraints, then attaches the resulting stream to an <audio> element once the stream is returned.
... font-size: 16px; text-align: center; padding-top: 2px; padding-bottom: 4px; color: white; background-color: darkgreen; } javascript content let audioelement = document.getelementbyid("audio"); let logelement = document.getelementbyid("log"); function log(msg) { logelement.innerhtml += msg + "<br>"; } document.getelementbyid("startbutton").addeventlistener("click", function() { navigator.mediadevices.getusermedia({ audio: { samplesize: 8, echocancellation: true } }).then(stream => audioelement.srcobject = stream) .catch(err => log(err.name + ": " + err.message)); }, false); here we see an event handler for a click event which calls getusermedia(), specifying a set of audio constraints requesting that echo cancellation be enabled and that, if possible, t...
MediaStreamConstraints.video - Web APIs
Web › API › MediaStreamConstraints › video
font-size: 16px; text-align: center; padding-top: 2px; padding-bottom: 4px; color: white; background-color: darkgreen; } javascript content let videoelement = document.getelementbyid("video"); let logelement = document.getelementbyid("log"); function log(msg) { logelement.innerhtml += msg + "<br>"; } document.getelementbyid("startbutton").addeventlistener("click", function() { navigator.mediadevices.getusermedia({ video: true }).then(stream => videoelement.srcobject = stream) .catch(err => log(err.name + ": " + err.message)); }, false); here we see an event handler for a click event which uses getusermedia() to obtain a video-only stream with no specific constraints, then attaches the resulting stream to a <video> element once the stream is returned.
... font-size: 16px; text-align: center; padding-top: 2px; padding-bottom: 4px; color: white; background-color: darkgreen; } javascript content let videoelement = document.getelementbyid("video"); let logelement = document.getelementbyid("log"); function log(msg) { logelement.innerhtml += msg + "<br>"; } document.getelementbyid("startbutton").addeventlistener("click", function() { navigator.mediadevices.getusermedia({ video: { width: 160, height: 120, framerate: 15 } }).then(stream => videoelement.srcobject = stream) .catch(err => log(err.name + ": " + err.message)); }, false); here we see an event handler for a click event which calls getusermedia(), specifying a set of video constraints that indicate a preference for a video track whose d...
MediaStreamTrackAudioSourceNode - Web APIs
Web › API › MediaStreamTrackAudioSourceNode
example in this example, we grab a media (audio + video) stream from navigator.getusermedia, feed the media into a <video> element to play then mute the audio, but then also feed the audio into a mediastreamaudiosourcenode.
... var pre = document.queryselector('pre'); var video = document.queryselector('video'); var myscript = document.queryselector('script'); var range = document.queryselector('input'); // getusermedia block - grab stream // put it into a mediastreamaudiosourcenode // also output the visuals into a video element if (navigator.mediadevices) { console.log('getusermedia supported.'); navigator.mediadevices.getusermedia ({audio: true, video: true}) .then(function(stream) { video.srcobject = stream; video.onloadedmetadata = function(e) { video.play(); video.muted = true; }; // create a mediastreamaudiosourcenode // feed the htmlmediaelement into i...
Using the MediaStream Recording API - Web APIs
Web › API › MediaStream Recording API › Using the MediaStream Recording API
when used with navigator.mediadevices.getusermedia(), it provides an easy way to record from the user's input devices and instantly use the result in web apps.
... we'll declare some variables for the record and stop buttons, and the <article> that will contain the generated audio players: const record = document.queryselector('.record'); const stop = document.queryselector('.stop'); const soundclips = document.queryselector('.sound-clips'); finally for this section, we set up the basic getusermedia structure: if (navigator.mediadevices && navigator.mediadevices.getusermedia) { console.log('getusermedia supported.'); navigator.mediadevices.getusermedia ( // constraints - only audio needed for this app { audio: true }) // success callback .then(function(stream) { }) // error callback .catch(function(err) { console.log('the following getuserme...
MediaStream Recording API - Web APIs
Web › API › MediaStream Recording API
to do so, you'll need to call navigator.mediadevices.enumeratedevices() to get a list of the available media devices.
... navigator.mediadevices.enumeratedevices() .then(function(devices) { devices.foreach(function(device) { let menu = document.getelementbyid("inputdevices"); if (device.kind == "audioinput") { let item = document.createelement("option"); item.innerhtml = device.label; item.value = device.deviceid; menu.appendchild(item); } }); }); code similar to this can be used to let the user restrict the set of ...
MediaTrackSupportedConstraints.aspectRatio - Web APIs
Web › API › MediaTrackSupportedConstraints › aspectRatio
you can access the supported constraints dictionary by calling navigator.mediadevices.getsupportedconstraints().
... example html content <div id="result"> </div> css content #result { font: 14px "arial", sans-serif; } javascript content let result = document.getelementbyid("result"); if (navigator.mediadevices.getsupportedconstraints().aspectratio) { result.innerhtml = "supported!"; } else { result.innerhtml = "not supported!"; } result specifications specification status comment media capture and streamsthe definition of 'aspectratio' in that specification.
MediaTrackSupportedConstraints.autoGainControl - Web APIs
Web › API › MediaTrackSupportedConstraints › autoGainControl
you can access the supported constraints dictionary by calling navigator.mediadevices.getsupportedconstraints().
... html content <div id="result"> </div> css content #result { font: 14px "arial", sans-serif; } javascript content let result = document.getelementbyid("result"); if (navigator.mediadevices.getsupportedconstraints().autogaincontrol) { result.innerhtml = "supported!"; } else { result.innerhtml = "not supported!"; } result specifications specification status comment media capture and streamsthe definition of 'autogaincontrol' in that specification.
MediaTrackSupportedConstraints.channelCount - Web APIs
Web › API › MediaTrackSupportedConstraints › channelCount
you can access the supported constraints dictionary by calling navigator.mediadevices.getsupportedconstraints().
... example html content <div id="result"> </div> css content #result { font: 14px "arial", sans-serif; } javascript content let result = document.getelementbyid("result"); if (navigator.mediadevices.getsupportedconstraints().channelcount) { result.innerhtml = "supported!"; } else { result.innerhtml = "not supported!"; } result specifications specification status comment media capture and streamsthe definition of 'channelcount' in that specification.
MediaTrackSupportedConstraints.cursor - Web APIs
Web › API › MediaTrackSupportedConstraints › cursor
the supported constraints list is obtained by calling navigator.mediadevices.getsupportedconstraints().
... async function capturewithcursor() { let supportedconstraints = navigator.mediadevices.getsupportedconstraints(); let displaymediaoptions = { video: { displaysurface: "browser" }, audio: false; }; if (supportedconstraints.cursor) { displaymediaoptions.video.cursor = "always"; } try { videoelem.srcobject = await navigator.mediadevices.getdisplaymedia(displaymediaoptions); } catch(err) { /* handle the error */ } } specifica...
MediaTrackSupportedConstraints.deviceId - Web APIs
Web › API › MediaTrackSupportedConstraints › deviceId
you can access the supported constraints dictionary by calling navigator.mediadevices.getsupportedconstraints().
... example html content <div id="result"> </div> css content #result { font: 14px "arial", sans-serif; } javascript content let result = document.getelementbyid("result"); if (navigator.mediadevices.getsupportedconstraints().deviceid) { result.innerhtml = "supported!"; } else { result.innerhtml = "not supported!"; } result specifications specification status comment media capture and streamsthe definition of 'deviceid' in that specification.
MediaTrackSupportedConstraints.displaySurface - Web APIs
Web › API › MediaTrackSupportedConstraints › displaySurface
the supported constraints list is obtained by calling navigator.mediadevices.getsupportedconstraints().
... async function capture() { let supportedconstraints = navigator.mediadevices.getsupportedconstraints(); let displaymediaoptions = { video: { }, audio: false; }; if (supportedconstraints.displaysurface) { displaymediaoptions.video.displaysurface = "monitor"; } try { videoelem.srcobject = await navigator.mediadevices.getdisplaymedia(displaymediaoptions); } catch(err) { /* handle the error */ } } specifications ...
MediaTrackSupportedConstraints.echoCancellation - Web APIs
Web › API › MediaTrackSupportedConstraints › echoCancellation
you can access the supported constraints dictionary by calling navigator.mediadevices.getsupportedconstraints().
... example html content <div id="result"> </div> css content #result { font: 14px "arial", sans-serif; } javascript content let result = document.getelementbyid("result"); if (navigator.mediadevices.getsupportedconstraints().echocancellation) { result.innerhtml = "supported!"; } else { result.innerhtml = "not supported!"; } result specifications specification status comment media capture and streamsthe definition of 'echocancellation' in that specification.
MediaTrackSupportedConstraints.facingMode - Web APIs
Web › API › MediaTrackSupportedConstraints › facingMode
you can access the supported constraints dictionary by calling navigator.mediadevices.getsupportedconstraints().
... example html <div id="result"> </div> css #result { font: 14px "arial", sans-serif; } javascript let result = document.getelementbyid("result"); if (navigator.mediadevices.getsupportedconstraints().facingmode) { result.innerhtml = "supported!"; } else { result.innerhtml = "not supported!"; } result specifications specification status comment media capture and streamsthe definition of 'facingmode' in that specification.
MediaTrackSupportedConstraints.groupId - Web APIs
Web › API › MediaTrackSupportedConstraints › groupId
you can access the supported constraints dictionary by calling navigator.mediadevices.getsupportedconstraints().
... example html content <div id="result"> </div> css content #result { font: 14px "arial", sans-serif; } javascript content let result = document.getelementbyid("result"); if (navigator.mediadevices.getsupportedconstraints().groupid) { result.innerhtml = "supported!"; } else { result.innerhtml = "not supported!"; } result specifications specification status comment media capture and streamsthe definition of 'groupid' in that specification.
MediaTrackSupportedConstraints.height - Web APIs
Web › API › MediaTrackSupportedConstraints › height
you can access the supported constraints dictionary by calling navigator.mediadevices.getsupportedconstraints().
... example html content <div id="result"> </div> css content #result { font: 14px "arial", sans-serif; } javascript content let result = document.getelementbyid("result"); if (navigator.mediadevices.getsupportedconstraints().height) { result.innerhtml = "supported!"; } else { result.innerhtml = "not supported!"; } result specifications specification status comment media capture and streamsthe definition of 'height' in that specification.
MediaTrackSupportedConstraints.latency - Web APIs
Web › API › MediaTrackSupportedConstraints › latency
you can access the supported constraints dictionary by calling navigator.mediadevices.getsupportedconstraints().
... example html content <div id="result"> </div> css content #result { font: 14px "arial", sans-serif; } javascript content let result = document.getelementbyid("result"); if (navigator.mediadevices.getsupportedconstraints().latency) { result.innerhtml = "supported!"; } else { result.innerhtml = "not supported!"; } result specifications specification status comment media capture and streamsthe definition of 'latency' in that specification.
MediaTrackSupportedConstraints.logicalSurface - Web APIs
Web › API › MediaTrackSupportedConstraints › logicalSurface
the supported constraints list is obtained by calling navigator.mediadevices.getsupportedconstraints().
... async function capture() { let supportedconstraints = navigator.mediadevices.getsupportedconstraints(); let displaymediaoptions = { video: { }, audio: false; }; if (supportedconstraints.logicalsurface) { displaymediaoptions.video.logicalsurface = "monitor"; } try { videoelem.srcobject = await navigator.mediadevices.getdisplaymedia(displaymediaoptions); } catch(err) { /* handle the error */ } } specifications ...
MediaTrackSupportedConstraints.noiseSuppression - Web APIs
Web › API › MediaTrackSupportedConstraints › noiseSuppression
you can access the supported constraints dictionary by calling navigator.mediadevices.getsupportedconstraints().
... html content <div id="result"> </div> css content #result { font: 14px "arial", sans-serif; } javascript content let result = document.getelementbyid("result"); if (navigator.mediadevices.getsupportedconstraints().noisesuppression) { result.innerhtml = "supported!"; } else { result.innerhtml = "not supported!"; } result specifications specification status comment media capture and streamsthe definition of 'noisesuppression' in that specification.
MediaTrackSupportedConstraints.sampleRate - Web APIs
Web › API › MediaTrackSupportedConstraints › sampleRate
you can access the supported constraints dictionary by calling navigator.mediadevices.getsupportedconstraints().
... example html content <div id="result"> </div> css content #result { font: 14px "arial", sans-serif; } javascript content let result = document.getelementbyid("result"); if (navigator.mediadevices.getsupportedconstraints().samplerate) { result.innerhtml = "supported!"; } else { result.innerhtml = "not supported!"; } result specifications specification status comment media capture and streamsthe definition of 'samplerate' in that specification.
MediaTrackSupportedConstraints.sampleSize - Web APIs
Web › API › MediaTrackSupportedConstraints › sampleSize
you can access the supported constraints dictionary by calling navigator.mediadevices.getsupportedconstraints().
... example html content <div id="result"> </div> css content #result { font: 14px "arial", sans-serif; } javascript content let result = document.getelementbyid("result"); if (navigator.mediadevices.getsupportedconstraints().samplesize) { result.innerhtml = "supported!"; } else { result.innerhtml = "not supported!"; } result specifications specification status comment media capture and streamsthe definition of 'samplesize' in that specification.
MediaTrackSupportedConstraints.volume - Web APIs
Web › API › MediaTrackSupportedConstraints › volume
you can access the supported constraints dictionary by calling navigator.mediadevices.getsupportedconstraints().
... example html content <div id="result"> </div> css content #result { font: 14px "arial", sans-serif; } javascript content let result = document.getelementbyid("result"); if (navigator.mediadevices.getsupportedconstraints().volume) { result.innerhtml = "supported!"; } else { result.innerhtml = "not supported!"; } result ...
MediaTrackSupportedConstraints.width - Web APIs
Web › API › MediaTrackSupportedConstraints › width
you can access the supported constraints dictionary by calling navigator.mediadevices.getsupportedconstraints().
... example html content <div id="result"> </div> css content #result { font: 14px "arial", sans-serif; } javascript content let result = document.getelementbyid("result"); if (navigator.mediadevices.getsupportedconstraints().width) { result.innerhtml = "supported!"; } else { result.innerhtml = "not supported!"; } result specifications specification status comment media capture and streamsthe definition of 'width' in that specification.
MimeTypeArray - Web APIs
Web › API › MimeTypeArray
this object is returned by navigatorplugins.mimetypes.
... var mimetypes = navigator.mimetype; var flashplugin = mimetypes['video/x-flv']; if (typeof flashplugin === "undefined") { var vid = document.createelement('video'); // use vid.canplaytype() to test for a supported mime type.
NetworkInformation.onchange - Web APIs
Web › API › NetworkInformation › onchange
var type = navigator.connection.type; function changehandler(e) { // handle change of connection type here.
... } // register for event changes: navigator.connection.onchange = changehandler; // another way: navigator.connection.addeventlistener('change', changehandler); specifications specification status comment network information apithe definition of 'onchange' in that specification.
PerformanceEventTiming - Web APIs
Web › API › PerformanceEventTiming
function sendtoanalytics(data) { const body = json.stringify(data); // use `navigator.sendbeacon()` if available, falling back to `fetch()`.
... (navigator.sendbeacon && navigator.sendbeacon('/analytics', body)) || fetch('/analytics', {body, method: 'post', keepalive: true}); } // use a try/catch instead of feature detecting `first-input` // support, since some browsers throw when using the new `type` option.
Permissions API - Web APIs
Web › API › Permissions API
the permissions property has been made available on the navigator object, both in the standard browsing context and the worker context (workernavigator — so permission checks are available inside workers), and returns a permissions object that provides access to the permissions api functionality.
... interfaces navigator.permissions and workernavigator.permissions read only provides access to the permissions object from the main context and worker context respectively.
Pointer events - Web APIs
Web › API › Pointer events
the standard also includes some extensions to the element and navigator interfaces.
... navigator extension the navigator.maxtouchpoints property is used to determine the maximum number of simultaneous touch points that are supported at any single point in time.
Presentation API - Web APIs
Web › API › Presentation API
--> <script> navigator.presentation.defaultrequest = new presentationrequest(presurls); navigator.presentation.defaultrequest.onconnectionavailable = function(evt) { setconnection(evt.connection); }; </script> monitor connection's state and exchange data <!-- controller.html --> <button id="disconnectbtn" style="display: none;">disconnect</button> <button id="stopbtn" style="display: none;">stop</button>...
...d from localstorage if exists delete localstorage["presid"]; connection = null; showdisconnectedui(); }; }; </script> monitor available connection(s) and say hello <!-- presentation.html --> <script> var addconnection = function(connection) { this.onmessage = function (message) { if (message.data == "say hello") this.send("hello"); }; }; navigator.presentation.receiver.connectionlist.then(function (list) { list.connections.map(function (connection) { addconnection(connection); }); list.onconnectionavailable = function (evt) { addconnection(evt.connection); }; }); </script> passing locale information with a message <!-- controller.html --> <script> connection.send("{string: '你好,世界!', lang: 'z...
PublicKeyCredential.getClientExtensionResults() - Web APIs
Web › API › PublicKeyCredential › getClientExtensionResults
during the creation or fetching of a publickeycredential (respectively via navigator.credentials.create() and navigator.credentials.get()), it is possible to have "custom" processing by the client for different extensions which are respectively given by publickeycredentialcreationoptions.extensions and publickeycredentialrequestoptions.extensions.
...uvi": true // user verification index: how the user was verified }, challenge: new uint8array(16) /* from the server */, rp: { name: "example corp", id : "login.example.com" }, user: { id: new uint8array(16) /* from the server */, name: "jdoe@example.com", displayname: "john doe" }, pubkeycredparams: [ { type: "public-key", alg: -7 } ] }; navigator.credentials.create({ publickey }) .then(function (newcredentialinfo) { var mybuffer = newcredentialinfo.getclientextensionresults(); // mybuffer will contain the result of any of the processing of the "loc" and "uvi" extensions }).catch(function (err) { console.error(err); }); specifications specification status comment web authentication: an api f...
PublicKeyCredentialCreationOptions.challenge - Web APIs
Web › API › PublicKeyCredentialCreationOptions › challenge
note: when the credential is retrieved with a navigator.credentials.get() call, the signature of the challenge is contained in authenticatorassertionresponse.signature.
... examples var publickey = { challenge: new uint8array(26) /* this actually is given from the server */, rp: { name: "example corp", id : "login.example.com" }, user: { id: new uint8array(26), /* to be changed for each user */ name: "jdoe@example.com", displayname: "john doe", }, pubkeycredparams: [ { type: "public-key", alg: -7 } ] }; navigator.credentials.create({ publickey }) .then(function (newcredentialinfo) { // send attestation response and client extensions // to the server to proceed with the registration // of the credential }).catch(function (err) { console.error(err); }); specifications specification status comment web authentication: an api for accessing public key credent...
PublicKeyCredentialCreationOptions.extensions - Web APIs
Web › API › PublicKeyCredentialCreationOptions › extensions
note: an analogous option exists for the fetching operation (navigators.credentials.get()), see publickeycredentialrequestoptions.extensions.
... loc: false, uvm: false, exts: true }, challenge: new uint8array(26) /* this actually is given from the server */, rp: { name: "example corp", id : "login.example.com" }, user: { id: new uint8array(26), /* to be changed for each user */ name: "jdoe@example.com", displayname: "john doe", }, pubkeycredparams: [ { type: "public-key", alg: -7 } ] }; navigator.credentials.create({ publickey }) .then(function (newcredentialinfo) { // mybuffer will contain the result of any of the processing of the extensions var mybuffer = newcredentialinfo.getclientextensionresults(); // send attestation response and client extensions // to the server to proceed with the registration // of the credential }).catch(function (err) { console.e...
PublicKeyCredentialCreationOptions.rp - Web APIs
Web › API › PublicKeyCredentialCreationOptions › rp
the rp property of the publickeycredentialcreationoptions dictionary is an object describing the relying party which requested the credential creation (via navigator.credentials.create()).
... examples var publickey = { challenge: /* from the server */, rp: { name: "example corp", id : "login.example.com", icon: "https://login.example.com/login.ico" }, user: { id: new uint8array(16), name: "jdoe@example.com", displayname: "john doe" }, pubkeycredparams: [ { type: "public-key", alg: -7 } ] }; navigator.credentials.create({ publickey }) .then(function (newcredentialinfo) { // send attestation response and client extensions // to the server to proceed with the registration // of the credential }).catch(function (err) { console.error(err); }); specifications specification status comment web authentication: an api for accessing public key credent...
PublicKeyCredentialCreationOptions.timeout - Web APIs
Web › API › PublicKeyCredentialCreationOptions › timeout
note: an analogous option exists for the fetching operation (navigators.credentials.get()), see publickeycredentialrequestoptions.timeout.
... challenge: new uint8array(26) /* this actually is given from the server */, rp: { name: "example corp", id : "login.example.com" }, user: { id: new uint8array(26), /* to be changed for each user */ name: "jdoe@example.com", displayname: "john doe", }, pubkeycredparams: [ { type: "public-key", alg: -7 } ] }; navigator.credentials.create({ publickey }) .then(function (newcredentialinfo) { // send attestation response and client extensions // to the server to proceed with the registration // of the credential }).catch(function (err) { console.error(err); }); specifications specification status comment web authentication: an api for accessing public key credent...
PublicKeyCredentialCreationOptions.user - Web APIs
Web › API › PublicKeyCredentialCreationOptions › user
the user property of the publickeycredentialcreationoptions dictionary is an object describing the user account for which the credentials are generated (via navigator.credentials.create()).
... rp: { name: "example corp", id : "login.example.com" }, user: { // to be changed for each user id: new uint8array.from(window.atob("laegmlkjnrlkgnamlafalfka="), c=>c.charcodeat(0)); name: "jdoe@example.com", displayname: "john doe", icon: "https://gravatar.com/avatar/jdoe.png" }, pubkeycredparams: [ { type: "public-key", alg: -7 } ] }; navigator.credentials.create({ publickey }) .then(function (newcredentialinfo) { // send attestation response and client extensions // to the server to proceed with the registration // of the credential }).catch(function (err) { console.error(err); }); specifications specification status comment web authentication: an api for accessing public key credent...
PublicKeyCredentialCreationOptions - Web APIs
Web › API › PublicKeyCredentialCreationOptions
the publickeycredentialcreationoptions dictionary of the web authentication api holds options passed to navigators.credentials.create() in order to create a publickeycredential.
... type: "public-key", // the id for john.doe@example.com id : new uint8array(26) /* this actually is given by the server */ }, { type: "public-key", // the id for john-doe@example.com id : new uint8array(26) /* another id */ } ] } }; // create the new credential with the options above navigator.credentials.create(createcredentialoptions) .then(function (newcredentialinfo) { var attestationresponse = newcredentialinfo.response; var clientextensionsoutputs = newcredentialinfo.getclientextensionsresults(); // send the response to the relying party server // it will verify the content and integrity before // creating a new credential }).catch(function (err) { /...
PublicKeyCredentialRequestOptions.challenge - Web APIs
Web › API › PublicKeyCredentialRequestOptions › challenge
note: when the credential is created with a navigator.credentials.create() call, the signature of the challenge is contained within authenticatorattestationresponse.attestationobject.
... examples var options = { challenge: new uint8array([/* bytes sent from the server */]) }; navigator.credentials.get({ "publickey": options }) .then(function (credentialinfoassertion) { // send assertion response back to the server // to proceed with the control of the credential }).catch(function (err) { console.error(err); }); specifications specification status comment web authentication: an api for accessing public key credentials level 1the d...
PublicKeyCredentialRequestOptions.extensions - Web APIs
Web › API › PublicKeyCredentialRequestOptions › extensions
note: an analogous option exists for the creation operation (navigators.credentials.create()), see publickeycredentialcreationoptions.extensions.
... examples var options = { extensions: { uvm: true, loc: false, txauthsimple: "could you please verify yourself?" }, challenge: new uint8array([/* bytes sent from the server */]) }; navigator.credentials.get({ "publickey": options }) .then(function (credentialinfoassertion) { // send assertion response back to the server // to proceed with the control of the credential }).catch(function (err) { console.error(err); }); specifications specification status comment web authentication: an api for accessing public key credentials level 1the d...
PublicKeyCredentialRequestOptions.rpId - Web APIs
Web › API › PublicKeyCredentialRequestOptions › rpId
note: an analogous option exists for the creation operation (navigators.credentials.create()), see the id property of publickeycredentialcreationoptions.rp.
... examples var options = { challenge: new uint8array([/* bytes sent from the server */]), rpid: "example.com" // will only work if the current domain // is something like foo.example.com }; navigator.credentials.get({ "publickey": options }) .then(function (credentialinfoassertion) { // send assertion response back to the server // to proceed with the control of the credential }).catch(function (err) { console.error(err); }); specifications specification status comment web authentication: an api for accessing public key credentials level 1the defi...
PublicKeyCredentialRequestOptions.timeout - Web APIs
Web › API › PublicKeyCredentialRequestOptions › timeout
note: an analogous option exists for the creation operation (navigators.credentials.create()), see publickeycredentialcreationoptions.timeout.
... examples var options = { challenge: new uint8array([/* bytes sent from the server */]), timeout: 6000 // wait a minute for the fetching operation // and maybe fail if it takes longer }; navigator.credentials.get({ "publickey": options }) .then(function (credentialinfoassertion) { // send assertion response back to the server // to proceed with the control of the credential }).catch(function (err) { console.error(err); }); specifications specification status comment web authentication: an api for accessing public key credentials level 1the definition ...
PublicKeyCredentialRequestOptions.userVerification - Web APIs
Web › API › PublicKeyCredentialRequestOptions › userVerification
note: an analogous option exists for the creation operation (navigators.credentials.create()), see the userverification property of publickeycredentialcreationoptions.authenticatorselection.
... examples var options = { userverification: "preferred", challenge: new uint8array([/* bytes sent from the server */]), }; navigator.credentials.get({ "publickey": options }) .then(function (credentialinfoassertion) { // send assertion response back to the server // to proceed with the control of the credential }).catch(function (err) { console.error(err); }); specifications specification status comment web authentication: an api for accessing public key credentials level 1the de...
PublicKeyCredentialRequestOptions - Web APIs
Web › API › PublicKeyCredentialRequestOptions
the publickeycredentialrequestoptions dictionary of the web authentication api holds the options passed to navigator.credentials.get() in order to fetch a given publickeycredential.
...s: "usb", type: "public-key", id: new uint8array(26) // actually provided by the server }, { transports: "internal", type: "public-key", id: new uint8array(26) // actually provided by the server } ], extensions: { uvm: true, // rp wants to know how the user was verified loc: false, txauthsimple: "could you please verify yourself?" } }; navigator.credentials.get({ "publickey": options }) .then(function (credentialinfoassertion) { // send assertion response back to the server // to proceed with the control of the credential }).catch(function (err) { console.error(err); }); specifications specification status comment web authentication: an api for accessing public key credentials level 1the d...
PushManager.register() - Web APIs
Web › API › PushManager › register
syntax var request = navigator.push.register(); return a domrequest object to handle the success or failure of the method call.
... example var req = navigator.push.register(); req.onsuccess = function(e) { var endpoint = req.result; debug("new endpoint: " + endpoint ); } req.onerror = function(e) { debug("error getting a new endpoint: " + json.stringify(e)); } specification specification status comment push api working draft defines the pushmanager interface.
PushManager.unregister() - Web APIs
Web › API › PushManager › unregister
syntax var request = navigator.push.unregister(pushendpoint); properties pushendpoint a pushendpoint to be unregistered.
... example var req = navigator.push.unregister(pushendpoint); req.onsuccess = function(e) { var endpoint = req.result; debug("unregistered endpoint: " + endpoint ); } req.onerror = function(e) { debug("error unregistering the endpoint: " + json.stringify(e)); } specification specification status comment push api working draft defines the pushmanager interface.
Sensor APIs - Web APIs
Web › API › Sensor APIs
notice that detection through the navigator interface is not one of the available options.
... navigator.permissions.query({ name: 'accelerometer' }) .then(result => { if (result.state === 'denied') { console.log('permission to use accelerometer sensor is denied.'); return; } // use the sensor.
ServiceWorkerContainer.ready - Web APIs
Web › API › ServiceWorkerContainer › ready
syntax navigator.serviceworker.ready.then(function(serviceworkerregistration) { ...
... example if ('serviceworker' in navigator) { navigator.serviceworker.ready .then(function(registration) { console.log('a service worker is active:', registration.active); // at this point, you can call methods that require an active // service worker, like registration.pushmanager.subscribe() }); } else { console.log('service workers are not supported.'); } specifications specification status comment service workersthe definition of 'serviceworkerregistration.ready' in that specification.
SharedWorkerGlobalScope - Web APIs
Web › API › SharedWorkerGlobalScope
workerglobalscope.navigator read only returns the workernavigator associated with the worker.
... workernavigator is a specific navigator object, mostly a subset of the navigator for browsing scopes, but adapted to workers.
StorageManager.persist() - Web APIs
Web › API › StorageManager › persist
syntax navigator.storage.persist().then(function(persistent) { ...
... example if (navigator.storage && navigator.storage.persist) navigator.storage.persist().then(function(persistent) { if (persistent) console.log("storage will not be cleared except by explicit user action"); else console.log("storage may be cleared by the ua under storage pressure."); }); specifications specification status comment storagethe definition of 'persist' in that specification.
StorageManager.persisted() - Web APIs
Web › API › StorageManager › persisted
syntax navigator.storage.persisted().then(function(persistent) { ...
... example if (navigator.storage && navigator.storage.persist) navigator.storage.persisted().then(function(persistent) { if (persistent) console.log("storage will not be cleared except by explicit user action"); else console.log("storage may be cleared by the ua under storage pressure."); }); specifications specification status comment storagethe definition of 'persisted' in that specification.
StorageQuota - Web APIs
Web › API › StorageQuota
the storagequota property of the navigator interface of the quota management api provides means to query and request storage usage and quota information.
... you can get a reference to this interface using navigator.storagequota.
Storage API - Web APIs
Web › API › Storage API
to determine the estimated quota and usage values for a given origin, use the navigator.storage.estimate() method, which returns a promise that, when resolved, receives a storageestimate that contains these figures.
... for example: navigator.storage.estimate().then(estimate => { // estimate.quota is the estimated quota // estimate.usage is the estimated number of bytes used }); specifications specification status comment storage living standard initial definition.
VRDevice.hardwareUnitId - Web APIs
Web › API › VRDisplay › hardwareUnitId
examples the following snippet (see our vrdevice example) returns an array of all the vrdevices connected to your computer via navigator.getvrdevices().
... var list = document.queryselector('ul'); var info = document.queryselector('p'); if(navigator.getvrdevices) { navigator.getvrdevices().then(function(mydevices) { reportdevices(mydevices); }); } else { info.textcontent = 'webvr api not supported by this browser.' } function reportdevices(devices) { for(i = 0; i < devices.length; i++) { var listitem = document.createelement('li'); listitem.innerhtml = 'device ' + (i+1) + ': <strong>hardware id</strong>: ' + devices[i].hardwareunitid + ', <strong>vd device id</strong>: ' + devices[i].deviceid + ', <strong>vr device name</strong>: ' + devices[i].devicename ...
VRDisplay - Web APIs
Web › API › VRDisplay
an array of all connected vr devices can be returned by invoking the navigator.getvrdisplays() method.
... examples if(navigator.getvrdisplays) { console.log('webvr 1.1 supported'); // then get the displays attached to the computer navigator.getvrdisplays().then(function(displays) { // if a display is available, use it to present the scene if(displays.length > 0) { vrdisplay = displays[0]; // now we have our vrdisplay object and can do what we want with it } }); } note: you can see this co...
WakeLock.request() - Web APIs
Web › API › WakeLock › request
syntax var wakelock = navigator.wakelock.request(type); parameters type options are as follows: 'screen': requests a screen wake lock.
... const requestwakelock = async () => { try { const wakelock = await navigator.wakelock.request('screen'); } catch (err) { // the wake lock request fails - usually system related, such low as battery console.log(`${err.name}, ${err.message}`); } } requestwakelock(); specifications specification status comment screen wake lock apithe definition of 'request()' in that specification.
WakeLock - Web APIs
Web › API › WakeLock
the system wake lock is exposed through the global navigator.wakelock property.
... const requestwakelock = async () => { try { const wakelock = await navigator.wakelock.request('screen'); } catch (err) { // the wake lock request fails - usually system related, such low as battery console.log(`${err.name}, ${err.message}`); } } requestwakelock(); specifications specification status comment screen wake lock apithe definition of 'wakelock' in that specification.
WakeLockSentinel - Web APIs
Web › API › WakeLockSentinel
an object representing the wake lock is returned via the navigator.wakelock.request() method.
... // create a reference for the wake lock let wakelock = null; // create an async function to request a wake lock const requestwakelock = async () => { try { wakelock = await navigator.wakelock.request('screen'); // listen for our release event wakelock.addeventlistener('release', () => { // if wake lock is released alter the ui accordingly }); } catch (err) { // if wake lock request fails - usually system related, such as battery } } wakelockonbutton.addeventlistener('click', () => { requestwakelock(); }) wakelockoffbutton.addeventlistener('cli...
WebGLRenderingContext.makeXRCompatible() - Web APIs
Web › API › WebGLRenderingContext › makeXRCompatible
he game to your xr headset.", "cancel"); break; case invalidstateerror: showsimplemessagebox("you don't appear to have a compatible xr headset available.", "cancel"); break; default: handlefatalerror(err); break; } xrsession.end(); } } async function handlestartbuttonclick(event) { if (event.target.classlist.contains("use-webxr") && navigator.xr) { try { xrsession = await navigator.xr.requestsession("immersive-vr"); usingxr = true; } catch(err) { xrsession = null; usingxr = false; } } startgame(); } function startgame() { currentscene = "scene1"; loadsceneresources(currentscene); /* and so on */ } this works by having two buttons, one which starts the game normally and the other which ...
...if the button clicked by the user has that class (and we've confirmed that webxr is available by ensuring that the navigator.xr property exists), we use requestsession() to request a new webxr session and set the usingxr flag to true.
Taking still photos with WebRTC - Web APIs
Web › API › WebRTC API › Taking still photos
function startup() { video = document.getelementbyid('video'); canvas = document.getelementbyid('canvas'); photo = document.getelementbyid('photo'); startbutton = document.getelementbyid('startbutton'); get the media stream the next task is to get the media stream: navigator.mediadevices.getusermedia({ video: true, audio: false }) .then(function(stream) { video.srcobject = stream; video.play(); }) .catch(function(err) { console.log("an error occurred: " + err); }); here, we're calling mediadevices.getusermedia() and requesting a video stream (without audio).
...to do so, call navigator.mediadevices.enumeratedevices().
Geometry and reference spaces in WebXR - Web APIs
Web › API › WebXR Device API › Geometry
it is not only always available when using an immersive session mode (immersive-vr or immersive-ar), but is always included among the optional features when requesting a new session; thus, every session created by navigator.xr.requestsession() supports the local reference space type.
... xr sessions are created using the navigator.xr.requestsession() method.
Functions and classes available to Web Workers - Web APIs
Web › API › Web Workers API › Functions and classes available to workers
3.6 (1.9.2) 10.0 (yes) (yes) workernavigator the subset of the navigator interface available to workers.
... basic implementation (yes) appcodename, product, taintenabled(): 28 (28) online: 29 (29) navigatorlanguage: (yes) appname, appversion, online, platform, useragent: 10.0 other: no support (yes) (yes) xmlhttprequest creates and returns a new xmlhttprequest object; this mimics the behavior of the standard xmlhttprequest() constructor.
Synchronous and asynchronous requests - Web APIs
Web › API › XMLHttpRequest › Synchronous and Asynchronous Requests
when fetch with keepalive isn't available, you can consider using the navigator.sendbeacon() api, which can support these use cases while typically delivering a good ux.
... window.addeventlistener('unload', logdata, false); function logdata() { navigator.sendbeacon("/log", analyticsdata); } ...
XRPermissionDescriptor.requiredFeatures - Web APIs
Web › API › XRPermissionDescriptor › requiredFeatures
the xrpermissiondescriptor dictionary's requiredfeatures property should be set prior to calling navigator.permissions.query() to a list of webxr features which must be supported for the app to work.
... let xrpermissiondesc = { name: "xr", mode: "immersive-ar", requiredfeatures: [ "local-floor" ] }; if (navigator.permissions) { navigator.permissions.query(xrpermissiondesc).then(({state}) => { switch(state) { case "granted": setupxr(); break; case "prompt": promptandsetupxr(); break; default: /* do nothing otherwise */ break; } .catch(err) { console.log(err); } } else { setupxr(); } specifications specification ...
XRPermissionDescriptor - Web APIs
Web › API › XRPermissionDescriptor
if the permissions api is found to be available (by checking to see if navigator.permissions is defined), its query() method is called, specifying the permission descriptor we've established, xrpermissiondesc.
... let xrpermissiondesc = { name: "xr", mode: "immersive-vr", requiredfeatures: [ "local-floor" ] }; if (navigator.permissions) { navigator.permissions.query(xrpermissiondesc).then(({state}) => { switch(state) { case "granted": setupxr(); break; case "prompt": promptandsetupxr(); break; default: /* do nothing otherwise */ break; } .catch(err) { console.log(err); } } else { setupxr(); } specifications specification ...
XRSession.requestAnimationFrame() - Web APIs
Web › API › XRSession › requestAnimationFrame
// obtain xr object const xr = navigator.xr // request a new xrsession xr.requestsession("inline").then((xrsession) => { xrsession.requestanimationframe((time, xrframe) => { let viewer = xrframe.getviewerpose(xrreferencespace) gl.bindframebuffer(xrwebgllayer.framebuffer) for (xrview of viewer.views) { let xrviewport = xrwebgllayer.getviewport(xrview) gl.viewport(xrviewport.x, xrviewport.y, xrviewport.width, x...
...function startxrsession() { navigator.xr.requestsession('immersive-vr').then((session) => { xrsession = session xrsession.addeventlistener('end', onxrsessionended) // do necessary session setup here.
XRSystem: devicechange event - Web APIs
Web › API › XRSystem › devicechange event
if (navigator.xr) { navigator.xr.addeventlistener("devicechange", event => { navigator.xr.issessionsupported("immersive-vr") .then(immersiveok) => { if (immersiveok) { enablexrbutton.disabled = false; } else { enablexrbutton.disabled = true; } }); }); } when devicechange is received, the handler set up in this code calls the xr method issessionsupported() to...
... you can also use the ondevicechange event handler property to set a single handler for devicechange events: if (navigator.xr) { navigator.xr.ondevicechange = event => { /* ...
XRSystem: ondevicechange - Web APIs
Web › API › XRSystem › ondevicechange
syntax navigator.xr.ondevicechange = function(event) { ...
... }; value undefined example navigator.xr.ondevicechange = function(ev) { console.log("the availability of immersive xr devices has changed.") }; specifications specification status comment webxr device apithe definition of 'ondevicechange ' in that specification.
XRSystem - Web APIs
Web › API › XRSystem
if (navigator.xr) { immersivebutton.addeventlistener("click", onbuttonclicked); navigator.xr.issessionsupported('immersive-vr') .then((issupported) => { if (issupported) { immersivebutton.disabled = false; } else { immersivebutton.disabled = true; }); } function onbuttonclicked() { if (!xrsession) { navigator.xr.requestsession('immersive-vr') .then(() => { // onsess...
... onsessionstarted(xrsession); }); } else { // shut down the already running xrsession xrsession.end() .then(() => xrsession = null); } } this code starts by checking to see if webxr is available by looking for the navigator.xr property.
Web APIs
Web › API
iatrackconstraints mediatracksettings mediatracksupportedconstraints merchantvalidationevent messagechannel messageevent messageport metadata mimetype mimetypearray mouseevent mousescrollevent mousewheelevent mutationevent mutationobserver mutationobserverinit mutationrecord n ndefmessage ndefreader ndefreadingevent ndefrecord ndefwriter namelist namednodemap navigationpreloadmanager navigator navigatorconcurrenthardware navigatorid navigatorlanguage navigatoronline navigatorplugins navigatorstorage networkinformation node nodefilter nodeiterator nodelist nondocumenttypechildnode notation notification notificationaction notificationevent notifyaudioavailableevent o oes_element_index_uint oes_fbo_render_mipmap oes_standard_derivatives oes_texture_float oes_texture_float_lin...
...r webglcontextevent webglframebuffer webglprogram webglquery webglrenderbuffer webglrenderingcontext webglsampler webglshader webglshaderprecisionformat webglsync webgltexture webgltransformfeedback webgluniformlocation webglvertexarrayobject webkitcssmatrix websocket wheelevent window windowclient windoweventhandlers windoworworkerglobalscope worker workerglobalscope workerlocation workernavigator worklet writablestream writablestreamdefaultcontroller writablestreamdefaultwriter x xdomainrequest xmldocument xmlhttprequest xmlhttprequesteventtarget xmlhttprequestresponsetype xmlserializer xpathevaluator xpathexception xpathexpression xpathnsresolver xpathresult xrboundedreferencespace xrenvironmentblendmode xreye xrframe xrframerequestcallback xrhandedness xrinputsource xrinput...
Audio and Video Delivery - Developer guides
Web › Guide › Audio and video delivery
to grab the stream from your webcam, first set up a <video> element: <video id="webcam" width="480" height="360"></video> next, if supported connect the webcam source to the video element: if (navigator.mediadevices) { navigator.mediadevices.getusermedia({ video: true, audio: false }) .then(function onsuccess(stream) { var video = document.getelementbyid('webcam'); video.autoplay = true; video.srcobject = stream; }) .catch(function onerror() { alert('there has been a problem retreiving the streams - are you running on file:/// or did you disallow access?'); }); } else {...
... the main mechanism is outlined below: navigator.mediadevices.getusermedia({audio:true}) .then(function onsuccess(stream) { var recorder = new mediarecorder(stream); var data = []; recorder.ondataavailable = function(e) { data.push(e.data); }; recorder.start(); recorder.onerror = function(e) { throw e.error || new error(e.name); // e.name is ff non-spec } recorder.onstop = function(e) { var a...
<figure>: The Figure with Optional Caption element - HTML: Hypertext Markup Language
Web › HTML › Element › figure
an image --> <figure> <img src="https://udn.realityripple.com/samples/6c/98485e5d8a.png" alt="the beautiful mdn logo."> </figure> <!-- image with a caption --> <figure> <img src="https://udn.realityripple.com/samples/6c/98485e5d8a.png" alt="the beautiful mdn logo."> <figcaption>mdn logo</figcaption> </figure> code snippets <figure> <figcaption>get browser details using <code>navigator</code>.</figcaption> <pre> function navigatorexample() { var txt; txt = "browser codename: " + navigator.appcodename + "; "; txt+= "browser name: " + navigator.appname + "; "; txt+= "browser version: " + navigator.appversion + "; "; txt+= "cookies enabled: " + navigator.cookieenabled + "; "; txt+= "platform: " + navigator.platform + "; "; txt+= "user-agent header: " + navigator...
....useragent + "; "; console.log("navigatorexample", txt); } </pre> </figure> quotations <figure> <figcaption><cite>edsger dijkstra:</cite></figcaption> <blockquote>if debugging is the process of removing software bugs, then programming must be the process of putting them in.</blockquote> </figure> poems <figure> <p style="white-space:pre"> bid me discourse, i will enchant thine ear, or like a fairy trip upon the green, or, like a nymph, with long dishevell'd hair, dance on the sands, and yet no footing seen: love is a spirit all compact of fire, not gross to sink, but light, and will aspire.</p> <figcaption><cite>venus and adonis</cite>, by william shakespeare</figcaption> </figure> specifications specification status comment html liv...
Quirks Mode and Standards Mode - HTML: Hypertext Markup Language
Web › HTML › Quirks Mode and Standards Mode
in the old days of the web, pages were typically written in two versions: one for netscape navigator, and one for microsoft internet explorer.
...in quirks mode, layout emulates nonstandard behavior in navigator 4 and internet explorer 5.
CSP: connect-src - HTTP
Web › HTTP › Headers › Content-Security-Policy › connect-src
the apis that are restricted are: <a> ping, fetch, xmlhttprequest, websocket, eventsource, and navigator.sendbeacon().
...cases given this csp header: content-security-policy: connect-src https://example.com/ the following connections are blocked and won't load: <a ping="https://not-example.com"> <script> var xhr = new xmlhttprequest(); xhr.open('get', 'https://not-example.com/'); xhr.send(); var ws = new websocket("https://not-example.com/"); var es = new eventsource("https://not-example.com/"); navigator.sendbeacon("https://not-example.com/", { ...
API - Archive of obsolete content
Archive › API
navigatorfeatures that used to hang off the navigator interface, but have since been removed.
window/utils - Archive of obsolete content
Archive › Add-ons › Add-on SDK › Low-Level APIs › window utils
in particular: null: get all window types navigator:browser: get "normal" browser windows devtools:scratchpad: get scratchpad windows navigator:view-source: get view source windows if you're not also passing options, you can omit this, and it's the same as passing null.
Miscellaneous - Archive of obsolete content
Archive › Add-ons › Code snippets › Miscellaneous
var ci = components.interfaces; var cc = components.classes; //assume you can not get the main window object directly, if you can, just use it var wm = cc["@mozilla.org/appshell/window-mediator;1"].getservice(ci.nsiwindowmediator); var mainwindow = wm.getmostrecentwindow("navigator:browser"); //get sessionhistory from the current selected tab var history = mainwindow.gbrowser.selectedbrowser.webnavigation.sessionhistory; and then get the page you want, and it's postdata.
On page load - Archive of obsolete content
Archive › Add-ons › Code snippets › On page load
creating an overlay first, you need to create an overlay to one (or more, depending on which applications you target) of the following xul documents: application uri to overlay firefox chrome://browser/content/browser.xul thunderbird chrome://messenger/content/messenger.xul navigator from seamonkey chrome://navigator/content/navigator.xul attaching a script attach a script to your overlay (see "attaching a script to an overlay") that adds a load event listener to appcontent element (browsers) or messagepane (mail): window.addeventlistener("load", function load(event){ window.removeeventlistener("load", load, false); //remove listener, no longer needed myex...
Windows - Archive of obsolete content
Archive › Add-ons › Code snippets › Windows
example window.open(); //this open a pop-up window that could be "blocked" client-side //the following code generate an error as describe in the following warning box var wm = components.classes["@mozilla.org/appshell/window-mediator;1"] .getservice(components.interfaces.nsiwindowmediator); var newwindow = wm.getmostrecentwindow("navigator:browser"); var b = newwindow.gbrowser; the code generate a typeerror from firefox console.
Chapter 3: Introduction to XUL—How to build a more intuitive UI - Archive of obsolete content
Archive › Add-ons › Overlay Extensions › Firefox addons developer guide › Introduction to XUL—How to build a more intuitive UI
for example, firefox uses the windowtype navigator:browser for its browser window and browser:preferences for its options dialog.
Adding Toolbars and Toolbar Buttons - Archive of obsolete content
Archive › Add-ons › Overlay Extensions › XUL School › Adding Toolbars and Toolbar Buttons
<window id="main-window"> <toolbox id="navigator-toolbox"> <toolbar id="xulschoolhello-toolbar" toolbarname="&xulschoolhello.toolbarname.label;" accesskey="&xulschoolhello.toolbar.accesskey;" customizable="true" mode="icons" context="toolbar-context-menu" defaultset="xulschoolhello-hello-world-button" insertbefore="personaltoolbar" /> </toolbox> </window> (note for mac os x: <window id="main-window"> and </windo...
Appendix E: DOM Building and Insertion (HTML & XUL) - Archive of obsolete content
Archive › Add-ons › Overlay Extensions › XUL School › DOM Building and HTML Insertion
label: "test button label", tooltiptext: "test button tooltip", removable: true, key: "mytestbutton123" }, [ "menupopup", { onpopupshowing: function(event) { addentrytopopup(this, document, window); } }, null ] ]; var capturednodes = {}; var toolbox = doc.getelementbyid("navigator-toolbox"); var palette = toolbox.palette; var domfragment = jsontodom(jsontemplatebtn, document, capturednodes); palette.appendchild(domfragment); alert("capturednodes contains any created nodes that have optionally been captured (for later convenient javascript access) by giving them a 'key' attribute; for example: " + capturednodes.mytestbutton123); another example this here is another exam...
Handling Preferences - Archive of obsolete content
Archive › Add-ons › Overlay Extensions › XUL School › Handling Preferences
tip: you can use window.navigator.platform in your chrome code to figure out the operating system firefox is running on.
Signing an XPI - Archive of obsolete content
Archive › Add-ons › Signing an XPI
ideally you want a certificate that has a root ca installed in all major platforms (microsoft windows, sun java, mozilla/netscape firefox/navigator, opera) so you only use one certificate for signing all your software, no matter which platform it is for.
List of Former Mozilla-Based Applications - Archive of obsolete content
Archive › List of Former Mozilla-Based Applications
old article available about how borland embedded mozilla in kylix 2 mango im client last news item on site from january 2007 mobidvd dvd/vcd/cd ripping software site down mozilla suite internet application suite development shifted to firefox, thunderbird and seamonkey applications netscape navigator browser support for netscape ended on february 1, 2008 nvu web authoring tool development stopped in 2005 and is being continued as an unofficial bugfix release by the kompozer project pogo browser from at&t site no longer accessible as of may 2009 pyro desktop desktop environment last news item on site from july 2007 script editor ed...
MCD, Mission Control Desktop, AKA AutoConfig - Archive of obsolete content
Archive › Misc top level › MCD, Mission Control Desktop AKA AutoConfig
// var = getenv(envvar) // var = putenv(envvar) // // objects/functions you *can't* use because they aren't defined // navigator.* (argh, this *really* bites) //========================================================================= // preferences configuration //========================================================================= with (prefconfig) { var values = getldapattributes("ldap2.int-evry.fr", \ "ou=people,dc=int-evry,dc=fr", "uid=" + env_user, "cn,mail"); var ldap_email = getldapvalue(values, "mail"); var l...
Adding the structure - Archive of obsolete content
Archive › Mozilla › Creating a Mozilla extension › Adding the structure
to implement this ui, we'll add a statusbarpanel element to the statusbar element in the navigator.xul file.
Conclusion - Archive of obsolete content
Archive › Mozilla › Creating a Mozilla extension › Conclusion
for example, you need to change chrome://navigator/content/navigator.xul to chrome://browser/content/browser.xul.
Finding the code to modify - Archive of obsolete content
Archive › Mozilla › Creating a Mozilla extension › Finding the code to modify
open the navigator.xul file in a text editor.
Making it into a dynamic overlay and packaging it up for distribution - Archive of obsolete content
Archive › Mozilla › Creating a Mozilla extension › Making it into a dynamic overlay and packaging it up for distribution
tatus"/> </rdf:seq> <rdf:description about="urn:mozilla:package:tinderstatus" chrome:displayname="mozilla tinderstatus extension" chrome:author="myk melez" chrome:name="tinderstatus" chrome:extension="true" chrome:description="displays tinderbox status for the mozilla codebase."> </rdf:description> <rdf:seq about="urn:mozilla:overlays"> <rdf:li resource="chrome://navigator/content/navigator.xul"/> </rdf:seq> <rdf:seq about="chrome://navigator/content/navigator.xul"> <rdf:li>chrome://tinderstatus/content/tinderstatusoverlay.xul</rdf:li> </rdf:seq> </rdf:rdf> install.js, on the other hand, goes into the tinderstatus-installer directory: initinstall( "mozilla tinderstatus extension", "/mozdev/tinderstatus", "0.1"); var installdir = getfolder("...
chrome.manifest - Archive of obsolete content
Archive › Mozilla › Creating a Skin for SeaMonkey 2.x › chrome.manifest
hat file as "chrome.manifest": skin global my_theme jar:chrome/my_theme.jar!/global/ skin mozapps my_theme jar:chrome/my_theme.jar!/mozapps/ skin messenger my_theme jar:chrome/my_theme.jar!/messenger/ skin messenger-newsblog my_theme jar:chrome/my_theme.jar!/messenger-newsblog/ skin communicator my_theme jar:chrome/my_theme.jar!/communicator/ skin help my_theme jar:chrome/my_theme.jar!/help/ skin navigator my_theme jar:chrome/my_theme.jar!/navigator/ skin editor my_theme jar:chrome/my_theme.jar!/editor/ ...
Creating a Skin for Firefox/Getting Started - Archive of obsolete content
Archive › Mozilla › Creating a sking for Firefox Getting Started
<rdf:li resource="urn:mozilla:skin:my_theme:communicator"/> <rdf:li resource="urn:mozilla:skin:my_theme:editor"/> <rdf:li resource="urn:mozilla:skin:my_theme:global"/> <rdf:li resource="urn:mozilla:skin:my_theme:messenger"/> <rdf:li resource="urn:mozilla:skin:my_theme:navigator"/> save the file and exit the text editor.
Layout System Overview - Archive of obsolete content
Archive › Mozilla › Firefox › Layout System Overview
presentation formatting is also required to provide compatibility with legacy browsers (microsoft internet explorer and netscape navigator 4.x).
Migrate apps from Internet Explorer to Mozilla - Archive of obsolete content
Archive › Mozilla › Migrate apps from Internet Explorer to Mozilla
as a result, mozilla is not fully backwards-compatible with netscape navigator 4.x and microsoft internet explorer legacy code; for example, mozilla does not support <layer> as i will discuss later.
Remote Verification API - Archive of obsolete content
Archive › Mozilla › Persona › Remote Verification API
available as the first parameter passed to the onlogin function in navigator.id.watch().
Problems integrating with CRSF protection - Archive of obsolete content
Archive › Mozilla › Persona › The implementor s guide › Problems integrating with CRSF protection
but when persona has generated an assertion in response to a call to navigator.id.request(), persona calls onlogin for every tab which has that website loaded, not just the single tab that requested the assertion.
Supporting users without JavaScript - Archive of obsolete content
Archive › Mozilla › Persona › The implementor s guide › Supporting users without JavaScript
if you need to support users who don't have javascript enabled, you'll have to implement an alternative login scheme for these users, and disable the "sign in with persona" button, enabling it in the javascript code that connects the sign-in button to navigator.id.request().
createKey - Archive of obsolete content
Archive › Mozilla › XPInstall › Reference › WinReg Object › Methods › createKey
method of winreg object syntax int createkey ( string subkey, string classname); parameters the method has the following parameters: subkey the key path to the appropriate location in the key hierarchy, such as "software\\netscape\\navigator\\mail".
deleteKey - Archive of obsolete content
Archive › Mozilla › XPInstall › Reference › WinReg Object › Methods › deleteKey
method of winreg object syntax int deletekey ( string subkey); parameters the method has the following parameters: subkey the key path to the appropriate location in the key hierarchy, such as "software\\netscape\\navigator\\mail".
deleteValue - Archive of obsolete content
Archive › Mozilla › XPInstall › Reference › WinReg Object › Methods › deleteValue
method of winreg object syntax int deletevalue ( string subkey, string valname); parameters the deletevalue method has the following parameters: subkey the key path to the appropriate location in the key hierarchy, such as "software\\netscape\\navigator\\mail".
enumKeys - Archive of obsolete content
Archive › Mozilla › XPInstall › Reference › WinReg Object › Methods › enumKeys
method of winreg object syntax string enumkeys ( string key, int subkeyindex ); parameters the enumkeys method has the following parameters: key the key path to the appropriate location in the key hierarchy, such as "software\\netscape\\navigator\\mail".
enumValueNames - Archive of obsolete content
Archive › Mozilla › XPInstall › Reference › WinReg Object › Methods › enumValueNames
method of winreg object syntax string enumvaluenames ( string key, int subkeyindex ); parameters the enumvaluenames method has the following parameters: key the key path to the appropriate location in the key hierarchy, such as "software\\netscape\\navigator\\mail".
getValue - Archive of obsolete content
Archive › Mozilla › XPInstall › Reference › WinReg Object › Methods › getValue
method of winreg object syntax winregvalue getvalue ( string subkey, string valname); parameters the getvalue method has the following parameters: subkey the key path to the appropriate location in the key hierarchy, such as "software\\netscape\\navigator\\mail".
getValueNumber - Archive of obsolete content
Archive › Mozilla › XPInstall › Reference › WinReg Object › Methods › getValueNumber
method of winreg object syntax number getvaluenumber ( string subkey, string valname); parameters the getvaluestring method has the following parameters: subkey the key path to the appropriate location in the key hierarchy, such as "software\\netscape\\navigator\\mail".
getValueString - Archive of obsolete content
Archive › Mozilla › XPInstall › Reference › WinReg Object › Methods › getValueString
method of winreg object syntax string getvaluestring ( string subkey, string valname); parameters the getvaluestring method has the following parameters: subkey the key path to the appropriate location in the key hierarchy, such as "software\\netscape\\navigator\\mail".
setValue - Archive of obsolete content
Archive › Mozilla › XPInstall › Reference › WinReg Object › Methods › setValue
method of winreg object syntax string setvalue ( string subkey, string valname, winregvalue value); parameters the setvalue method has the following parameters: subkey the key path to the appropriate location in the key hierarchy, such as "software\\netscape\\navigator\\mail".
setValueNumber - Archive of obsolete content
Archive › Mozilla › XPInstall › Reference › WinReg Object › Methods › setValueNumber
method of winreg object syntax int setvaluenumber ( string subkey, string valname, number value ); parameters the method has the following parameters: subkey the key path to the appropriate location in the key hierarchy, such as "software\\netscape\\navigator\\mail".
setValueString - Archive of obsolete content
Archive › Mozilla › XPInstall › Reference › WinReg Object › Methods › setValueString
method of winreg object syntax int setvaluestring ( string subkey, string valname, string value); parameters the method has the following parameters: subkey the key path to the appropriate location in the key hierarchy, such as "software\\netscape\\navigator\\mail".
Learn XPI Installer Scripting by Example - Archive of obsolete content
Archive › Mozilla › XPInstall › Scripting by example
var cf = getfolder("chrome"); registerchrome(content | delayed_chrome, getfolder(cf,"toolkit.xpi"),"content/global/"); registerchrome(content | delayed_chrome, getfolder(cf,"browser.xpi"),"content/communicator/"); registerchrome(content | delayed_chrome, getfolder(cf,"browser.xpi"),"content/editor/"); registerchrome(content | delayed_chrome, getfolder(cf,"browser.xpi"),"content/navigator/"); registerchrome(skin | delayed_chrome, getfolder(cf,"modern.jar"),"skin/modern/communicator/"); registerchrome(skin | delayed_chrome, getfolder(cf,"modern.jar"),"skin/modern/editor/"); ...
reserved - Archive of obsolete content
Archive › Mozilla › XUL › Attribute › reserved
example here, the command to open a new browser window is reserved: <command id="cmd_newnavigator" oncommand="openbrowserwindow()" reserved="true"/> if the keyboard shortcut for that is accel-t, then this code will not work as expected, as compared to when it is run from web content: document.addeventlistener("keydown", handlekey, true); function handlekey(event) { // listen for the "new tab" shortcut if (event.metakey && (event.key == "t")) { // log a message console.log("...
windowtype - Archive of obsolete content
Archive › Mozilla › XUL › Attribute › windowtype
values for window type as found on mxr: http://mxr.mozilla.org/mozilla-release/search?string=windowtype navigator:browser - looks like if window has gbrowser it has this window type devtools:scratchpad - scratchpad windows navigator:view-source - the view source windows ...
appendNotification - Archive of obsolete content
Archive › Mozilla › XUL › Method › appendNotification
var window=components.classes["@mozilla.org/appshell/window-mediator;1"] .getservice(components.interfaces.nsiwindowmediator) .getmostrecentwindow("navigator:browser"); } if (typeof gbrowser === "undefined") { //if there is no gbrowser defined, get it var gbrowser = window.gbrowser; } function testnotificationbutton1callback(thenotification, buttoninfo, eventtarget) { window.alert("button 1 pressed"); //prevent notification from closing: return true; }; function testnotificationbutton2c...
Creating toolbar buttons (Customize Toolbar Window) - Archive of obsolete content
Archive › Mozilla › XUL › Toolbars › Creating toolbar buttons
a list of commonly overlayed windows with toolbars url application and affected window(s) palette id chrome://browser/content/browser.xul firefox - main window browsertoolbarpalette chrome://navigator/content/navigator.xul seamonkey 2.0 - browser window browsertoolbarpalette chrome://messenger/content/messenger.xul thunderbird - main window mailtoolbarpalette chrome://messenger/content/messenger...gercompose.xul thunderbird - compose window msgcomposetoolbarpalette chrome://messenger/content/addressbo...ddressbook.xul thunderbird - address book ...
Code Samples - Archive of obsolete content
Archive › Mozilla › XUL › Toolbars › Custom toolbar button › Code Samples
ordmanager" const uri = chrome://messenger/content/preferenc...wpasswords.xul" mail & newsgroups const name = "mail:3pane" const uri = "chrome://messenger/content/" sunbird passwords* const name = "toolkit:passwordmanager" const uri = "chrome://passwordmgr/content/passwordmanager.xul" seamonkey navigator const name = "navigator:browser" const uri = "chrome://navigator/content/" mail & newsgroups const name = "mail:3pane" const uri = "chrome://messenger/content/" composer const name = "composer:html" const uri = "chrome://editor/content/" address book const name = "mail:addressbook" ...
Creating a Window - Archive of obsolete content
Archive › Mozilla › XUL › Tutorial › Creating a Window
the syntax is described below: window.open(url,windowname,flags); where the flags contains the flag "chrome" as in this example window.open("chrome://navigator/content/navigator.xul", "bmarks", "chrome,width=600,height=300"); if you are using firefox, try below: window.open("chrome://browser/content/places/places.xul", "bmarks", "chrome,width=600,height=300"); you can test lines of javascript like these in the error console.
Skinning XUL Files by Hand - Archive of obsolete content
Archive › Mozilla › XUL › Tutorial › Skinning XUL Files by Hand
here is a very short (but complete!) cascading stylesheet that might be referenced and used by a xul file: toolbar.nav-bar { background-image: url("chrome://navigator/skin/navbar-bg.gif"); padding: 0px; padding-bottom: 2px; } box#navbar { background-color: lightblue; } a:link { color: #fa8072; } this stylesheet exhibits three of the different types of style definitions described above.
Using nsIXULAppInfo - Archive of obsolete content
Archive › Mozilla › XUL › Using nsIXULAppInfo
this is not useful for scripts on webpages, which should continue using the navigator object when it's not possible to rely on feature-detection.
window - Archive of obsolete content
Archive › Mozilla › XUL › window
values for window type as found on mxr: http://mxr.mozilla.org/mozilla-release/search?string=windowtype navigator:browser - looks like if window has gbrowser it has this window type devtools:scratchpad - scratchpad windows navigator:view-source - the view source windows properties inherited properties align, , allowevents, , boxobject, builder, , , , classname, , , , , collapsed, contextmenu, controllers, database, datasources, dir, , , flex, height, hidden, id, , , left, , maxheight, maxwidth, ...
wizard - Archive of obsolete content
Archive › Mozilla › XUL › wizard
values for window type as found on mxr: http://mxr.mozilla.org/mozilla-release/search?string=windowtype navigator:browser - looks like if window has gbrowser it has this window type devtools:scratchpad - scratchpad windows navigator:view-source - the view source windows properties canadvance type: boolean this property is set to true if the user can press the next button to go to the next page.
Debugging a XULRunner Application - Archive of obsolete content
Archive › Mozilla › XULRunner › Debugging XULRunner applications
add the following code to your xul app: components.utils.import('resource://gre/modules/devtools/dbg-server.jsm'); if (!debuggerserver.initialized) { debuggerserver.init(); // don't specify a window type parameter below if "navigator:browser" // is suitable for your app.
MacFAQ - Archive of obsolete content
Archive › Mozilla › XULRunner › MacFAQ
taking advantage of the core code "openurl" from "nscommandlineservicemac.cpp", you'll see that it looks for "browser.chromeurl" before defaulting to navigator.xul, and this is called when an xulrunner app is already running, so: create a default preference of "browser.chromeurl" that points to your new "hiddenwindow" as such: "chrome://myxul/content/hiddenwindow.xul" next take the code below and drop it in, to create the hiddenwindow.xul (note: the debug function and nsicommandline try/catch can be removed, all you need is the window.arguments[0])...
Archived Mozilla and build documentation - Archive of obsolete content
Archive › Mozilla
as a result, mozilla is not fully backwards-compatible with netscape navigator 4.x and microsoft internet explorer legacy code; for example, mozilla does not support <layer> as i will discuss later.
NPWindow - Archive of obsolete content
Archive › Plugins › Reference › NPWindow
values: npwindowtypewindow: indicates that the window field holds a platform-specific handle to a window (as in navigator 2.0 and navigator 3.0).
NP_GetMIMEDescription - Archive of obsolete content
Archive › Plugins › Reference › NP GetMIMEDescription
#include <gio/gio.h> const char* desc = g_content_type_get_description("audio/ogg"); javascript inside a web page, you can retrieve these informations with this code: var mimetype = navigator.mimetypes['application/basic-example-plugin']; if (mimetype) { alert(mimetype.type + ':' + mimetype.suffixes + ':' + mimetype.description); } ...
Browser Feature Detection - Archive of obsolete content
Archive › Web › Browser feature detection
window.onerror = null; document.write('<p><b> your browser ' + navigator.useragent + '<\/b><\/p>'); generatereport(document, 'domcore1', 'document'); generatereport(document, 'domcore2', 'document'); generatereport(document, 'domhtml', 'document'); generatereport(document.body.style, 'domcss1', 'document.body.style'); generatereport(document.body.style, 'domcss2', 'document.body.style'); window.onerror = oldonerror; see also browser detection and cross br...
Displaying notifications (deprecated) - Archive of obsolete content
Archive › Web › Displaying notifications (deprecated)
creating a notification the first thing you need to do is create the notification object by using the navigator.moznotification object's createnotification() method, as follows: var notification = navigator.moznotification.createnotification( "hey, check this out!", "this is a notification posted by " + "firefox 4.
New in JavaScript 1.5 - Archive of obsolete content
Archive › Web › JavaScript › New in JavaScript › 1.5
this version was included in netscape navigator 6.0 was released on november 14, 2000 and was also used in later versions of netscape navigator and firefox 1.0.
LiveConnect Overview - Archive of obsolete content
Archive › Web › LiveConnect › LiveConnect Overview
for example, with netscape navigator 4 for windows nt, the classes are delivered in the java40.jar file in the program\java\classes directory beneath the navigator directory.
Fixing Table Inheritance in Quirks Mode - Archive of obsolete content
Archive › Web Standards › Fixing Table Inheritance in Quirks Mode
in version 4 browsers such as netscape navigator 4.x and internet explorer 4.x, tables generally "broke" the inheritance of font styling.
Using the Right Markup to Invoke Plugins - Archive of obsolete content
Archive › Web Standards › Using the Right Markup to Invoke Plugins
under edit | preferences | navigator | helper applications is a preference to use netscape's plugin finder service.
WebVR — Virtual Reality for the Web - Game development
Games › Techniques › 3D on the web › WebVR
get the devices to get information about devices connected to your computer, you can use the navigator.getvrdevices method: navigator.getvrdevices().then(function(devices) { for (var i = 0; i < devices.length; ++i) { if (devices[i] instanceof hmdvrdevice) { ghmd = devices[i]; break; } } if (ghmd) { for (var i = 0; i < devices.length; ++i) { if (devices[i] instanceof positionsensorvrdevice && devices[i].hardwareunitid === ghmd.hardwareunitid) { g...
Implementing controls using the Gamepad API - Game development
Games › Techniques › Controls Gamepad API
getting the gamepads the navigator.getgamepads() method has been updated with a longer explanation and an example piece of code.
2D maze game with device orientation - Game development
Games › Tutorials › HTML5 Gamedev Phaser Device Orientation
the best way to use it in our case is to vibrate the phone every time the ball hits the walls — inside the wallcollision function: if("vibrate" in window.navigator) { window.navigator.vibrate(100); } if the vibrate method is supported by the browser and available in the window.navigator object, vibrate the phone for 100 miliseconds.
JavaScript - MDN Web Docs Glossary: Definitions of Web-related terms
Glossary › JavaScript
origins and history conceived as a server-side language by brendan eich (then employed by the netscape corporation), javascript soon came to netscape navigator 2.0 in september 1995.
MDN Web Docs Glossary: Definitions of Web-related terms
Glossary
microsoft internet explorer middleware mime mime type minification mitm mixin mobile first modem modern web apps modularity mozilla firefox mutable mvc n namespace nan nat native navigation directive netscape navigator network throttling nntp node node (dom) node (networking) node.js non-normative normative null nullish value number o object object reference oop opengl openssl opera browser operand operator origin ...
Index - Learn web development
Learn › Index
61 manipulating documents api, article, beginner, codingscripting, dom, document, document object model, javascript, learn, navigator, webapi, window we have reached the end of our study of document and dom manipulation.
Graceful asynchronous programming with Promises - Learn web development
Learn › JavaScript › Asynchronous › Promises
the code that the video chat application would use might look something like this: function handlecallbutton(evt) { setstatusmessage("calling..."); navigator.mediadevices.getusermedia({video: true, audio: true}) .then(chatstream => { selfviewelem.srcobject = chatstream; chatstream.gettracks().foreach(track => mypeerconnection.addtrack(track, chatstream)); setstatusmessage("connected"); }).catch(err => { setstatusmessage("failed to connect"); }); } this function starts by using a function called setstatusmessage() ...
Chrome registration
Mozilla › Chrome Registration
xbl-marquee jar:comm.jar!/content/xbl-marquee/ content pipnss jar:pipnss.jar!/content/pipnss/ locale pipnss en-us jar:en-us.jar!/locale/pipnss/ # firefox-only overlay chrome://browser/content/pageinfo.xul chrome://pippki/content/pageinfooverlay.xul application={ec8030f7-c20a-464f-9b0e-13a3a9e97384} # seamonkey-only overlay chrome://navigator/content/pageinfo.xul chrome://pippki/content/pageinfooverlay.xul application={92650c4d-4b8e-4d2a-b7eb-24ecf4f6b63a} overlay chrome://communicator/content/pref/preftree.xul chrome://pippki/content/prefoverlay.xul content pippki jar:pippki.jar!/content/pippki/ locale pippki en-us jar:en-us.jar!/locale/pippki/ content global-platform jar...
Developer guide
Mozilla › Developer guide
adding apis to the navigator object how to augment the window.navigator object with additional apis.
Hacking with Bonsai
Mozilla › Hacking with Bonsai
the original navigator code base had large sections that were shared across multiple platforms.
How to Report a Hung Firefox
Mozilla › How to report a hung Firefox
getservice(ci.nsiwindowmediator); let win = wm.getmostrecentwindow("navigator:browser"); let browser = win.gbrowser.selectedbrowser; if (browser.isremotebrowser) { browser.messagemanager.loadframescript('data:,let appinfo = components.classes["@mozilla.org/xre/app-info;1"];if (appinfo && appinfo.getservice(components.interfaces.nsixulruntime).processtype != components.interfaces.nsixulruntime.process_type_default) {components.utils.import("resource://gre/modules/ctypes.j...
Add-on Manager
Mozilla › JavaScript code modules › Add-on Manager
= addonmanager.getstartupchanges(addonmanager.startup_change_disabled); if (addonids.length > 0) { // addonids is now an array of the add-on ids that have been disabled alert("note: " + addonids.length + " add-ons have been disabled."); } open add-on manager tab the add-on manager tab can be opened programatically with the function browseropenaddonsmgr which is available on chrome window of "navigator:browser" type.
Mozilla Quirks Mode Behavior
Mozilla › Mozilla quirks mode behavior
there are a bunch of quirks to get percentage heights on images, tables, objects, and applets (etc.?) to "work" (the way they did in netscape navigator 4), even though css says that percentage heights should behave like 'auto' heights when the parent element doesn't have a fixed height.
Index
Mozilla › Projects › NSS › Index
to see fully qualified certificate names when you run communicator, click the security button in navigator, then click yours under certificates in the left frame.
NSS tools : signtool
Mozilla › Projects › NSS › tools › signtool
to see fully qualified certificate names when you run communicator, click the security button in navigator, then click yours under certificates in the left frame.
Rhino history
Mozilla › Projects › Rhino › History
at the time, netscape was planning to produce a version of navigator written entirely in java and so it needed an implementation of javascript written in java.
Rhino overview
Mozilla › Projects › Rhino › Overview
these features allow for the implementation of a traditional url-based security policy for javascript as in netscape navigator.
Split object
Mozilla › Projects › SpiderMonkey › Split object
(several objects, such as window.location and window.navigator, are intentionally parented to the outer window object using such apis.) to enforce this rule: apis that allow the caller to pass a scope object always check that object first and fail if any outer objects are on its scope chain.
nsIAlertsService
Mozilla › Tech › XPCOM › Reference › Interface › nsIAlertsService
mozilla.org/alerts-service;1'].getservice(ci.nsialertsservice); var notiflistener = { observe: function(asubject, atopic, adata) { console.error('incoming notification observer:', asubject, atopic, adata); if (atopic == 'alertclickcallback') { console.error('user clicked trying to throw click'); services.prompt.alert(services.wm.getmostrecentwindow('navigator:firefox'), 'focus firefox', 'will now focus fireox and then focus the tab'); } else if (atopic == 'alertshow') { console.log('just showed notification'); } else if (atopic == 'alertfinished') { console.log('just alertfinished') } } }; as.showalertnotification('chrome://branding/content/icon64.png', 'stackoverflow - new messages', 'there are ## ...
nsIDOMDesktopNotificationCenter
Mozilla › Tech › XPCOM › Reference › Interface › nsIDOMDesktopNotificationCenter
the nsidomdesktopnotificationcenter interface implements the dom navigator.moznotification interface.
nsIDOMWindowInternal
Mozilla › Tech › XPCOM › Reference › Interface › nsIDOMWindowInternal
navigator nsidomnavigator readonly: returns a reference to the navigator object.
nsIMacDockSupport
Mozilla › Tech › XPCOM › Reference › Interface › nsIMacDockSupport
this can be done like this: var docksupport = cc['@mozilla.org/widget/macdocksupport;1'].getservice(ci.nsimacdocksupport); console.log('docksupport:', docksupport); var win = services.wm.getmostrecentwindow('navigator:browser'); var macmenu = win.document.createelementns('http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul', 'menupopup'); macmenu.setattribute('id', 'mymacmenu'); var macmenuitem = win.document.createelementns('http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul', 'menuitem'); macmenuitem.setattribute('label', 'show most recent window'); macmenuitem.setattribute('id', 'mymacm...
nsISessionStore
Mozilla › Tech › XPCOM › Reference › Interface › nsISessionStore
the api operates on top-level browser.xul and navigator.xul windows; see note on windows for details.
nsIWinTaskbar
Mozilla › Tech › XPCOM › Reference › Interface › nsIWinTaskbar
example netscape.security.privilegemanager.enableprivilege("universalxpconnect"); var taskbar = components.classes["@mozilla.org/windows-taskbar;1"].getservice(components.interfaces.nsiwintaskbar); // get the docshell for the browser var navigator2 = top.queryinterface(components.interfaces.nsiinterfacerequestor).getinterface(components.interfaces.nsiwebnavigation); var docshell = navigator2.queryinterface(components.interfaces.nsidocshell); // get the parent docshell; this is the top-level docshell var docshelltreeitem = docshell.queryinterface(components.interfaces.nsidocshelltreeitem); var parent = docshelltreeitem.parent; var ds = pa...
nsIWorkerGlobalScope
Mozilla › Tech › XPCOM › Reference › Interface › nsIWorkerGlobalScope
navigator nsiworkernavigator read only.
XPCOM Interface Reference
Mozilla › Tech › XPCOM › Reference › Interface
allbacknsidomgeopositioncoordsnsidomgeopositionerrornsidomgeopositionerrorcallbacknsidomgeopositionoptionsnsidomglobalpropertyinitializernsidomhtmlaudioelementnsidomhtmlformelementnsidomhtmlmediaelementnsidomhtmlsourceelementnsidomhtmltimerangesnsidomjswindownsidommousescrolleventnsidommoznetworkstatsnsidommoznetworkstatsdatansidommoznetworkstatsmanagernsidommoztoucheventnsidomnshtmldocumentnsidomnavigatordesktopnotificationnsidomnodensidomofflineresourcelistnsidomorientationeventnsidomparsernsidomprogresseventnsidomserializernsidomsimplegestureeventnsidomstoragensidomstorage2nsidomstorageeventobsoletensidomstorageitemnsidomstoragelistnsidomstoragemanagernsidomstoragewindownsidomuserdatahandlernsidomwindownsidomwindow2nsidomwindowinternalnsidomwindowutilsnsidomxpathevaluatornsidomxpathexceptionnsid...
Working with windows in chrome code
Mozilla › Working with windows in chrome code
you could check the location property of the opener and use opener.opener in case it's the extension manager window, but a better way is to use nsiwindowmediator: var wm = components.classes["@mozilla.org/appshell/window-mediator;1"] .getservice(components.interfaces.nsiwindowmediator); var browserwindow = wm.getmostrecentwindow("navigator:browser"); // read values from |browserwindow| you might be tempted to use a similar technique to apply the changes the user made in the options dialog, but a better way to do that is to use preferences observers.
Mozilla
Mozilla
the original navigator code base had large sections that were shared across multiple platforms.
Blocking By Domain - Plugins
Plugins › Blocking By Domain
plugin detection mechanisms such as navigator.mimetypes and navigator.plugins will also behave as if the plugin were not installed.
Flash Activation: Browser Comparison - Plugins
Plugins › Flash Activation: Browser Comparison
mozilla firefox google chrome microsoft edge setting name ask to activate html5 by default click-to-run 'application/x-shockwave-flash' in navigator.mimetypes by default when flash is inactive yes no no 'application/x-shockwave-flash' in navigator.mimetypes when user enables flash yes yes yes <object> with fallback content triggers ui yes, with exceptions no yes small/hidden flash triggers additional ui yes no no enabling flash automatically reloads the page no yes ...
URLs - Plugins
Plugins › Guide › URLs
in general, if a url works in the location box of the navigator, it works as a target for npn_geturl, except for the _self target.
Debugging service workers - Firefox Developer Tools
Tools › Application › Service workers
registration is done with a block of code along these lines, using the register() method: if('serviceworker' in navigator) { navigator.serviceworker .register('sw.js') .then(function() { console.log('service worker registered'); }); } if you get the path wrong, for example, you'll get an error in the web console giving you a hint as to what's wrong, which depends on what exactly is wrong with the code.
Responsive Design Mode - Firefox Developer Tools
Tools › Responsive Design Mode
the navigator.useragent property is set to the same value.
AbsoluteOrientationSensor - Web APIs
Web › API › AbsoluteOrientationSensor
const sensor = new absoluteorientationsensor(); promise.all([navigator.permissions.query({ name: "accelerometer" }), navigator.permissions.query({ name: "magnetometer" }), navigator.permissions.query({ name: "gyroscope" })]) .then(results => { if (results.every(result => result.state === "granted")) { sensor.start(); ...
AudioConfiguration - Web APIs
Web › API › AudioConfiguration
} }; // check support and performance navigator.mediacapabilities.decodinginfo(mediaconfig).then(result => { console.log('this configuration is ' + (result.supported ?
AudioContext.createMediaStreamDestination() - Web APIs
Web › API › AudioContext › createMediaStreamDestination
this stream can be used in a similar way as a mediastream obtained via navigator.getusermedia — it can, for example, be sent to a remote peer using the rtcpeerconnection addstream() method.
AudioContext.createMediaStreamTrackSource() - Web APIs
Web › API › AudioContext › createMediaStreamTrackSource
navigator.mediadevices.getusermedia ({audio: true, video: false}) .then(function(stream) { audio.srcobject = stream; audio.onloadedmetadata = function(e) { audio.play(); audio.muted = true; }; let audioctx = new audiocontext(); let source = audioctx.createmediastreamsource(stream); let biquadfilter = audioctx.createbiquadfilter(); biquadfilter.type = "lowshelf"; biquadfilter.frequ...
AuthenticatorAttestationResponse.attestationObject - Web APIs
Web › API › AuthenticatorAttestationResponse › attestationObject
examples var publickey = { challenge: /* from the server */, rp: { name: "example corp", id : "login.example.com" }, user: { id: new uint8array(16), name: "jdoe@example.com", displayname: "john doe" }, pubkeycredparams: [ { type: "public-key", alg: -7 } ] }; navigator.credentials.create({ publickey }) .then(function (newcredentialinfo) { var attestationobj = newcredentialinfo.response.attestationobject; // this will be a cbor encoded arraybuffer // do something with the response // (sending it back to the relying party server maybe?) }).catch(function (err) { console.error(err); }); specifications specification status ...
AuthenticatorAttestationResponse - Web APIs
Web › API › AuthenticatorAttestationResponse
examples var publickey = { challenge: /* from the server */, rp: { name: "example corp", id : "login.example.com" }, user: { id: new uint8array(16), name: "jdoe@example.com", displayname: "john doe" }, pubkeycredparams: [ { type: "public-key", alg: -7 } ] }; navigator.credentials.create({ publickey }) .then(function (newcredentialinfo) { var response = newcredentialinfo.response; // do something with the response // (sending it back to the relying party server maybe?) }).catch(function (err) { console.error(err); }); specifications specification status comment web authentication: an api for accessing public ...
BaseAudioContext.createGain() - Web APIs
Web › API › BaseAudioContext › createGain
the below snippet wouldn't work as is — for a complete working example, check out our voice-change-o-matic demo (view source.) <div> <button class="mute">mute button</button> </div> var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); var gainnode = audioctx.creategain(); var mute = document.queryselector('.mute'); var source; if (navigator.mediadevices.getusermedia) { navigator.mediadevices.getusermedia ( // constraints - only audio needed for this app { audio: true }, // success callback function(stream) { source = audioctx.createmediastreamsource(stream); }, // error callback function(err) { console.log('the following gum error occured: ' + err); } ); } else { console.log('getuse...
BatteryManager.charging - Web APIs
Web › API › BatteryManager › charging
example html content <div id="charging">(charging state unknown)</div> javascript content navigator.getbattery().then(function(battery) { var charging = battery.charging; document.queryselector('#charging').textcontent = charging ; }); specifications specification status comment battery status api candidate recommendation initial definition ...
BatteryManager.chargingTime - Web APIs
Web › API › BatteryManager › chargingTime
example html content <div id="chargingtime">(charging time unknown)</div> javascript content navigator.getbattery().then(function(battery) { var time = battery.chargingtime; document.queryselector('#chargingtime').textcontent = battery.chargingtime; }); specifications specification status comment battery status api candidate recommendation initial definition ...
BatteryManager.dischargingTime - Web APIs
Web › API › BatteryManager › dischargingTime
example html content <div id="dischargingtime">(discharging time unknown)</div> javascript content navigator.getbattery().then(function(battery) { var time = battery.dischargingtime; document.queryselector('#dischargingtime').textcontent = battery.dischargingtime; }); specifications specification status comment battery status api candidate recommendation initial definition ...
BatteryManager.level - Web APIs
Web › API › BatteryManager › level
example html content <div id="level">(battery level unknown)</div> javascript content navigator.getbattery().then(function(battery) { var level = battery.level; document.queryselector('#level').textcontent = level; }); specifications specification status comment battery status api candidate recommendation initial definition ...
BatteryManager.onchargingchange - Web APIs
Web › API › BatteryManager › onchargingchange
example html content <div id="level">(battery level unknown)</div> <div id="chargingtime">(charging time unknown)</div> javascript content navigator.getbattery().then(function(battery) { battery.onchargingchange = chargingchange(); function chargingchange() { document.queryselector('#level').textcontent = battery.level; document.queryselector('#chargingtime').textcontent = battery.chargingtime; } }); specifications specification status comment battery status api candidate recommendati...
BatteryManager.onchargingtimechange - Web APIs
Web › API › BatteryManager › onchargingtimechange
example html content <div id="level">(battery level unknown)</div> <div id="chargingtime">(charging time unknown)</div> javascript content navigator.getbattery().then(function(battery) { battery.onchargingtimechange = chargingtimechange(); function chargingtimechange(){ document.queryselector('#level').textcontent = battery.level; document.queryselector('#chargingtime').textcontent = battery.chargingtime; } }); specifications specification status comment battery status api can...
BatteryManager.ondischargingtimechange - Web APIs
Web › API › BatteryManager › ondischargingtimechange
example html content <div id="level">(battery level unknown)</div> <div id="chargingtime">(charging time unknown)</div> javascript content navigator.getbattery().then(function(battery) { battery.ondischargingtimechange = dischargingtimechange; function dischargingtimechange(){ document.queryselector('#level').textcontent = battery.level; document.queryselector('#chargingtime').textcontent = battery.chargingtime; } }); specifications specification status comment battery status api...
BatteryManager - Web APIs
Web › API › BatteryManager
the navigator.getbattery() method returns a battery promise that is resolved in a batterymanager interface which you can use to interact with the battery status api.
Bluetooth.requestDevice() - Web APIs
Web › API › Bluetooth › requestDevice
let options = { filters: [ {services: ['heart_rate']}, {services: [0x1802, 0x1803]}, {services: ['c48e6067-5295-48d3-8d5c-0395f61792b1']}, {name: 'examplename'}, {nameprefix: 'prefix'} ], optionalservices: ['battery_service'] } navigator.bluetooth.requestdevice(options).then(function(device) { console.log('name: ' + device.name); // do something with the device.
Bluetooth - Web APIs
Web › API › Bluetooth
a bluetoothdevice representing the beacon would be available through navigator.bluetooth.referringdevice.
BluetoothCharacteristicProperties - Web APIs
Web › API › BluetoothCharacteristicProperties
let device = await navigator.bluetooth.requestdevice({ filters: [{services: ['heart_rate']}] }); let gatt = await device.gatt.connect(); let service = await gatt.getprimaryservice('heart_rate'); let characteristic = await service.getcharacteristic('heart_rate_measurement'); if (characteristic.properties.notify) { characteristics.addeventlistener('characteristicvaluechanged', function(event) { console.log(`recei...
Client.type - Web APIs
Web › API › Client › type
a document) function sendmessage(message) { return new promise(function(resolve, reject) { // note that this is the serviceworker.postmessage version navigator.serviceworker.controller.postmessage(message); window.serviceworker.onmessage = function(e) { resolve(e.data); }; }); } // controlling service worker self.addeventlistener("message", function(e) { // e.source is a client object e.source.postmessage("hello!
Clients.claim() - Web APIs
Web › API › Clients › claim
this triggers a "controllerchange" event on navigator.serviceworker in any clients that become controlled by this service worker.
Clipboard - Web APIs
Web › API › Clipboard
the system clipboard is exposed through the global navigator.clipboard property.
ClipboardItem() - Web APIs
Web › API › ClipboardItem › ClipboardItem
async function writeclipimg() { try { const imgurl = '/myimage.png'; const data = await fetch(imgurl); const blob = await data.blob(); await navigator.clipboard.write([ new clipboarditem({ [blob.type]: blob }) ]); console.log('fetched image copied.'); } catch(err) { console.error(err.name, err.message); } } specifications specification status comment clipboard api and eventsthe definition of 'clipboarditem' in that specification.
ClipboardItem.getType() - Web APIs
Web › API › ClipboardItem › getType
async function getclipboardcontents() { try { const clipboarditems = await navigator.clipboard.read(); for (const clipboarditem of clipboarditems) { for (const type of clipboarditem.types) { const blob = await clipboarditem.gettype(type); // we can now use blob here } } } catch (err) { console.error(err.name, err.message); } } specifications specification status comment clipboard api and eventsthe definiti...
ClipboardItem.types - Web APIs
Web › API › ClipboardItem › types
async function getclipboardcontents() { try { const clipboarditems = await navigator.clipboard.read(); for (const clipboarditem of clipboarditems) { for (const type of clipboarditem.types) { const blob = await clipboarditem.gettype(type); // we can now use blob here } } } catch (err) { console.error(err.name, err.message); } } specifications specification status comment clipboard api and eventsthe definiti...
Clipboard API - Web APIs
Web › API › Clipboard API
accessing the clipboard instead of creating a clipboard object through instantiation, you access the system clipboard through the navigator.clipboard global: navigator.clipboard.readtext().then( cliptext => document.queryselector(".editor").innertext += cliptext); this snippet fetches the text from the clipboard and appends it to the first element found with the class editor.
ContentIndex.add() - Web APIs
Web › API › ContentIndex › add
post-1', url: '/posts/amet.html', title: 'amet consectetur adipisicing', description: 'repellat et quia iste possimus ducimus aliquid a aut eaque nostrum.', icons: [{ src: '/media/dark.png', sizes: '128x128', type: 'image/png', }], category: 'article' }; // our asynchronous function to add indexed content async function registercontent(data) { const registration = await navigator.serviceworker.ready; // feature detect content index if (!registration.index) { return; } // register content try { await registration.index.add(data); } catch (e) { console.log('failed to register content: ', e.message); } } the add method can also be used within the service worker scope.
ContentIndex.delete() - Web APIs
Web › API › ContentIndex › delete
async function unregistercontent(article) { // reference registration const registration = await navigator.serviceworker.ready; // feature detect content index if (!registration.index) return; // unregister content from index await registration.index.delete(article.id); } the delete method can also be used within the service worker scope.
ContentIndex.getAll() - Web APIs
Web › API › ContentIndex › getAll
async function createreadinglist() { // access our service worker registration const registration = await navigator.serviceworker.ready; // get our index entries const entries = await registration.index.getall(); // create a containing element const readinglistelem = document.createelement('div'); // test for entries if (!array.length) { // if there are no entries, display a message const message = document.createelement('p'); message.innertext = 'you currently have no articles save...
Credential Management API - Web APIs
Web › API › Credential Management API
this interfaces is accessible from navigator.credentials.
CredentialsContainer - Web APIs
Web › API › CredentialsContainer
this interface is accessible from navigator.credentials.
DeprecationReportBody - Web APIs
Web › API › DeprecationReportBody
properties id a string representing the deprecated feature that generated the report, for example navigatorgetusermedia.
Device Memory API - Web APIs
Web › API › Device Memory API
javascript api you may query the approximate amount of ram device has by retreiving navigator.devicememory var ram1 = window.navigator.devicememory; var ram2 = navigator.devicememory; both of these will return the same result.
Document.onoffline - Web APIs
Web › API › Document › onoffline
the document.onoffline event handler is called when an offline is fired on the <body> element and bubbles up, when navigator.online property changes and becomes false.
Document.ononline - Web APIs
Web › API › Document › ononline
window.navigator.online returns boolean true if the browser is online and false if it is definitely offline (disconnected from the network).
Document.plugins - Web APIs
Web › API › Document › plugins
for a list of installed plugins, use navigatorplugins.plugins instead.
ExtendableMessageEvent - Web APIs
Web › API › ExtendableMessageEvent
// in the page being controlled if (navigator.serviceworker) { navigator.serviceworker.register('service-worker.js'); navigator.serviceworker.addeventlistener('message', event => { // event is a messageevent object console.log(`the service worker sent me a message: ${event.data}`); }); navigator.serviceworker.ready.then( registration => { registration.active.postmessage("hi service worker"); }); } the service worke...
FederatedCredential - Web APIs
Web › API › FederatedCredential
examples var cred = new federatedcredential({ id: id, name: name, provider: 'https://account.google.com', iconurl: iconurl }); // store it navigator.credentials.store(cred) .then(function() { // do something else.
GainNode.gain - Web APIs
Web › API › GainNode › gain
the below snippet wouldn't work as is — for a complete working example, check out our voice-change-o-matic demo (view source.) <div> <button class="mute">mute button</button> </div> var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); var gainnode = audioctx.creategain(); var mute = document.queryselector('.mute'); var source; if (navigator.mediadevices.getusermedia) { navigator.mediadevices.getusermedia ( // constraints - only audio needed for this app { audio: true }, // success callback function(stream) { source = audioctx.createmediastreamsource(stream); }, // error callback function(err) { console.log('the following gum error occured: ' + err); } ); } else { console.log('getuse...
GainNode - Web APIs
Web › API › GainNode
the below snippet wouldn't work as is — for a complete working example, check out our voice-change-o-matic demo (view source.) <div> <button class="mute">mute button</button> </div> var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); var gainnode = audioctx.creategain(); var mute = document.queryselector('.mute'); var source; if (navigator.mediadevices.getusermedia) { navigator.mediadevices.getusermedia ( // constraints - only audio needed for this app { audio: true }, // success callback function(stream) { source = audioctx.createmediastreamsource(stream); }, // error callback function(err) { console.log('the following gum error occured: ' + err); } ); } else { console.log('getuse...
Gamepad.axes - Web APIs
Web › API › Gamepad › axes
syntax readonly attribute double[] axes; example function gameloop() { if(navigator.webkitgetgamepads) { var gp = navigator.webkitgetgamepads()[0]; } else { var gp = navigator.getgamepads()[0]; } if(gp.axes[0] != 0) { b -= gp.axes[0]; } else if(gp.axes[1] != 0) { a += gp.axes[1]; } else if(gp.axes[2] != 0) { b += gp.axes[2]; } else if(gp.axes[3] != 0) { a -= gp.axes[3]; } ball.style.left = a*2 + "px"; ball.style.top = b*2 + "px"; va...
Gamepad.connected - Web APIs
Web › API › Gamepad › connected
syntax readonly attribute boolean connected; example var gp = navigator.getgamepads()[0]; console.log(gp.connected); value a boolean.
Gamepad.id - Web APIs
Web › API › Gamepad › id
syntax readonly attribute domstring id; example window.addeventlistener("gamepadconnected", function() { var gp = navigator.getgamepads()[0]; gamepadinfo.innerhtml = "gamepad connected at index " + gp.index + ": " + gp.id + "."; }); value a string.
Gamepad.index - Web APIs
Web › API › Gamepad › index
syntax readonly attribute long index; example window.addeventlistener("gamepadconnected", function() { var gp = navigator.getgamepads()[0]; gamepadinfo.innerhtml = "gamepad connected at index " + gp.index + ": " + gp.id + "."; }); value a number.
Gamepad.mapping - Web APIs
Web › API › Gamepad › mapping
syntax readonly attribute domstring mapping; example var gp = navigator.getgamepads()[0]; console.log(gp.mapping); value a string.
Gamepad.timestamp - Web APIs
Web › API › Gamepad › timestamp
syntax readonly attribute domhighrestimestamp timestamp; example var gp = navigator.getgamepads()[0]; console.log(gp.timestamp); value a domhighrestimestamp.
Gamepad - Web APIs
Web › API › Gamepad
a gamepad object can be returned in one of two ways: via the gamepad property of the gamepadconnected and gamepaddisconnected events, or by grabbing any position in the array returned by the navigator.getgamepads() method.
GamepadButton.pressed - Web APIs
Web › API › GamepadButton › pressed
syntax var ispressed = navigator.getgamepads()[0].pressed; example var gp = navigator.getgamepads()[0]; // get the first gamepad object if(gp.buttons[0].pressed == true) { // respond to button being pressed } value a boolean.
GamepadButton.value - Web APIs
Web › API › GamepadButton › value
syntax readonly attribute double value; example var gp = navigator.getgamepads()[0]; if(gp.buttons[0].value > 0) { // respond to analog button being pressed in } value a double.
Gamepad API - Web APIs
Web › API › Gamepad API
extensions to other interfaces navigator navigator.getgamepads() an extension to the navigator object that returns an array of gamepad objects, one for each connected gamepad.
Geolocation - Web APIs
Web › API › Geolocation
an object with this interface is obtained using the navigator.geolocation property implemented by the navigator object.
GeolocationCoordinates.longitude - Web APIs
Web › API › GeolocationCoordinates › longitude
let button = document.getelementbyid("get-location"); let lattext = document.getelementbyid("latitude"); let longtext = document.getelementbyid("longitude"); button.addeventlistener("click", function() { navigator.geolocation.getcurrentposition(function(position) { let lat = position.coords.latitude; let long = position.coords.longitude; lattext.innertext = lat.tofixed(2); longtext.innertext = long.tofixed(2); }); }); after setting up variables to more conveniently reference the button element and the two elements into which the latitude and logitude will be drawn, the event listener is...
HMDVRDevice - Web APIs
Web › API › HMDVRDevice
navigator.getvrdevices().then(function(devices) { for (var i = 0; i < devices.length; ++i) { if (devices[i] instanceof hmdvrdevice) { ghmd = devices[i]; break; } } if (ghmd) { for (var i = 0; i < devices.length; ++i) { if (devices[i] instanceof positionsensorvrdevice && devices[i].hardwareunitid === ghmd.hardwareunitid) { gpositionsensor = devices[i]; br...
HTMLMediaElement.setSinkId() - Web APIs
Web › API › HTMLMediaElement › setSinkId
exceptions exception explanation domexception no permission to use the requested device examples const devices = await navigator.mediadevices.enumeratedevices(); const audiodevices = devices.filter(device => device.kind === 'audiooutput'); const audio = document.createelement('audio'); await audio.setsinkid(audiodevices[0].deviceid); console.log('audio is being played on ' + audio.sinkid); specifications specification status comment audio output devices apithe definition of 'sinkid' in that speci...
ImageCapture() constructor - Web APIs
Web › API › ImageCapture › ImageCapture
navigator.mediadevices.getusermedia({video: true}) .then(mediastream => { document.queryselector('video').srcobject = mediastream const track = mediastream.getvideotracks()[0]; imagecapture = new imagecapture(track); }) .catch(error => console.log(error)); specifications specification status comment mediastream image capturethe definition of 'imagecapture' in tha...
ImageCapture.getPhotoCapabilities() - Web APIs
Web › API › ImageCapture › getPhotoCapabilities
const input = document.queryselector('input[type="range"]'); var imagecapture; navigator.mediadevices.getusermedia({video: true}) .then(mediastream => { document.queryselector('video').srcobject = mediastream; const track = mediastream.getvideotracks()[0]; imagecapture = new imagecapture(track); return imagecapture.getphotocapabilities(); }) .then(photocapabilities => { const settings = imagecapture.track.getsettings(); input.min = photocapabilities.imagewidth.min; i...
ImageCapture.getPhotoSettings() - Web APIs
Web › API › ImageCapture › getPhotoSettings
const input = document.queryselector('input[type="range"]'); var imagecapture; navigator.mediadevices.getusermedia({video: true}) .then(mediastream => { document.queryselector('video').srcobject = mediastream; const track = mediastream.getvideotracks()[0]; imagecapture = new imagecapture(track); return imagecapture.getphotocapabilities(); }) .then(photocapabilities => { const settings = imagecapture.track.getsettings(); input.min = photocapabilities.imagewidth.min; i...
ImageCapture - Web APIs
Web › API › ImageCapture
var imagecapture; function ongetusermediabuttonclick() { navigator.mediadevices.getusermedia({video: true}) .then(mediastream => { document.queryselector('video').srcobject = mediastream; const track = mediastream.getvideotracks()[0]; imagecapture = new imagecapture(track); }) .catch(error => console.log(error)); } function ongrabframebuttonclick() { imagecapture.grabframe() .then(imagebitmap => { const canvas = document.queryselector...
Keyboard.getLayoutMap() - Web APIs
Web › API › Keyboard › getLayoutMap
var keyboard = navigator.keyboard; keyboard.getlayoutmap() .then(keyboardlayoutmap => { var upkey = keyboardlayoutmap.get('keyw'); window.alert('press ' + upkey + ' to move up.'); }) specifications specification status comment keyboard mapthe definition of 'getlayoutmap()' in that specification.
Keyboard - Web APIs
Web › API › Keyboard
if (navigator.keyboard) { var keyboard = navigator.keyboard; keyboard.getlayoutmap() .then(keyboardlayoutmap => { var upkey = keyboardlayoutmap.get('keyw'); window.alert('press ' + upkey + ' to move up.'); }); } else { // do something else.
KeyboardLayoutMap.get() - Web APIs
Web › API › KeyboardLayoutMap › get
var keyboard = navigator.keyboard; keyboard.getlayoutmap() .then(keyboardlayoutmap => { var upkey = keyboardlayoutmap.get('keyw'); window.alert('press ' + upkey + ' to move up.'); } specifications specification status comment keyboard mapthe definition of 'get()' in that specification.
KeyboardLayoutMap - Web APIs
Web › API › KeyboardLayoutMap
var keyboard = navigator.keyboard; keyboard.getlayoutmap() .then(keyboardlayoutmap => { var upkey = keyboardlayoutmap.get('keyw'); window.alert('press ' + upkey + ' to move up.'); }) specifications specification status comment keyboard mapthe definition of 'keyboardlayoutmap' in that specification.
LocalFileSystem - Web APIs
Web › API › LocalFileSystem
so to request storage, you need to do something like the following: var requestedbytes = 1024*1024*10; // 10mb navigator.webkitpersistentstorage.requestquota ( requestedbytes, function(grantedbytes) { window.requestfilesystem(persistent, grantedbytes, oninitfs, errorhandler); }, function(e) { console.log('error', e); } ); your user must grant your app permission to store data locally before your app can use persistent storage.
LockManager.query() - Web APIs
Web › API › LockManager › query
example const state = await navigator.locks.query(); for (const lock of state.held) { console.log(`held lock: name ${lock.name}, mode ${lock.mode}`); } for (const request of state.pending) { console.log(`requested lock: name ${request.name}, mode ${request.mode}`); } specifications specification status comment web locks apithe definition of 'query()' in that specification.
LockManager - Web APIs
Web › API › LockManager
to get an instance of lockmanager, call navigator.locks.
MIDIAccess - Web APIs
Web › API › MIDIAccess
examples navigator.requestmidiaccess() .then(function(access) { // get lists of available midi controllers const inputs = access.inputs.values(); const outputs = access.outputs.values(); access.onstatechange = function(e) { // print information about the (dis)connected midi controller console.log(e.port.name, e.port.manufacturer, e.port.state); }; }); specifications ...
MIDIMessageEvent - Web APIs
Web › API › MIDIMessageEvent
examples // printing all messages to console navigator.requestmidiaccess().then(midiaccess => { array.from(midiaccess.inputs).foreach(input => { input[1].onmidimessage = console.log; }) }); specifications specification status comment web midi apithe definition of 'midimessageevent' in that specification.
MediaCapabilities.decodingInfo() - Web APIs
Web › API › MediaCapabilities › decodingInfo
}, }; // check support and performance navigator.mediacapabilities.decodinginfo(mediaconfig).then(result => { console.log('this configuration is ' + (result.supported ?
MediaCapabilities.encodingInfo() - Web APIs
Web › API › MediaCapabilities › encodingInfo
} }; // check support and performance navigator.mediacapabilities.encodinginfo(mediaconfig).then(result => { console.log('this configuration is ' + (result.supported ?
MediaCapabilities - Web APIs
Web › API › MediaCapabilities
the information is accessed through the mediacapabilities property of the navigator interface.
MediaCapabilitiesInfo - Web APIs
Web › API › MediaCapabilitiesInfo
example // mediaconfiguration to be tested const mediaconfig = { type : 'file', audio : { contenttype : "audio/ogg", channels : 2, bitrate : 132700, samplerate : 5200 }, }; // check support and performance navigator.mediacapabilities.decodinginfo(mediaconfig).then(result => { // result contains the media capabilities information console.log('this configuration is ' + (result.supported ?
MediaDecodingConfiguration - Web APIs
Web › API › MediaDecodingConfiguration
} }; // check support and performance navigator.mediacapabilities.decodinginfo(mediaconfig).then(result => { console.log('this configuration is ' + (result.supported ?
MediaDevices: devicechange event - Web APIs
Web › API › MediaDevices › devicechange event
bubbles no cancelable no interface event event handler ondevicechange example you can use the devicechange event in an addeventlistener method: navigator.mediadevices.addeventlistener('devicechange', function(event) { updatedevicelist(); }); or use the ondevicechange event handler property: navigator.mediadevices.ondevicechange = function(event) { updatedevicelist(); } specifications specification status media capture and streamsthe definition of 'devicechange' in that specification.
MediaDevices - Web APIs
Web › API › MediaDevices
var video = document.queryselector('video'); var constraints = window.constraints = { audio: false, video: true }; var errorelement = document.queryselector('#errormsg'); navigator.mediadevices.getusermedia(constraints) .then(function(stream) { var videotracks = stream.getvideotracks(); console.log('got stream with constraints:', constraints); console.log('using video device: ' + videotracks[0].label); stream.onremovetrack = function() { console.log('stream ended'); }; window.stream = stream; // make variable available to browser console video.srcobject = ...
MediaEncodingConfiguration - Web APIs
Web › API › MediaEncodingConfiguration
} }; // check support and performance navigator.mediacapabilities.encodinginfo(mediaconfig).then(result => { console.log('this configuration is ' + (result.supported ?
MediaKeySystemAccess - Web APIs
Web › API › MediaKeySystemAccess
you can request an instance of this object using the navigator.requestmediakeysystemaccess() method.
MediaRecorder: error event - Web APIs
Web › API › MediaRecorder › error event
examples using addeventlistener to listen for error events: async function record() { const stream = await navigator.mediadevices.getusermedia({audio: true}); const recorder = new mediarecorder(stream); recorder.addeventlistener('error', (event) => { console.error(`error recording stream: ${event.error.name}`) }); recorder.start(); } record(); the same, but using the onerror event handler property: async function record() { const stream = await navigator.mediadevices.getusermedia(...
MediaRecorder.mimeType - Web APIs
Web › API › MediaRecorder › mimeType
if (navigator.mediadevices) { console.log('getusermedia supported.'); var constraints = { audio: true, video: true }; var chunks = []; navigator.mediadevices.getusermedia(constraints) .then(function(stream) { var options = { audiobitspersecond: 128000, videobitspersecond: 2500000, mimetype: 'video/mp4' } var mediarecorder = new mediarecorder(stream,option...
MediaRecorder.stream - Web APIs
Web › API › MediaRecorder › stream
example if (navigator.getusermedia) { console.log('getusermedia supported.'); navigator.getusermedia ( // constraints - only audio needed for this app { audio: true }, // success callback function(stream) { var mediarecorder = new mediarecorder(stream); var mystream = mediarecorder.stream; console.log(mystream); ...
MediaRecorder - Web APIs
Web › API › MediaRecorder
example if (navigator.mediadevices) { console.log('getusermedia supported.'); var constraints = { audio: true }; var chunks = []; navigator.mediadevices.getusermedia(constraints) .then(function(stream) { var mediarecorder = new mediarecorder(stream); visualize(stream); record.onclick = function() { mediarecorder.start(); console.log(mediarecorder.state); console.log("record...
MediaSession.playbackState - Web APIs
Web › API › MediaSession › playbackState
example the following example sets up event handlers, for pausing and playing: var audio = document.queryselector("#player"); audio.src = "song.mp3"; navigator.mediasession.setactionhandler('play', play); navigator.mediasession.setactionhandler('pause', pause); function play() { audio.play(); navigator.mediasession.playbackstate = "playing"; } function pause() { audio.pause(); navigator.mediasession.playbackstate = "paused"; } specifications specification status comment media session standardthe definition of 'pla...
MediaSettingsRange - Web APIs
Web › API › MediaSettingsRange
const input = document.queryselector('input[type="range"]'); var imagecapture; navigator.mediadevices.getusermedia({video: true}) .then(mediastream => { document.queryselector('video').srcobject = mediastream; const track = mediastream.getvideotracks()[0]; imagecapture = new imagecapture(track); return imagecapture.getphotocapabilities(); }) .then(photocapabilities => { const settings = imagecapture.track.getsettings(); input.min = photocapabilities.imagewidth.min; i...
active - Web APIs
Web › API › MediaStream › active
var promise = navigator.mediadevices.getusermedia({ audio: true, video: true }); promise.then(function(stream) { var startbtn = document.queryselector('#startbtn'); startbtn.disabled = stream.active; };) specifications specification status comment media capture and streamsthe definition of 'active' in that specification.
MediaStream.getAudioTracks() - Web APIs
Web › API › MediaStream › getAudioTracks
navigator.mediadevices.getusermedia({audio: true, video: true}) .then(mediastream => { document.queryselector('video').srcobject = mediastream; // stop the audio stream after 5 seconds settimeout(() => { const tracks = mediastream.getaudiotracks() tracks[0].stop() }, 5000) }) specifications specification status comment media capture and streamsthe definition o...
MediaStream.getTracks() - Web APIs
Web › API › MediaStream › getTracks
example navigator.mediadevices.getusermedia({audio: false, video: true}) .then(mediastream => { document.queryselector('video').srcobject = mediastream; // stop the stream after 5 seconds settimeout(() => { const tracks = mediastream.gettracks() tracks[0].stop() }, 5000) }) specifications specification status comment media capture and streamsthe definition of 'gettracks()' in that specification.
MediaStream.getVideoTracks() - Web APIs
Web › API › MediaStream › getVideoTracks
var imagecapture; navigator.mediadevices.getusermedia({video: true}) .then(mediastream => { document.queryselector('video').srcobject = mediastream; const track = mediastream.getvideotracks()[0]; imagecapture = new imagecapture(track); return imagecapture.getphotocapabilities(); }) specifications specification status comment media capture and streamsthe definition of 'getvideotracks()' in...
MediaStream.id - Web APIs
Web › API › MediaStream › id
syntax var id = mediastream.id; example var p = navigator.mediadevices.getusermedia({ audio: true, video: true }); p.then(function(stream) { console.log(stream.id); }) specifications specification status comment media capture and streamsthe definition of 'mediastream.id' in that specification.
MediaStreamAudioDestinationNode - Web APIs
Web › API › MediaStreamAudioDestinationNode
the mediastreamaudiodestinationnode interface represents an audio destination consisting of a webrtc mediastream with a single audiomediastreamtrack, which can be used in a similar way to a mediastream obtained from navigator.getusermedia.
MediaStreamAudioSourceNode() - Web APIs
Web › API › MediaStreamAudioSourceNode › MediaStreamAudioSourceNode
// define variables var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); // getusermedia block - grab stream // put it into a mediastreamaudiosourcenode if (navigator.mediadevices.getusermedia) { navigator.mediadevices.getusermedia ( // constraints: audio and video for this app { audio: true, video: false }).then(function(stream) { var options = { mediastream : stream } var source = new mediastreamaudiosourcenode(audioctx, options); source.connect(audioctx.destination); }).
MediaStreamTrack.applyConstraints() - Web APIs
Web › API › MediaStreamTrack › applyConstraints
const constraints = { width: {min: 640, ideal: 1280}, height: {min: 480, ideal: 720}, advanced: [ {width: 1920, height: 1280}, {aspectratio: 1.333} ] }; navigator.mediadevices.getusermedia({ video: true }) .then(mediastream => { const track = mediastream.getvideotracks()[0]; track.applyconstraints(constraints) .then(() => { // do something with the track such as using the image capture api.
MediaStreamTrackAudioSourceNode() - Web APIs
Web › API › MediaStreamTrackAudioSourceNode › MediaStreamTrackAudioSourceNode
let audioctx = new (window.audiocontext || window.webkitaudiocontext)(); if (navigator.mediadevices.getusermedia) { navigator.mediadevices.getusermedia ( { audio: true, video: false }).then(function(stream) { let options = { mediastreamtrack: stream.getaudiotracks()[0]; } let source = new mediastreamtrackaudiosourcenode(audioctx, options); source.connect(audioctx.destination); }).catch(function(err) { console.log('the...
MediaStreamTrackAudioSourceOptions.mediaStreamTrack - Web APIs
Web › API › MediaStreamTrackAudioSourceOptions › mediaStreamTrack
let audioctx = new (window.audiocontext || window.webkitaudiocontext)(); if (navigator.mediadevices.getusermedia) { navigator.mediadevices.getusermedia ( { audio: true, video: false }).then(function(stream) { let options = { mediastreamtrack: stream.getaudiotracks()[0]; } let source = new mediastreamtrackaudiosourcenode(audioctx, options); source.connect(audioctx.destination); }).catch(function(err) { console.log('the...
MediaStream Image Capture API - Web APIs
Web › API › MediaStream Image Capture API
navigator.mediadevices.getusermedia({ video: true }) .then(mediastream => { // do something with the stream.
MediaTrackSupportedConstraints.frameRate - Web APIs
Web › API › MediaTrackSupportedConstraints › frameRate
javascript let result = document.getelementbyid("result"); if (navigator.mediadevices.getsupportedconstraints().framerate) { result.innerhtml = "supported!"; } else { result.innerhtml = "not supported!"; } html <div id="result"> </div> css #result { font: 14px "arial", sans-serif; } result the output, showing if your browser supports the framerate constraint, is: while this example is trivial, you can replace the simple output of "supported" v...
Media Capabilities API - Web APIs
Web › API › Media Capabilities API
if ('mediacapabilities' in navigator) { const audiofileconfiguration = { type : 'file', audio : { contenttype: "audio/mp3", channels: 2, bitrate: 132700, samplerate: 5200 } }; navigator.mediacapabilities.decodinginfo(audiofileconfiguration).then(result => { console.log('this configuration is ' + (result.supported ?
Media Capture and Streams API (Media Stream) - Web APIs
Web › API › Media Streams API
blobevent canvascapturemediastreamtrack inputdeviceinfo mediadevicekind mediadeviceinfo mediadevices mediastream mediastreamconstraints mediastreamevent mediastreamtrack mediastreamtrackevent mediatrackcapabilities mediatrackconstraints mediatracksettings mediatracksupportedconstraints navigatorusermedia navigatorusermediaerror overconstrainederror url early versions of the media capture and streams api specification included separate audiostreamtrack and videostreamtrack interfaces—each based upon mediastreamtrack—which represented streams of those types.
Microsoft API extensions - Web APIs
Web › API › Microsoft Extensions
deoformatchanged onmsvideoframestepcompleted onmsvideooptimallayoutchanged msfirstpaint pinned sites apis mssitemodeevent mssitemodejumplistitemremoved msthumbnailclick other apis x-ms-aria-flowfrom x-ms-acceleratorkey x-ms-format-detection mscaching mscachingenabled mscapslockwarningoff event.msconverturl() mselementresize document.mselementsfromrect() msisstatichtml navigator.mslaunchuri() mslaunchuricallback element.msmatchesselector() msprotocols msputpropertyenabled mswriteprofilermark ...
MimeType - Web APIs
Web › API › MimeType
navigatorplugins.mimetypes returns an array of this object.
NetworkInformation.downlinkMax - Web APIs
Web › API › NetworkInformation › downlinkMax
function logconnectiontype() { var connectiontype = 'not supported'; var downlinkmax = 'not supported'; if ('connection' in navigator) { connectiontype = navigator.connection.effectivetype; if ('downlinkmax' in navigator.connection) { downlinkmax = navigator.connection.downlinkmax; } } console.log('current connection type: ' + connectiontype + ' (downlink max: ' + downlinkmax + ')'); } logconnectiontype(); navigator.connection.addeventlistener('change', logconnectiontype); specifications ...
NetworkInformation - Web APIs
Web › API › NetworkInformation
it is instead accessed through the connection property of the navigator interface.
OrientationSensor - Web APIs
Web › API › OrientationSensor
const sensor = new absoluteorientationsensor(); promise.all([navigator.permissions.query({ name: "accelerometer" }), navigator.permissions.query({ name: "magnetometer" }), navigator.permissions.query({ name: "gyroscope" })]) .then(results => { if (results.every(result => result.state === "granted")) { sensor.start(); ...
PasswordCredential - Web APIs
Web › API › PasswordCredential › PasswordCredential
navigator.credentials.store(creds) .then(function(creds) { // do something with the credentials if you need to.
PasswordCredential.additionalData - Web APIs
Web › API › PasswordCredential › additionalData
navigator.credentials.get(options).then(function(creds) { if (creds.type == 'password') { var form = new formdata(); var csrf_token = document.queryselector('csrf_token').value; form.append('csrf_token', csrf_token); creds.additionaldata = form; fetch('https://www.example.com', { method: 'post', credentials: creds }); }; }); specifications specification ...
PasswordCredential - Web APIs
Web › API › PasswordCredential
examples var cred = new passwordcredential({ id: id, password: password, name: name, iconurl: iconurl }); navigator.credentials.store(cred) .then(function() { // do something else.
PermissionStatus.onchange - Web APIs
Web › API › PermissionStatus › onchange
}) example navigator.permissions.query({name:'geolocation'}).then(function(permissionstatus) { console.log('geolocation permission state is ', permissionstatus.state); permissionstatus.onchange = function() { console.log('geolocation permission state has changed to ', this.state); }; }); specification specification status comment permissionsthe definition of 'onchange' in that specification.
PermissionStatus.state - Web APIs
Web › API › PermissionStatus › state
syntax var permission = permissionstatus.state; example navigator.permissions.query({name:'geolocation'}).then(function(permissionstatus) { console.log('geolocation permission state is ', permissionstatus.state); permissionstatus.onchange = function() { console.log('geolocation permission status has changed to ', this.state); }; }); specification specification status comment permissionsthe definition of 'state' in that specification.
PermissionStatus - Web APIs
Web › API › PermissionStatus
example navigator.permissions.query({name:'geolocation'}).then(function(permissionstatus) { console.log('geolocation permission status is ', permissionstatus.state); permissionstatus.onchange = function() { console.log('geolocation permission status has changed to ', this.state); }; }); specification specification status comment permissionsthe definition of 'permissionstatus' in...
Permissions - Web APIs
Web › API › Permissions
example navigator.permissions.query({name:'geolocation'}).then(function(result) { if (result.state === 'granted') { showlocalnewswithgeolocation(); } else if (result.state === 'prompt') { showbuttontoenablelocalnews(); } // don't do anything if the permission was denied.
PhotoCapabilities - Web APIs
Web › API › PhotoCapabilities
const input = document.queryselector('input[type="range"]'); var imagecapture; navigator.mediadevices.getusermedia({video: true}) .then(mediastream => { document.queryselector('video').srcobject = mediastream; const track = mediastream.getvideotracks()[0]; imagecapture = new imagecapture(track); return imagecapture.getphotocapabilities(); }) .then(photocapabilities => { const settings = imagecapture.track.getsettings(); input.min = photocapabilities.imagewidth.min; i...
Proximity Events - Web APIs
Web › API › Proximity Events
example window.addeventlistener('userproximity', function(event) { if (event.near) { // let's power off the screen navigator.mozpower.screenenabled = false; } else { // otherwise, let's power on the screen navigator.mozpower.screenenabled = true; } }); specifications specification status comment proximity sensorthe definition of 'proximity events' in that specification.
PublicKeyCredential.id - Web APIs
Web › API › PublicKeyCredential › id
examples var publickey = { challenge: new uint8array(26) /* this actually is given from the server */, rp: { name: "example corp", id : "login.example.com" }, user: { id: new uint8array(26), /* to be changed for each user */ name: "jdoe@example.com", displayname: "john doe", }, pubkeycredparams: [ { type: "public-key", alg: -7 } ] }; navigator.credentials.create({ publickey }) .then(function (newcredentialinfo) { var id = newcredentialinfo.id; // do something with the id // send attestation response and client extensions // to the server to proceed with the registration // of the credential }).catch(function (err) { console.error(err); }); specifications specification status comment ...
PublicKeyCredential.rawId - Web APIs
Web › API › PublicKeyCredential › rawId
examples var options = { challenge: new uint8array(26) /* from the server */, rp: { name: "example corp", id : "login.example.com" }, user: { id: new uint8array(26), /* to be changed for each user */ name: "jdoe@example.com", displayname: "john doe", }, pubkeycredparams: [ { type: "public-key", alg: -7 } ] }; navigator.credentials.create({ publickey: options }) .then(function (pubkeycredential) { var rawid = pubkeycredential.rawid; // do something with rawid }).catch(function (err) { // deal with any error }); specifications specification status comment web authentication: an api for accessing public key credentials level 1the definition of 'rawid' in that specificati...
PublicKeyCredential.response - Web APIs
Web › API › PublicKeyCredential › response
examples var options = { challenge: new uint8array(16) /* from the server */, rp: { name: "example corp", id : "login.example.com" }, user: { id: new uint8array(16) /* from the server */, name: "jdoe@example.com", displayname: "john doe" }, pubkeycredparams: [ { type: "public-key", alg: -7 } ] }; navigator.credentials.create({ publickey: options }) .then(function (pubkeycredential) { var response = pubkeycredential.response; var clientextresults = pubkeycredential.getclientextensionresults(); // send response and client extensions to the server so that it can validate // and create credentials }).catch(function (err) { // deal with any error }); specifications spec...
PublicKeyCredentialCreationOptions.attestation - Web APIs
Web › API › PublicKeyCredentialCreationOptions › attestation
key = { attestation: "indirect", challenge: new uint8array(26) /* this actually is given from the server */, rp: { name: "example corp", id : "login.example.com" }, user: { id: new uint8array(26), /* to be changed for each user */ name: "jdoe@example.com", displayname: "john doe", }, pubkeycredparams: [ { type: "public-key", alg: -7 } ] }; navigator.credentials.create({ publickey }) .then(function (newcredentialinfo) { // send attestation response and client extensions // to the server to proceed with the registration // of the credential }).catch(function (err) { console.error(err); }); specifications specification status comment web authentication: an api for accessing public key credent...
PublicKeyCredentialCreationOptions.authenticatorSelection - Web APIs
Web › API › PublicKeyCredentialCreationOptions › authenticatorSelection
key: true, userverification: "required" }, challenge: new uint8array(26) /* this actually is given from the server */, rp: { name: "example corp", id : "login.example.com" }, user: { id: new uint8array(26), /* to be changed for each user */ name: "jdoe@example.com", displayname: "john doe", }, pubkeycredparams: [ { type: "public-key", alg: -7 } ] }; navigator.credentials.create({ publickey }) .then(function (newcredentialinfo) { // send attestation response and client extensions // to the server to proceed with the registration // of the credential }).catch(function (err) { console.error(err); }); specifications specification status comment web authentication: an api for accessing public key credent...
PublicKeyCredentialCreationOptions.excludeCredentials - Web APIs
Web › API › PublicKeyCredentialCreationOptions › excludeCredentials
: new uint8array(26) /* another id */ } ], challenge: new uint8array(26) /* this actually is given from the server */, rp: { name: "example corp", id : "login.example.com" }, user: { id: new uint8array(26), /* to be changed for each user */ name: "jdoe@example.com", displayname: "john doe", }, pubkeycredparams: [ { type: "public-key", alg: -7 } ] }; navigator.credentials.create({ publickey }) .then(function (newcredentialinfo) { // send attestation response and client extensions // to the server to proceed with the registration // of the credential }).catch(function (err) { console.error(err); }); specifications specification status comment web authentication: an api for accessing public key credent...
PublicKeyCredentialCreationOptions.pubKeyCredParams - Web APIs
Web › API › PublicKeyCredentialCreationOptions › pubKeyCredParams
// if not, then we will fallback on an rsa algorithm { type: "public-key", alg: -37 } ], challenge: new uint8array(26) /* this actually is given from the server */, rp: { name: "example corp", id : "login.example.com" }, user: { id: new uint8array(26), /* to be changed for each user */ name: "jdoe@example.com", displayname: "john doe", } }; navigator.credentials.create({ publickey }) .then(function (newcredentialinfo) { // send attestation response and client extensions // to the server to proceed with the registration // of the credential }).catch(function (err) { console.error(err); }); specifications specification status comment web authentication: an api for accessing public key credent...
PublicKeyCredentialRequestOptions.allowCredentials - Web APIs
Web › API › PublicKeyCredentialRequestOptions › allowCredentials
examples var options = { allowcredentials: [ { transports: ["usb"], type: "public-key", id: new uint8array(26) // actually provided by the server }, { transports: ["internal"], type: "public-key", id: new uint8array(26) // actually provided by the server } ], challenge: new uint8array([/* bytes sent from the server */]) }; navigator.credentials.get({ "publickey": options }) .then(function (credentialinfoassertion) { // send assertion response back to the server // to proceed with the control of the credential }).catch(function (err) { console.error(err); }); specifications specification status comment web authentication: an api for accessing public key credentials level 1the de...
PushManager.getSubscription() - Web APIs
Web › API › PushManager › getSubscription
(no live demo is available.) // we need the service worker registration to check for a subscription navigator.serviceworker.ready.then(function(serviceworkerregistration) { // do we already have a push message subscription?
PushManager.subscribe() - Web APIs
Web › API › PushManager › subscribe
} navigator.serviceworker.register('serviceworker.js'); // use serviceworker.ready to ensure that you can subscribe for push navigator.serviceworker.ready.then( function(serviceworkerregistration) { var options = { uservisibleonly: true, applicationserverkey: applicationserverkey }; serviceworkerregistration.pushmanager.subscribe(options).then( function(pushsubscription) { ...
PushManager - Web APIs
Web › API › PushManager
} navigator.serviceworker.register('serviceworker.js').then( function(serviceworkerregistration) { serviceworkerregistration.pushmanager.subscribe().then( function(pushsubscription) { console.log(pushsubscription.endpoint); // the push subscription details needed by the application // server are now available, and can be sent to it using, // for example, an xmlhttp...
PushSubscription.endpoint - Web APIs
Web › API › PushSubscription › endpoint
example navigator.serviceworker.ready.then(function(reg) { reg.pushmanager.subscribe({uservisibleonly: true}).then(function(subscription) { console.log(subscription.endpoint); // at this point you would most likely send the subscription // endpoint to your server, save it, then use it to send a // push message at a later date }) }) specifications specification status co...
PushSubscription.toJSON() - Web APIs
Web › API › PushSubscription › toJSON
example navigator.serviceworker.ready.then(function(reg) { reg.pushmanager.getsubscription().then(function(subscription) { var mysubscription = subscription.tojson(); // do something with subscription details }) }); specifications specification status comment push apithe definition of 'pushsubscription: tojson' in that specification.
PushSubscription.unsubscribe() - Web APIs
Web › API › PushSubscription › unsubscribe
example navigator.serviceworker.ready.then(function(reg) { reg.pushmanager.getsubscription().then(function(subscription) { subscription.unsubscribe().then(function(successful) { // you've successfully unsubscribed }).catch(function(e) { // unsubscription failed }) }) }); specifications specification status comment push apithe definition of 'unsubscribe()' in that specification.
PushSubscription - Web APIs
Web › API › PushSubscription
example navigator.serviceworker.ready.then(function(reg) { reg.pushmanager.getsubscription().then(function(subscription) { subscription.unsubscribe().then(function(successful) { // you've successfully unsubscribed }).catch(function(e) { // unsubscription failed }) }) }); specifications specification status comment push apithe definition of 'pushsubscription' in...
RTCPeerConnection.addStream() - Web APIs
Web › API › RTCPeerConnection › addStream
navigator.mediadevices.getusermedia({video:true, audio:true}, function(stream) { var pc = new rtcpeerconnection(); pc.addstream(stream); }); migrating to addtrack() compatibility allowing, you should update your code to instead use the addtrack() method: navigator.getusermedia({video:true, audio:true}, function(stream) { var pc = new rtcpeerconnection(); stream.gettracks().foreach(function(track...
RTCPeerConnection.removeStream() - Web APIs
Web › API › RTCPeerConnection › removeStream
example var pc, videostream; navigator.getusermedia({video: true}, function(stream) { pc = new rtcpeerconnection(); videostream = stream; pc.addstream(stream); } document.getelementbyid("closebutton").addeventlistener("click", function(event) { pc.removestream(videostream); pc.close(); }, false); ...
RTCPeerConnection.removeTrack() - Web APIs
Web › API › RTCPeerConnection › removeTrack
var pc, sender; navigator.getusermedia({video: true}, function(stream) { pc = new rtcpeerconnection(); var track = stream.getvideotracks()[0]; sender = pc.addtrack(track, stream); }); document.getelementbyid("closebutton").addeventlistener("click", function(event) { pc.removetrack(sender); pc.close(); }, false); specifications specification status comment webrtc 1.0: real-time comm...
RTCPeerConnection.setRemoteDescription() - Web APIs
Web › API › RTCPeerConnection › setRemoteDescription
function handleoffer(msg) { createmypeerconnection(); mypeerconnection.setremotedescription(msg.description).then(function () { return navigator.mediadevices.getusermedia(mediaconstraints); }) .then(function(stream) { document.getelementbyid("local_video").srcobject = stream; return mypeerconnection.addstream(stream); }) .then(function() { return mypeerconnection.createanswer(); }) .then(function(answer) { return mypeerconnection.setlocaldescription(answer); }) .then(function() { // send the answer to t...
RTCRtpSender.replaceTrack() - Web APIs
Web › API › RTCRtpSender › replaceTrack
examples switching video cameras // example to change video camera, suppose selected value saved into window.selectedcamera navigator.mediadevices .getusermedia({ video: { deviceid: { exact: window.selectedcamera } } }) .then(function(stream) { let videotrack = stream.getvideotracks()[0]; pcs.foreach(function(pc) { var sender = pc.getsenders().find(function(s) { return s.track.kind == videotrack.kind; }); console.log('found sender:', sender); sender.repla...
RTCSessionDescription() - Web APIs
Web › API › RTCSessionDescription › RTCSessionDescription
navigator.getusermedia({video: true}, function(stream) { pc.onaddstream({stream: stream}); // adding a local stream won't trigger the onaddstream callback pc.addstream(stream); pc.createoffer(function(offer) { pc.setlocaldescription(new rtcsessiondescription(offer), function() { // send the offer to a server to be forwarded to the friend you're calling.
RelativeOrientationSensor - Web APIs
Web › API › RelativeOrientationSensor
const sensor = new relativeorientationsensor(); promise.all([navigator.permissions.query({ name: "accelerometer" }), navigator.permissions.query({ name: "gyroscope" })]) .then(results => { if (results.every(result => result.state === "granted")) { sensor.start(); ...
ReportingObserver - Web APIs
Web › API › ReportingObserver
btn.onclick = () => displayreports(reports); }, options); we then tell it to start observing reports using reportingobserver.observe(); this tells the observer to start collecting reports in its report queue, and runs the callback function specified inside the constructor: observer.observe(); later on in the example we deliberately use the deprecated version of mediadevices.getusermedia(): if(navigator.mozgetusermedia) { navigator.mozgetusermedia( constraints, success, failure); } else { navigator.getusermedia( constraints, success, failure); } this causes a deprecation report to be generated; because of the event handler we set up inside the reportingobserver() constructor, we can now click the button to display the report details.
Reporting API - Web APIs
Web › API › Reporting API
btn.onclick = () => displayreports(reports); }, options); we then tell it to start observing reports using reportingobserver.observe(); this tells the observer to start collecting reports in its report queue, and runs the callback function specified inside the constructor: observer.observe(); later on in the example we deliberately use the deprecated version of mediadevices.getusermedia(): if(navigator.mozgetusermedia) { navigator.mozgetusermedia( constraints, success, failure); } else { navigator.getusermedia( constraints, success, failure); } this causes a deprecation report to be generated; because of the event handler we set up inside the reportingobserver() constructor, we can now click the button to display the report details.
RequestDestination - Web APIs
Web › API › RequestDestination
navigator.sendbeacon(), eventsource, <a ping>, <area ping>, fetch(), xmlhttprequest, websocket, cache and more.
Screen Capture API - Web APIs
Web › API › Screen Capture API
to start capturing video from the screen, you call getdisplaymedia() on the instance of media navigator.mediadevices: capturestream = await navigator.mediadevices.getdisplaymedia(displaymediaoptions); the promise returned by getdisplaymedia() resolves to a mediastream which streams the captured media.
ServiceWorker.onstatechange - Web APIs
Web › API › ServiceWorker › onstatechange
for example: navigator.serviceworker.register(..).then(function(swr) { swr.installing.state == "installing" swr.installing.onstatechange = function() { swr.installing == null; // at this point, swr.waiting or swr.active might be true.
ServiceWorker - Web APIs
Web › API › ServiceWorker
if ('serviceworker' in navigator) { navigator.serviceworker.register('service-worker.js', { scope: './' }).then(function (registration) { var serviceworker; if (registration.installing) { serviceworker = registration.installing; document.queryselector('#kind').textcontent = 'installing'; } else if (registration.waiting) { serviceworker = registration.wai...
ServiceWorkerContainer.getRegistration() - Web APIs
Web › API › ServiceWorkerContainer › getRegistration
example navigator.serviceworker.getregistration('/app').then(function(registration) { if(registration){ document.queryselector('#status').textcontent = 'serviceworkerregistration found.'; } }); specifications specification status comment service workersthe definition of 'serviceworkercontainer: getregistration' in that specification.
ServiceWorkerContainer.getRegistrations() - Web APIs
Web › API › ServiceWorkerContainer › getRegistrations
example navigator.serviceworker.getregistrations().then(function(registrations) { document.queryselector('#status').textcontent = 'serviceworkerregistrations found.'; }); specifications specification status comment service workersthe definition of 'getregistrations()' in that specification.
ServiceWorkerContainer: message event - Web APIs
Web › API › ServiceWorkerContainer › message event
}); }); the client can receive the message by listening to the message event: // in the page being controlled navigator.serviceworker.addeventlistener('message', (message) => { console.log(message); }); specifications specification status service workersthe definition of 'message' in that specification.
ServiceWorkerContainer.onerror - Web APIs
Web › API › ServiceWorkerContainer › onerror
} example navigator.serviceworker.onerror = function(errorevent) { console.log(`received error message: ${errorevent.message}`); } ...
ServiceWorkerContainer.onmessage - Web APIs
Web › API › ServiceWorkerContainer › onmessage
} example navigator.serviceworker.onmessage = function(messageevent) { console.log(`received data: ${messageevent.data}`); } specifications specification status comment service workersthe definition of 'serviceworkercontainer: onmessage' in that specification.
ServiceWorkerGlobalScope: message event - Web APIs
Web › API › ServiceWorkerGlobalScope › message event
// in the page being controlled if (navigator.serviceworker) { navigator.serviceworker.register('service-worker.js'); navigator.serviceworker.addeventlistener('message', event => { // event is a messageevent object console.log(`the service worker sent me a message: ${event.data}`); }); navigator.serviceworker.ready.then( registration => { registration.active.postmessage("hi service worker"); }); } the service worke...
ServiceWorkerMessageEvent.data - Web APIs
Web › API › ServiceWorkerMessageEvent › data
navigator.serviceworker.ready.then(function(reg) { ...
ServiceWorkerMessageEvent.lastEventId - Web APIs
Web › API › ServiceWorkerMessageEvent › lastEventId
navigator.serviceworker.ready.then(function(reg) { ...
ServiceWorkerMessageEvent.origin - Web APIs
Web › API › ServiceWorkerMessageEvent › origin
navigator.serviceworker.ready.then(function(reg) { ...
ServiceWorkerMessageEvent.ports - Web APIs
Web › API › ServiceWorkerMessageEvent › ports
navigator.serviceworker.ready.then(function(reg) { ...
ServiceWorkerMessageEvent.source - Web APIs
Web › API › ServiceWorkerMessageEvent › source
navigator.serviceworker.ready.then(function(reg) { ...
ServiceWorkerMessageEvent - Web APIs
Web › API › ServiceWorkerMessageEvent
navigator.serviceworker.ready.then(function(reg) { ...
ServiceWorkerRegistration.getNotifications() - Web APIs
Web › API › ServiceWorkerRegistration › getNotifications
example navigator.serviceworker.register('sw.js'); var options = { tag : 'user_alerts' }; navigator.serviceworker.ready.then(function(registration) { registration.getnotifications(options).then(function(notifications) { // do something with your notifications }) }); specifications specification status comment notifications apithe definition of 'serviceworkerregistration.getnotif...
ServiceWorkerRegistration.index - Web APIs
Web › API › ServiceWorkerRegistration › index
here is an example from the main script: // reference registration const registration = await navigator.serviceworker.ready; // feature detection if ('index' in registration) { // content index api functionality const contentindex = registration.index; } from the service worker: // service worker script const contentindex = self.registration.index; specifications specification status comment unknownthe definition of 'index' in that specification.
ServiceWorkerRegistration.pushManager - Web APIs
Web › API › ServiceWorkerRegistration › pushManager
} navigator.serviceworker.register('serviceworker.js').then( function(serviceworkerregistration) { serviceworkerregistration.pushmanager.subscribe().then( function(pushsubscription) { console.log(pushsubscription.subscriptionid); console.log(pushsubscription.endpoint); // the push subscription details needed by the application // server are now available, and can b...
ServiceWorkerRegistration.showNotification() - Web APIs
Web › API › ServiceWorkerRegistration › showNotification
examples navigator.serviceworker.register('sw.js'); function shownotification() { notification.requestpermission(function(result) { if (result === 'granted') { navigator.serviceworker.ready.then(function(registration) { registration.shownotification('vibration sample', { body: 'buzz!
ServiceWorkerRegistration.unregister() - Web APIs
Web › API › ServiceWorkerRegistration › unregister
example the following simple example registers a service worker example, but then immediately unregisters it again: if ('serviceworker' in navigator) { navigator.serviceworker.register('/sw-test/sw.js', {scope: 'sw-test'}).then(function(registration) { // registration worked console.log('registration succeeded.'); registration.unregister().then(function(boolean) { // if boolean = true, unregister is successful }); }).catch(function(error) { // registration failed console.log('registration failed with ' + erro...
ServiceWorkerRegistration.update() - Web APIs
Web › API › ServiceWorkerRegistration › update
example the following simple example registers a service worker example then adds an event handler to a button so you can explicitly update the service worker whenever desired: if ('serviceworker' in navigator) { navigator.serviceworker.register('/sw-test/sw.js', {scope: 'sw-test'}).then(function(registration) { // registration worked console.log('registration succeeded.'); button.onclick = function() { registration.update(); } }).catch(function(error) { // registration failed console.log('registration failed with ' + error); }); }; specifications specific...
ServiceWorkerRegistration - Web APIs
Web › API › ServiceWorkerRegistration
if ('serviceworker' in navigator) { navigator.serviceworker.register('/sw.js') .then(function(registration) { registration.addeventlistener('updatefound', function() { // if updatefound is fired, it means that there's // a new service worker being installed.
Using Service Workers - Web APIs
Web › API › Service Worker API › Using Service Workers
if ('serviceworker' in navigator) { navigator.serviceworker.register('./sw-test/sw.js', {scope: './sw-test/'}) .then((reg) => { // registration worked console.log('registration succeeded.
Service Worker API - Web APIs
Web › API › Service Worker API
navigator.serviceworker returns a serviceworkercontainer object, which provides access to registration, removal, upgrade, and communication with the serviceworker objects for the associated document.
StorageEstimate.quota - Web APIs
Web › API › StorageEstimate › quota
</label> javascript content navigator.storage.estimate().then(function(estimate) { document.getelementbyid("percent").value = (estimate.usage / estimate.quota * 100).tofixed(2); }); result specifications specification status comment storagethe definition of 'quota' in that specification.
StorageEstimate.usage - Web APIs
Web › API › StorageEstimate › usage
</label> javascript content navigator.storage.estimate().then(function(estimate) { document.getelementbyid("percent").value = (estimate.usage / estimate.quota * 100).tofixed(2); }); result specifications specification status comment storagethe definition of 'usage' in that specification.
StorageManager.estimate() - Web APIs
Web › API › StorageManager › estimate
</label> javascript content navigator.storage.estimate().then(function(estimate) { document.getelementbyid("percent").value = (estimate.usage / estimate.quota * 100).tofixed(2); }); result specifications specification status comment storagethe definition of 'estimate()' in that specification.
StorageManager - Web APIs
Web › API › StorageManager
you can get a reference to this interface using either navigator.storage or workernavigator.storage.
USB.getDevices() - Web APIs
Web › API › USB › getDevices
navigator.usb.getdevices() .then(devices => { console.log("total devices: " + devices.length); devices.foreach(device => { console.log("product name: " + device.productname + ", serial number " + device.serialnumber); }); }); specifications specification status comment webusbthe definition of 'getdevices' in that specification.
USB.requestDevice() - Web APIs
Web › API › USB › requestDevice
const filters = [ {vendorid: 0x1209, productid: 0xa800}, {vendorid: 0x1209, productid: 0xa850} ]; navigator.usb.requestdevice({filters: filters}) .then(usbdevice => { console.log("product name: " + usbdevice.productname); }) .catch(e => { console.log("there is no device.
VRDisplay.cancelAnimationFrame() - Web APIs
Web › API › VRDisplay › cancelAnimationFrame
examples canvas.width = window.innerwidth; canvas.height = window.innerheight; drawscene(); // webvr: check to see if webvr is supported if(navigator.getvrdisplays) { console.log('webvr 1.1 supported'); // then get the displays attached to the computer navigator.getvrdisplays().then(function(displays) { // if a display is available, use it to present the scene if(displays.length > 0) { vrdisplay = displays[0]; console.log('display found'); // starting the presentation when the button is clicked: it can only be c...
VRDisplay.capabilities - Web APIs
Web › API › VRDisplay › capabilities
examples function reportdisplays() { navigator.getvrdisplays().then(function(displays) { for(var i = 0; i < displays.length; i++) { var cap = displays[i].capabilities; // cap is a vrdisplaycapabilities object var listitem = document.createelement('li'); listitem.innerhtml = '<strong>display ' + (i+1) + '</strong>' + '<br>vr display id: ' + displays[i].displayid + '<br>vr display name: ' + displays[i].displayname + '<br>display can present cont...
VRDisplay.depthFar - Web APIs
Web › API › VRDisplay › depthFar
examples var vrdisplay; navigator.getvrdisplays().then(function(displays) { vrdisplay = displays[0]; vrdisplay.depthnear = 1.0; vrdisplay.depthfar = 7500.0; }); specifications specification status comment webvr 1.1the definition of 'depthfar' in that specification.
VRDisplay.depthNear - Web APIs
Web › API › VRDisplay › depthNear
examples var vrdisplay; navigator.getvrdisplays().then(function(displays) { vrdisplay = displays[0]; vrdisplay.depthnear = 1.0; vrdisplay.depthfar = 7500.0; }); specifications specification status comment webvr 1.1the definition of 'depthnear' in that specification.
VRDisplay.displayId - Web APIs
Web › API › VRDisplay › displayId
examples function reportdisplays() { navigator.getvrdisplays().then(function(displays) { for(var i = 0; i < displays.length; i++) { var cap = displays[i].capabilities; // cap is a vrdisplaycapabilities object var listitem = document.createelement('li'); listitem.innerhtml = '<strong>display ' + (i+1) + '</strong>' + '<br>vr display id: ' + displays[i].displayid + '<br>vr display name: ' + displays[i].disp...
VRDisplay.displayName - Web APIs
Web › API › VRDisplay › displayName
examples function reportdisplays() { navigator.getvrdisplays().then(function(displays) { for(var i = 0; i < displays.length; i++) { var cap = displays[i].capabilities; // cap is a vrdisplaycapabilities object var listitem = document.createelement('li'); listitem.innerhtml = '<strong>display ' + (i+1) + '</strong>' + '<br>vr display id: ' + displays[i].displayid + '<br>vr displa...
VRDisplay.exitPresent() - Web APIs
Web › API › VRDisplay › exitPresent
examples if(navigator.getvrdisplays) { console.log('webvr 1.1 supported'); // then get the displays attached to the computer navigator.getvrdisplays().then(function(displays) { // if a display is available, use it to present the scene if(displays.length > 0) { vrdisplay = displays[0]; console.log('display found'); // starting the presentation when the button is clicked: it can only be c...
VRDisplay.getEyeParameters() - Web APIs
Web › API › VRDisplay › getEyeParameters
examples navigator.getvrdisplays().then(function(displays) { // if a display is available, use it to present the scene vrdisplay = displays[0]; console.log('display found'); // starting the presentation when the button is clicked: // it can only be called in response to a user gesture btn.addeventlistener('click', function() { vrdisplay.requestpresent([{ source: canvas }]).then(function() { ...
VRDisplay.getFrameData() - Web APIs
Web › API › VRDisplay › getFrameData
examples var framedata = new vrframedata(); var vrdisplay; navigator.getvrdisplays().then(function(displays) { vrdisplay = displays[0]; console.log('display found'); // starting the presentation when the button is clicked: it can only be called in response to a user gesture btn.addeventlistener('click', function() { vrdisplay.requestpresent([{ source: canvas }]).then(function() { drawvrscene(); }); }); }); // webvr: draw the scene for the ...
VRDisplay.getLayers() - Web APIs
Web › API › VRDisplay › getLayers
examples // currently returns an empty array var layers = vrdisplay.getlayers(); if(navigator.getvrdisplays) { console.log('webvr 1.1 supported'); // then get the displays attached to the computer navigator.getvrdisplays().then(function(displays) { // if a display is available, use it to present the scene if(displays.length > 0) { vrdisplay = displays[0]; console.log('display found'); // starting the presentation when the button is clicked: it can only be c...
VRDisplay.getPose() - Web APIs
Web › API › VRDisplay › getPose
if(navigator.getvrdisplays) { console.log('webvr 1.1 supported'); // then get the displays attached to the computer navigator.getvrdisplays().then(function(displays) { // if a display is available, use it to present the scene if(displays.length > 0) { vrdisplay = displays[0]; console.log('display found'); // return the current vrpose object for the display var po...
VRdisplay.isConnected - Web APIs
Web › API › VRDisplay › isConnected
examples navigator.getvrdisplays().then(function(displays) { // if a display is available, use it to present the scene if(displays.length > 0) { vrdisplay = displays[0]; // starting the presentation when the button is clicked: it can only be called in response to a user gesture btn.addeventlistener('click', function() { // only request presentation if the display is still connected.
VRDisplay.requestAnimationFrame() - Web APIs
Web › API › VRDisplay › requestAnimationFrame
examples var framedata = new vrframedata(); var vrdisplay; navigator.getvrdisplays().then(function(displays) { vrdisplay = displays[0]; console.log('display found'); // starting the presentation when the button is clicked: it can only be called in response to a user gesture btn.addeventlistener('click', function() { vrdisplay.requestpresent([{ source: canvas }]).then(function() { drawvrscene(); }); }); }); // webvr: draw the scene for the ...
VRDisplay.requestPresent() - Web APIs
Web › API › VRDisplay › requestPresent
examples if(navigator.getvrdisplays) { console.log('webvr 1.1 supported'); // then get the displays attached to the computer navigator.getvrdisplays().then(function(displays) { // if a display is available, use it to present the scene if(displays.length > 0) { vrdisplay = displays[0]; console.log('display found'); // starting the presentation when the button is clicked: it can only be c...
VRDisplay.stageParameters - Web APIs
Web › API › VRDisplay › stageParameters
examples var info = document.queryselector('p'); var vrdisplay; navigator.getvrdisplays().then(function(displays) { vrdisplay = displays[0]; var stageparams = vrdisplay.stageparameters; // stageparams is a vrstageparameters object if(stageparams === null) { info.textcontent = 'your vr hardware does not support room-scale experiences.' } else { info.innerhtml = '<strong>display stage parameters</strong>' + '<br>sitting to standing tra...
VRDisplay.submitFrame() - Web APIs
Web › API › VRDisplay › submitFrame
examples var framedata = new vrframedata(); var vrdisplay; navigator.getvrdisplays().then(function(displays) { vrdisplay = displays[0]; console.log('display found'); // starting the presentation when the button is clicked: it can only be called in response to a user gesture btn.addeventlistener('click', function() { vrdisplay.requestpresent([{ source: canvas }]).then(function() { drawvrscene(); }); }); }); // webvr: draw the scene for the ...
VRDisplayCapabilities.canPresent - Web APIs
Web › API › VRDisplayCapabilities › canPresent
examples function reportdisplays() { navigator.getvrdisplays().then(function(displays) { for(var i = 0; i < displays.length; i++) { var cap = displays[i].capabilities; // cap is a vrdisplaycapabilities object var listitem = document.createelement('li'); listitem.innerhtml = '<strong>display ' + (i+1) + '</strong>' + '<br>vr display id: ' + displays[i].displayid + '<br>vr displa...
VRDisplayCapabilities.hasExternalDisplay - Web APIs
Web › API › VRDisplayCapabilities › hasExternalDisplay
examples function reportdisplays() { navigator.getvrdisplays().then(function(displays) { for(var i = 0; i < displays.length; i++) { var cap = displays[i].capabilities; // cap is a vrdisplaycapabilities object var listitem = document.createelement('li'); listitem.innerhtml = '<strong>display ' + (i+1) + '</strong>' + '<br>vr display id: ' + displays[i].displayid + '<br>vr displa...
VRDisplayCapabilities.hasOrientation - Web APIs
Web › API › VRDisplayCapabilities › hasOrientation
examples function reportdisplays() { navigator.getvrdisplays().then(function(displays) { for(var i = 0; i < displays.length; i++) { var cap = displays[i].capabilities; // cap is a vrdisplaycapabilities object var listitem = document.createelement('li'); listitem.innerhtml = '<strong>display ' + (i+1) + '</strong>' + '<br>vr display id: ' + displays[i].displayid + '<br>vr display name: ' + displays[i].displayname + '<br>display can p...
VRDisplayCapabilities.hasPosition - Web APIs
Web › API › VRDisplayCapabilities › hasPosition
examples function reportdisplays() { navigator.getvrdisplays().then(function(displays) { for(var i = 0; i < displays.length; i++) { var cap = displays[i].capabilities; // cap is a vrdisplaycapabilities object var listitem = document.createelement('li'); listitem.innerhtml = '<strong>display ' + (i+1) + '</strong>' + '<br>vr display id: ' + displays[i].displayid + '<br>vr display name: ' + displays[i].displayname + '<br>display can present conten...
VRDisplayCapabilities.maxLayers - Web APIs
Web › API › VRDisplayCapabilities › maxLayers
examples function reportdisplays() { navigator.getvrdisplays().then(function(displays) { for(var i = 0; i < displays.length; i++) { var cap = displays[i].capabilities; // cap is a vrdisplaycapabilities object var listitem = document.createelement('li'); listitem.innerhtml = '<strong>display ' + (i+1) + '</strong>' + '<br>vr display id: ' + displays[i].displayid + '<br>vr displa...
VRDisplayCapabilities - Web APIs
Web › API › VRDisplayCapabilities
the maximum length of the array that vrdisplay.requestpresent() can accept.) examples function reportdisplays() { navigator.getvrdisplays().then(function(displays) { for(var i = 0; i < displays.length; i++) { var cap = displays[i].capabilities; // cap is a vrdisplaycapabilities object var listitem = document.createelement('li'); listitem.innerhtml = '<strong>display ' + (i+1) + '</strong>' + '<br>vr display id: ' + displays[i].displayid + '<br>vr displa...
VREyeParameters.fieldOfView - Web APIs
Web › API › VREyeParameters › fieldOfView
examples var info = document.queryselector('p'); var list = document.queryselector('ul'); var vrdisplay; if(navigator.getvrdisplays) { reportfieldofview(); } else { info.textcontent = 'webvr api not supported by this browser.' } function reportfieldofview() { navigator.getvrdisplays().then(function(displays) { vrdisplay = displays[0]; var leye = vrdisplay.geteyeparameters('left'); var reye = vrdisplay.geteyeparameters('right'); // leye and reye are vreyeparameters objects var lfov =...
VREyeParameters.offset - Web APIs
Web › API › VREyeParameters › offset
examples var info = document.queryselector('p'); var list = document.queryselector('ul'); var vrdisplay; if(navigator.getvrdisplays) { reportfieldofview(); } else { info.textcontent = 'webvr api not supported by this browser.' } function reportfieldofview() { navigator.getvrdisplays().then(function(displays) { vrdisplay = displays[0]; var leye = vrdisplay.geteyeparameters('left'); var reye = vrdisplay.geteyeparameters('right'); // leye and reye are vreyeparameters objects var lfov =...
VREyeParameters.renderHeight - Web APIs
Web › API › VREyeParameters › renderHeight
examples navigator.getvrdisplays().then(function(displays) { // if a display is available, use it to present the scene vrdisplay = displays[0]; console.log('display found'); // starting the presentation when the button is clicked: // it can only be called in response to a user gesture btn.addeventlistener('click', function() { vrdisplay.requestpresent([{ source: canvas }]).then(function() { ...
VREyeParameters.renderWidth - Web APIs
Web › API › VREyeParameters › renderWidth
examples navigator.getvrdisplays().then(function(displays) { // if a display is available, use it to present the scene vrdisplay = displays[0]; console.log('display found'); // starting the presentation when the button is clicked: // it can only be called in response to a user gesture btn.addeventlistener('click', function() { vrdisplay.requestpresent([{ source: canvas }]).then(function() { ...
VREyeParameters - Web APIs
Web › API › VREyeParameters
examples navigator.getvrdisplays().then(function(displays) { // if a display is available, use it to present the scene vrdisplay = displays[0]; console.log('display found'); // starting the presentation when the button is clicked: // it can only be called in response to a user gesture btn.addeventlistener('click', function() { vrdisplay.requestpresent([{ source: canvas }]).then(function() { ...
VRFieldOfView.downDegrees - Web APIs
Web › API › VRFieldOfView › downDegrees
examples var info = document.queryselector('p'); var list = document.queryselector('ul'); var vrdisplay; if(navigator.getvrdisplays) { reportfieldofview(); } else { info.textcontent = 'webvr api not supported by this browser.' } function reportfieldofview() { navigator.getvrdisplays().then(function(displays) { vrdisplay = displays[0]; var leye = vrdisplay.geteyeparameters('left'); var reye = vrdisplay.geteyeparameters('right'); // leye and reye are vreyeparameters objects var lfov = leye.fieldofview; var rfov = reye.fieldofview; // lfo...
VRFieldOfView.leftDegrees - Web APIs
Web › API › VRFieldOfView › leftDegrees
examples var info = document.queryselector('p'); var list = document.queryselector('ul'); var vrdisplay; if(navigator.getvrdisplays) { reportfieldofview(); } else { info.textcontent = 'webvr api not supported by this browser.' } function reportfieldofview() { navigator.getvrdisplays().then(function(displays) { vrdisplay = displays[0]; var leye = vrdisplay.geteyeparameters('left'); var reye = vrdisplay.geteyeparameters('right'); // leye and reye are vreyeparameters objects var lfov = leye.fieldofview; var rfov = reye.fieldofview; // l...
VRFieldOfView.rightDegrees - Web APIs
Web › API › VRFieldOfView › rightDegrees
examples var info = document.queryselector('p'); var list = document.queryselector('ul'); var vrdisplay; if(navigator.getvrdisplays) { reportfieldofview(); } else { info.textcontent = 'webvr api not supported by this browser.' } function reportfieldofview() { navigator.getvrdisplays().then(function(displays) { vrdisplay = displays[0]; var leye = vrdisplay.geteyeparameters('left'); var reye = vrdisplay.geteyeparameters('right'); // leye and reye are vreyeparameters objects var lfov = leye.fieldofview; var rfov = reye.fieldofview; ...
VRFieldOfView.upDegrees - Web APIs
Web › API › VRFieldOfView › upDegrees
examples var info = document.queryselector('p'); var list = document.queryselector('ul'); var vrdisplay; if(navigator.getvrdisplays) { reportfieldofview(); } else { info.textcontent = 'webvr api not supported by this browser.' } function reportfieldofview() { navigator.getvrdisplays().then(function(displays) { vrdisplay = displays[0]; var leye = vrdisplay.geteyeparameters('left'); var reye = vrdisplay.geteyeparameters('right'); // leye and reye are vreyeparameters objects var lfov = leye.fieldofview; var rfov = reye.fieldofview; // lfov and rf...
VRFieldOfView - Web APIs
Web › API › VRFieldOfView
examples var info = document.queryselector('p'); var list = document.queryselector('ul'); var vrdisplay; if(navigator.getvrdisplays) { reportfieldofview(); } else { info.textcontent = 'webvr api not supported by this browser.' } function reportfieldofview() { navigator.getvrdisplays().then(function(displays) { vrdisplay = displays[0]; var leye = vrdisplay.geteyeparameters('left'); var reye = vrdisplay.geteyeparameters('right'); // leye and reye are vreyeparameters objects var lfov =...
VRFrameData.VRFrameData() - Web APIs
Web › API › VRFrameData › VRFrameData
examples var framedata = new vrframedata(); var vrdisplay; navigator.getvrdisplays().then(function(displays) { vrdisplay = displays[0]; console.log('display found'); // starting the presentation when the button is clicked: it can only be called in response to a user gesture btn.addeventlistener('click', function() { vrdisplay.requestpresent([{ source: canvas }]).then(function() { drawvrscene(); }); }); }); // webvr: draw the scene for the webvr display.
VRFrameData.leftProjectionMatrix - Web APIs
Web › API › VRFrameData › leftProjectionMatrix
examples var framedata = new vrframedata(); var vrdisplay; navigator.getvrdisplays().then(function(displays) { vrdisplay = displays[0]; console.log('display found'); // starting the presentation when the button is clicked: it can only be called in response to a user gesture btn.addeventlistener('click', function() { vrdisplay.requestpresent([{ source: canvas }]).then(function() { drawvrscene(); }); }); }); // webvr: draw the scene for the ...
VRFrameData.leftViewMatrix - Web APIs
Web › API › VRFrameData › leftViewMatrix
examples var framedata = new vrframedata(); var vrdisplay; navigator.getvrdisplays().then(function(displays) { vrdisplay = displays[0]; console.log('display found'); // starting the presentation when the button is clicked: it can only be called in response to a user gesture btn.addeventlistener('click', function() { vrdisplay.requestpresent([{ source: canvas }]).then(function() { drawvrscene(); }); }); }); // webvr: draw the scene for the ...
VRFrameData.pose - Web APIs
Web › API › VRFrameData › pose
examples var framedata = new vrframedata(); var vrdisplay; navigator.getvrdisplays().then(function(displays) { vrdisplay = displays[0]; console.log('display found'); // starting the presentation when the button is clicked: it can only be called in response to a user gesture btn.addeventlistener('click', function() { vrdisplay.requestpresent([{ source: canvas }]).then(function() { drawvrscene(); }); }); }); // webvr: draw the scene for the webvr display.
VRFrameData.rightProjectionMatrix - Web APIs
Web › API › VRFrameData › rightProjectionMatrix
examples var framedata = new vrframedata(); var vrdisplay; navigator.getvrdisplays().then(function(displays) { vrdisplay = displays[0]; console.log('display found'); // starting the presentation when the button is clicked: it can only be called in response to a user gesture btn.addeventlistener('click', function() { vrdisplay.requestpresent([{ source: canvas }]).then(function() { drawvrscene(); }); }); }); // webvr: draw the scene for the ...
VRFrameData.rightViewMatrix - Web APIs
Web › API › VRFrameData › rightViewMatrix
examples var framedata = new vrframedata(); var vrdisplay; navigator.getvrdisplays().then(function(displays) { vrdisplay = displays[0]; console.log('display found'); // starting the presentation when the button is clicked: it can only be called in response to a user gesture btn.addeventlistener('click', function() { vrdisplay.requestpresent([{ source: canvas }]).then(function() { drawvrscene(); }); }); }); // webvr: draw the scene for the ...
VRFrameData.timestamp - Web APIs
Web › API › VRFrameData › timestamp
examples var framedata = new vrframedata(); var vrdisplay; navigator.getvrdisplays().then(function(displays) { vrdisplay = displays[0]; console.log('display found'); // starting the presentation when the button is clicked: it can only be called in response to a user gesture btn.addeventlistener('click', function() { vrdisplay.requestpresent([{ source: canvas }]).then(function() { drawvrscene(); }); }); }); // webvr: draw the scene for the ...
VRFrameData - Web APIs
Web › API › VRFrameData
examples var framedata = new vrframedata(); var vrdisplay; navigator.getvrdisplays().then(function(displays) { vrdisplay = displays[0]; console.log('display found'); // starting the presentation when the button is clicked: it can only be called in response to a user gesture btn.addeventlistener('click', function() { vrdisplay.requestpresent([{ source: canvas }]).then(function() { drawvrscene(); }); }); }); // webvr: draw the scene for the ...
VRLayerInit.leftBounds - Web APIs
Web › API › VRLayerInit › leftBounds
examples // currently returns an empty array var layers = vrdisplay.getlayers(); if(navigator.getvrdisplays) { console.log('webvr 1.1 supported'); // then get the displays attached to the computer navigator.getvrdisplays().then(function(displays) { // if a display is available, use it to present the scene if(displays.length > 0) { vrdisplay = displays[0]; console.log('display found'); // starting the presentation when the button is clicked: it can only be c...
VRLayerInit.rightBounds - Web APIs
Web › API › VRLayerInit › rightBounds
examples // currently returns an empty array var layers = vrdisplay.getlayers(); if(navigator.getvrdisplays) { console.log('webvr 1.1 supported'); // then get the displays attached to the computer navigator.getvrdisplays().then(function(displays) { // if a display is available, use it to present the scene if(displays.length > 0) { vrdisplay = displays[0]; console.log('display found'); // starting the presentation when the button is clicked: it can only be c...
VRLayerInit.source - Web APIs
Web › API › VRLayerInit › source
examples // currently returns an empty array var layers = vrdisplay.getlayers(); if(navigator.getvrdisplays) { console.log('webvr 1.1 supported'); // then get the displays attached to the computer navigator.getvrdisplays().then(function(displays) { // if a display is available, use it to present the scene if(displays.length > 0) { vrdisplay = displays[0]; console.log('display found'); // starting the presentation when the button is clicked: it can only be called in response to a user gesture btn.a...
VRLayerInit - Web APIs
Web › API › VRLayerInit
examples // currently returns an empty array var layers = vrdisplay.getlayers(); if(navigator.getvrdisplays) { console.log('webvr 1.1 supported'); // then get the displays attached to the computer navigator.getvrdisplays().then(function(displays) { // if a display is available, use it to present the scene if(displays.length > 0) { vrdisplay = displays[0]; console.log('display found'); // starting the presentation when the button is clicked: it can only be c...
VRPose.orientation - Web APIs
Web › API › VRPose › orientation
examples var framedata = new vrframedata(); var vrdisplay; navigator.getvrdisplays().then(function(displays) { vrdisplay = displays[0]; console.log('display found'); // starting the presentation when the button is clicked: it can only be called in response to a user gesture btn.addeventlistener('click', function() { vrdisplay.requestpresent([{ source: canvas }]).then(function() { drawvrscene(); }); }); }); // webvr: draw the scene for the ...
VRPose.position - Web APIs
Web › API › VRPose › position
examples var framedata = new vrframedata(); var vrdisplay; navigator.getvrdisplays().then(function(displays) { vrdisplay = displays[0]; console.log('display found'); // starting the presentation when the button is clicked: it can only be called in response to a user gesture btn.addeventlistener('click', function() { vrdisplay.requestpresent([{ source: canvas }]).then(function() { drawvrscene(); }); }); }); // webvr: draw the scene for the ...
VRPose - Web APIs
Web › API › VRPose
examples var framedata = new vrframedata(); var vrdisplay; navigator.getvrdisplays().then(function(displays) { vrdisplay = displays[0]; console.log('display found'); // starting the presentation when the button is clicked: it can only be called in response to a user gesture btn.addeventlistener('click', function() { vrdisplay.requestpresent([{ source: canvas }]).then(function() { drawvrscene(); }); }); }); // webvr: draw the scene for the ...
VRStageParameters.sittingToStandingTransform - Web APIs
Web › API › VRStageParameters › sittingToStandingTransform
examples var info = document.queryselector('p'); var vrdisplay; navigator.getvrdisplays().then(function(displays) { vrdisplay = displays[0]; var stageparams = vrdisplay.stageparameters; // stageparams is a vrstageparameters object if(stageparams === null) { info.textcontent = 'your vr hardware does not support room-scale experiences.' } else { info.innerhtml = '<strong>display stage parameters</strong>' + '<br>sitting to standing tra...
VRStageParameters.sizeX - Web APIs
Web › API › VRStageParameters › sizeX
examples var info = document.queryselector('p'); var vrdisplay; navigator.getvrdisplays().then(function(displays) { vrdisplay = displays[0]; var stageparams = vrdisplay.stageparameters; // stageparams is a vrstageparameters object if(stageparams === null) { info.textcontent = 'your vr hardware does not support room-scale experiences.' } else { info.innerhtml = '<strong>display stage parameters</strong>' + '<br>sitting to standing tra...
VRStageParameters.sizeY - Web APIs
Web › API › VRStageParameters › sizeY
examples var info = document.queryselector('p'); var vrdisplay; navigator.getvrdisplays().then(function(displays) { vrdisplay = displays[0]; var stageparams = vrdisplay.stageparameters; // stageparams is a vrstageparameters object if(stageparams === null) { info.textcontent = 'your vr hardware does not support room-scale experiences.' } else { info.innerhtml = '<strong>display stage parameters</strong>' + '<br>sitting to standing tra...
VRStageParameters - Web APIs
Web › API › VRStageParameters
examples var info = document.queryselector('p'); var vrdisplay; navigator.getvrdisplays().then(function(displays) { vrdisplay = displays[0]; var stageparams = vrdisplay.stageparameters; // stageparams is a vrstageparameters object if(stageparams === null) { info.textcontent = 'your vr hardware does not support room-scale experiences.' } else { info.innerhtml = '<strong>display stage parameters</strong>' + '<br>sitting to standing tra...
WakeLockSentinel.type - Web APIs
Web › API › WakeLockSentinel › type
const requestwakelock = async () => { wakelock = await navigator.wakelock.request('screen'); console.log(wakelock.type); // logs 'screen' }; requestwakelock(); specifications specification status comment screen wake lock apithe definition of 'wakelocktype' in that specification.
WebRTC connectivity - Web APIs
Web › API › WebRTC API › Connectivity
regardless of whether it's a new call, or reconfiguring an existing one, these are the basic steps which must occur to exchange the offer and answer, leaving out the ice layer for the moment: the caller captures local media via navigator.mediadevices.getusermedia() the caller creates rtcpeerconnection and called rtcpeerconnection.addtrack() (since addstream is deprecating) the caller calls rtcpeerconnection.createoffer() to create an offer.
Establishing a connection: The WebRTC perfect negotiation pattern - Web APIs
Web › API › WebRTC API › Perfect negotiation
async function start() { try { const stream = await navigator.mediadevices.getusermedia(constraints); for (const track of stream.gettracks()) { pc.addtrack(track, stream); } selfvideo.srcobject = stream; } catch(err) { console.error(err); } } this isn't appreciably different from older webrtc connection establishment code.
Using DTMF with WebRTC - Web APIs
Web › API › WebRTC API › Using DTMF
; callerpc.onsignalingstatechange = handlecallersignalingstatechangeevent; callerpc.onicegatheringstatechange = handlecallergatheringstatechangeevent; receiverpc = new rtcpeerconnection(); receiverpc.onicecandidate = handlereceivericeevent; if (hasaddtrack) { receiverpc.ontrack = handlereceivertrackevent; } else { receiverpc.onaddstream = handlereceiveraddstreamevent; } navigator.mediadevices.getusermedia(mediaconstraints) .then(gotstream) .catch(err => log(err.message)); } after creating the rtcpeerconnection for the caller (callerpc), we look to see if it has an addtrack() method.
Rendering and the WebXR frame animation callback - Web APIs
Web › API › WebXR Device API › Rendering
before you can render the virtual environment, you need to establish a webxr session by creating an xrsession using the navigator.xr.requestsession() method; you also need to associate the session with a framebuffer and perform other setup tasks.
Spaces and reference spaces: Spatial tracking in WebXR - Web APIs
Web › API › WebXR Device API › Spatial tracking
let viewerpose = frame.getviewerpose(worldreferencespace); let newsession = navigator.xr.requestsession("immersive-vr", { requiredfeatures: "unbounded" }); worldreferencespace = await newsession.requestreferencespace("unbounded"); viewerpose = worldreferencespace.getoffsetreferencespace(viewerpose.transform); here, the viewer pose is obtained, with its transform defined relative to worldreferencespace, the current session's global reference space.
Attestation and Assertion - Web APIs
Web › API › Web Authentication API › Attestation and Assertion
oid key attestation, the only option for android devices was to create android safetynet attestations fido u2f - security keys that implement the fido u2f standard use this format none - browsers may prompt users whether they want a site to be allowed to see their attestation data and/or may remove attestation data from the authenticator's response if the `attestation` parameter in `navigator.credentials.create()` is set to `none` the purpose of attestation is to cryptographically prove that a newly generated key pair came from a specific device.
Using Web Workers - Web APIs
Web › API › Web Workers API › Using web workers
functions and interfaces available in workers you can use most standard javascript features inside a web worker, including: navigator xmlhttprequest array, date, math, and string windowtimers.settimeout and windowtimers.setinterval the main thing you can't do in a worker is directly affect the parent page.
Web Workers API - Web APIs
Web › API › Web Workers API
workernavigator represents the identity and state of the user agent (the client): examples we have created a couple of simple demos to show basic usage: basic dedicated worker example (run dedicated worker).
Window.isSecureContext - Web APIs
Web › API › Window › isSecureContext
if (window.issecurecontext) { // page is a secure context so service workers are now available navigator.serviceworker.register("/offline-worker.js").then(function () { ...
Window: offline event - Web APIs
Web › API › Window › offline event
the offline event of the window interface is fired when the browser has lost access to the network and the value of navigator.online switches to false.
Window: online event - Web APIs
Web › API › Window › online event
the online event of the window interface is fired when the browser has gained access to the network and the value of navigator.online switches to true.
WindowEventHandlers.onlanguagechange - Web APIs
Web › API › WindowEventHandlers › onlanguagechange
the list is accessible via navigatorlanguage.languages.
WindowOrWorkerGlobalScope.fetch() - Web APIs
Web › API › WindowOrWorkerGlobalScope › fetch
fetch with the keepalive flag is a replacement for the navigator.sendbeacon() api.
XRPermissionDescriptor.mode - Web APIs
Web › API › XRPermissionDescriptor › mode
let xrpermissiondesc = { name: "xr", mode: "immersive-vr" }; if (navigator.permissions) { navigator.permissions.query(xrpermissiondesc).then(({state}) => { switch(state) { case "granted": setupxr(); break; case "prompt": promptandsetupxr(); break; default: /* do nothing otherwise */ break; } .catch(err) { console.log(err); } } else { setupxr(); } specifications specification ...
XRPermissionDescriptor.optionalFeatures - Web APIs
Web › API › XRPermissionDescriptor › optionalFeatures
xrreferencespace usage notes examples let xrpermissiondesc = { name: "xr", mode: "immersive-vr", optionalfeatures: [ "bounded-floor" ] }; if (navigator.permissions) { navigator.permissions.query(xrpermissiondesc).then(({state}) => { switch(state) { case "granted": setupxr(); break; case "prompt": promptandsetupxr(); break; default: /* do nothing otherwise */ break; } .catch(err) { console.log(err); } } else { setupxr(); } specifications specification ...
XRPermissionStatus.granted - Web APIs
Web › API › XRPermissionStatus › granted
the webxr device api's xrpermissionstatus interface's granted property is an array of strings, each identifying one of the webxr features for which permission has been granted as of the time at which the permission api's navigator.permissions.query() method was called.
XRSession.cancelAnimationFrame() - Web APIs
Web › API › XRSession › cancelAnimationFrame
const xr = navigator.xr; let requesthandle = null; let xrsession = null; if (xr) { xr.issessionsupported('immersive-vr') .then((issupported) => { if (issupported) { startxr(); } }); } function framecallback(time, xrframe) { xrsession.requestanimationframe(framecallback); // update and render the frame } async function startxr() { xrsession = xr.requestsession("immersive-vr"); if (xrs...
XRSession: visibilitychange event - Web APIs
Web › API › XRSession › visibilitychange event
examples this example demonstrates how to listen for a visibilitychange event on a webxr session, using addeventlistener() to begin listening for the event: navigator.xr.requestsession("inline").then((xrsession) => { xrsession.addeventlistener("visibilitychange", e => { switch(e.session.visiblitystate) { case "visible": case "visible-blurred": mysessionvisible(true); break; case "hidden": mysessionvisible(false); break; } }); }); when a visibility state change occurs, the event is received and dis...
XRSession - Web APIs
Web › API › XRSession
const xr = navigator.xr; if (xr) { xr.requestsession("inline").then((xrsession) => { xrsession.requestreferencespace("local").then((xrreferencespace) => { xrsession.requestanimationframe((time, xrframe) => { let viewer = xrframe.getviewerpose(xrreferencespace); gl.bindframebuffer(xrwebgllayer.framebuffer); for (xrview of viewer.views) { let xrviewport = xrwebgllayer.ge...
XRSessionInit - Web APIs
Web › API › XRSessionInit
the webxr device api dictionary xrsessioninit specifies required and/or optional features when requesting a new xrsession by calling the navigator.xr.requestsession() method.
XRSystem: isSessionSupported() - Web APIs
Web › API › XRSystem › isSessionSupported
if (navigator.xr) { navigator.xr.issessionsupported('immersive-vr') .then((issupported) => { if (issupported) { userbutton.addeventlistener('click', onbuttonclicked); userbutton.innerhtml = 'enter xr'; userbutton.disabled = false; } }); } function onbuttonclicked() { if (!xrsession) { navigator.xr.requestsession('immersive-vr') .then((session) => { xrsession = s...
Web accessibility for seizures and physical reactions - Accessibility
Web › Accessibility › Seizure disorders
developmental & experimental features mdn navigator​.donottrack from the documentation: "returns the user's do-not-track setting.
Pseudo-classes - CSS: Cascading Style Sheets
Web › CSS › Pseudo-classes
/* any button over which the user's pointer is hovering */ button:hover { color: blue; } pseudo-classes let you apply a style to an element not only in relation to the content of the document tree, but also in relation to external factors like the history of the navigator (:visited, for example), the status of its content (like :checked on certain form elements), or the position of the mouse (like :hover, which lets you know if the mouse is over an element or not).
Event reference
Web › Events
languagechange event html 5.1the definition of 'navigatorlanguage.languages' in that specification.
HTML5 - Developer guides
Web › Guide › HTML › HTML5
web-based protocol handlers you can now register web applications as protocol handlers using the navigator.registerprotocolhandler() method.
HTML documentation index - HTML: Hypertext Markup Language
Web › HTML › Index
236 quirks mode and standards mode gecko, guide, html, needsupdate, web development, web standards, xhtml in the old days of the web, pages were typically written in two versions: one for netscape navigator, and one for microsoft internet explorer.
CSP: worker-src - HTTP
Web › HTTP › Headers › Content-Security-Policy › worker-src
examples violation cases given this csp header: content-security-policy: worker-src https://example.com/ worker, sharedworker, serviceworker are blocked and won't load: <script> var blockedworker = new worker("data:application/javascript,..."); blockedworker = new sharedworker("https://not-example.com/"); navigator.serviceworker.register('https://not-example.com/sw.js'); </script> specifications specification status comment content security policy level 3the definition of 'worker-src' in that specification.
DNT - HTTP
Web › HTTP › Headers › DNT
examples reading do not track status from javascript the user's dnt preference can also be read from javascript using the navigator.donottrack property: navigator.donottrack; // "0" or "1" specifications specification status comment tracking preference expression (dnt)the definition of 'dnt header field for http requests' in that specification.
Feature-Policy: battery - HTTP
Web › HTTP › Headers › Feature-Policy › battery
the http feature-policy header battery directive controls whether the current document is allowed to gather information about the acceleration of the device through the batterymanager interface obtained via navigator.getbattery().
Feature-Policy: encrypted-media - HTTP
Web › HTTP › Headers › Feature-Policy › encrypted-media
when this policy is enabled, the promise returned by navigator.requestmediakeysystemaccess() will reject with a domexception.
Feature-Policy: midi - HTTP
Web › HTTP › Headers › Feature-Policy › midi
when this policy is enabled, the promise returned by navigator.requestmidiaccess() will reject with a domexception.
Feature-Policy: publickey-credentials-get - HTTP
Web › HTTP › Headers › Feature-Policy › publickey-credentials-get
the http feature-policy header publickey-credentials-get directive controls whether the current document is allowed to access web authentcation api to create new public-key credentials, i.e, via navigator.credentials.get({publickey: ..., ...}).
Feature-Policy: vibrate - HTTP
Web › HTTP › Headers › Feature-Policy › vibrate
the http feature-policy header vibrate directive controls whether the current document is allowed to trigger device vibrations via navigator.vibrate() method of vibration api.
Feature-Policy: vr - HTTP
Web › HTTP › Headers › Feature-Policy › vr
when this policy is enabled, the promise returned by navigator.getvrdisplays() will reject with a domexception.
web-share - HTTP
Web › HTTP › Headers › Feature-Policy › web-share
the http feature-policy header web-share directive controls controls whether the current document is allowed to use the navigator.share() of web share api to share text, links, images, and other content to arbitrary destiations of user's choice.
Feature-Policy: xr-spatial-tracking - HTTP
Web › HTTP › Headers › Feature-Policy › xr-spatial-tracking
this policy controls whether navigator.xr.requestsession() can return xrsession that requires spatial tracking and whether user agent can indicate support for sessions supporting spatial tracking via navigator.xr.issessionsupported() and devicechange event on navigator.xr object.
Firefox user agent string reference - HTTP
Web › HTTP › Headers › User-Agent › Firefox
see also firefox os user agent string (blog post w/bug 777710 reference) final user agent string for firefox 4 (blog post) recommendations on sniffing the ua string for cross-browser support window.navigator.useragent add android version to fennec ua string (bug 1169772) comments to mozilla.dev.platform ...
Proxy Auto-Configuration (PAC) file - HTTP
Web › HTTP › Proxy servers and tunneling › Proxy Auto-Configuration (PAC) file
history and implementation proxy auto-config was introduced into netscape navigator 2.0 in the late 1990s, at the same time when javascript was introduced.
Authoring MathML - MathML
Web › MathML › Authoring
note that ua string sniffing is not the most reliable method and might break from version to version: var ua = navigator.useragent; var isgecko = ua.indexof("gecko") > -1 && ua.indexof("khtml") === -1 && ua.indexof('trident') === -1; var iswebkit = ua.indexof('applewebkit') > -1 && ua.indexof('chrome') === -1; mathematical fonts in order to get a good layout or to allow different style, it's important to have mathematical fonts available.
Progressive web app structure - Progressive web apps (PWAs)
Web › Progressive web apps › App structure
g,games[i].name) .replace(/author/g,games[i].author) .replace(/twitter/g,games[i].twitter) .replace(/website/g,games[i].website) .replace(/github/g,games[i].github); entry = entry.replace('<a href=\'http:///\'></a>','-'); content += entry; }; document.getelementbyid('content').innerhtml = content; next, it registers a service worker: if('serviceworker' in navigator) { navigator.serviceworker.register('/pwa-examples/js13kpwa/sw.js'); }; the next code block requests permission for notifications when a button is clicked: var button = document.getelementbyid("notifications"); button.addeventlistener('click', function(e) { notification.requestpermission().then(function(result) { if(result === 'granted') { randomnotification(); ...
Making PWAs work offline with Service workers - Progressive web apps (PWAs)
Web › Progressive web apps › Offline Service workers
registering the service worker we'll start by looking at the code that registers a new service worker, in the app.js file: note : we're using the es6 arrow functions syntax in the service worker implementation if('serviceworker' in navigator) { navigator.serviceworker.register('./pwa-examples/js13kpwa/sw.js'); }; if the service worker api is supported in the browser, it is registered against the site using the serviceworkercontainer.register() method.
How to make PWAs re-engageable using Notifications and Push - Progressive web apps (PWAs)
Web › Progressive web apps › Re-engageable Notifications Push
let's explore all of these index.js the index.js file starts by registering the service worker: navigator.serviceworker.register('service-worker.js') .then(function(registration) { return registration.pushmanager.getsubscription() .then(async function(subscription) { // registration part }); }) .then(function(subscription) { // subscription part }); it is a little bit more complicated than the service worker we saw in the js13kpwa demo.
Structural overview of progressive web apps - Progressive web apps (PWAs)
Web › Progressive web apps › Structural overview
,games[i].name) .replace(/author/g,games[i].author) .replace(/twitter/g,games[i].twitter) .replace(/website/g,games[i].website) .replace(/github/g,games[i].github); entry = entry.replace('<a href=\'http:///\'></a>','-'); content += entry; }; document.getelementbyid('content').innerhtml = content; then it registers a service worker: if ("serviceworker" in navigator) { navigator.serviceworker.register("/pwa-examples/js13kpwa/sw.js"); } after that, the app adds a handler for clicks on a button whose id is notifications; this handler requests permission to send notifications to the user, then generates and sends a random notification.
<a> - SVG: Scalable Vector Graphics
Web › SVG › Element › a
for a more widely-supported feature addressing the same use cases, see navigator.sendbeacon().
Mixed content - Web security
Web › Security › Mixed content
<object> (data attribute) navigator.sendbeacon (url attribute) other resource types like web fonts and workers may be considered active mixed content, as they are in chrome.
Secure contexts - Web security
Web › Security › Secure Contexts
if (window.issecurecontext) { // page is a secure context so service workers are now available navigator.serviceworker.register("/offline-worker.js").then(function () { ...