Search completed in 1.60 seconds.
3972 results for "then":
Your results are loading. Please wait...
AuthenticatorAssertionResponse.authenticatorData - Web APIs
the authenticatordata property of the authenticatorassertionresponse interface returns an arraybuffer containing information from the authenticator such as the relying party id hash (rpidhash), a signature counter, test of user presence, user verification flags, and any extensions processed by the authenticator.
... syntax var authnrdata = authenticatorassertionresponse.authenticatordata; value an arraybuffer that has a arraybuffer.bytelength of at least 37 bytes, containing the following fields: rpidhash (32 bytes) - a sha256 hash of the relying party id that was seen by the browser.
... flags (1 bytes) - a bitfield that indicates various attributes that were asserted by the authenticator.
...And 10 more matches
Web Authentication API - Web APIs
the web authentication api is an extension of the credential management api that enables strong authentication with public key cryptography, enabling passwordless authentication and/or secure second-factor authentication without sms texts.
... web authentication concepts and usage the web authentication api (also referred to as webauthn) uses asymmetric (public-key) cryptography instead of passwords or sms texts for registering, authenticating, and second-factor authentication with websites.
... this resolves significant security problems related to phishing, data breaches, and attacks against sms texts or other second-factor authentication methods while at the same time significantly increasing ease of use (since users don't have to manage dozens of increasingly complicated passwords).
...And 52 more matches
Promise.prototype.then() - JavaScript
the then() method returns a promise.
... if one or both arguments are omitted or are provided non-functions, then then will be missing the handler(s), but will not generate any errors.
... if the promise that then is called on adopts a state (fulfillment or rejection) for which then has no handler, the returned promise simply adopts the final state of the original promise on which then was called.
...And 31 more matches
HTTP authentication - HTTP
http provides a general framework for access control and authentication.
... this page is an introduction to the http framework for authentication, and shows how to restrict access to your server using the http "basic" schema.
... the general http authentication framework rfc 7235 defines the http authentication framework, which can be used by a server to challenge a client request, and by a client to provide authentication information.
...And 28 more matches
Integrated Authentication
this document provides an overview of mozilla's support for integrated authentication.
... this entails support for the the simple and protected gss-api negotiation mechanism (spnego) internet standard (rfc 2478) to negotiate either kerberos, ntlm, or other authentication protocols supported by the operating system.
... spnego is commonly referred to as the "negotiate" authentication protocol.
...And 7 more matches
PublicKeyCredentialCreationOptions.authenticatorSelection - Web APIs
authenticatorselection, an optional property of the publickeycredentialcreationoptions dictionary, is an object giving criteria to filter out the authenticators to be used for the creation operation.
... syntax authenticatorselection = publickeycredentialcreationoptions.authenticatorselection value an object with the following properties: authenticatorattachmentoptional a string which is either "platform" or "cross-platform".
... the former describes an authenticator which is bound to the client and which is generally not removable.
...And 7 more matches
AuthenticatorAttestationResponse - Web APIs
the authenticatorattestationresponse interface of the web authentication api is returned by credentialscontainer.create() when a publickeycredential is passed, and provides a cryptographic root of trust for the new key pair that has been generated.
... this interface inherites from authenticatorresponse.
... properties authenticatorattestationresponse.clientdatajson secure contextread only client data for the authentication, such as origin and challenge.
...And 6 more matches
AuthenticatorAssertionResponse - Web APIs
the authenticatorassertionresponse interface of the web authentication api is returned by credentialscontainer.get() when a publickeycredential is passed, and provides proof to a service that it has a key pair and that the authentication request is valid and approved.
... this interface inherites from authenticatorresponse.
... properties authenticatorassertionresponse.clientdatajson secure contextread only the client data for the authentication, such as origin and challenge.
...And 5 more matches
AuthenticatorAttestationResponse.attestationObject - Web APIs
the attestationobject property of the authenticatorattestationresponse interface returns an arraybuffer containing the new public key, as well as signature over the entire attestationobject with a private key that is stored in the authenticator when it is manufactured.
... as part of the credentialscontainer.create() call, an authenticator will create a new keypair as well as an attestationobject for that keypair.
... syntax attestobj = authenticatorattestationresponse.attestationobject properties after decoding the cbor encoded arraybuffer, the resulting javascript object will contain the following properties: authdata the same as authenticatorassertionresponse.authenticatordata.
...And 4 more matches
AuthenticatorAttestationResponse.getTransports() - Web APIs
gettransports() is a method of the authenticatorattestationresponse interface that returns an array containing strings describing the different transports which may be used by the authenticator.
... such transports may be usb, nfc, ble or internal (applicable when the authenticator is not removable from the device).
... note: an authenticatorattestationresponse instance is available on publickeycredential.response after calling navigator.credentials.create().
...And 4 more matches
PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable() - Web APIs
isuserverifyingplatformauthenticatoravailable() is a static method of the publickeycredential interface that returns a promise which resolves to true if a user-verifying platform authenticator is available.
... a user-verifying platform authenticator is a kind of multi-factor authenticator that is part of the client device (it is generally not removable) and that involves an action from the user in order to identify them.
... syntax publickeycredential.isuserverifyingplatformauthenticatoravailable() parameters none.
...And 4 more matches
AuthenticatorAssertionResponse.signature - Web APIs
the signature read-only property of the authenticatorassertionresponse interface is an arraybuffer object which is the signature of the authenticator for both authenticatorassertionresponse.authenticatordata and a sha-256 hash of the client data (authenticatorassertionresponse.clientdatajson).
...it provides the proof that an authenticator does possess the private key which was used for the credential's generation.
... note: an authenticatorassertionresponse instance is available on publickeycredential.response after calling navigator.credentials.get().
...And 3 more matches
Proxy-Authenticate - HTTP
the http proxy-authenticate response header defines the authentication method that should be used to gain access to a resource behind a proxy server.
... it authenticates the request to the proxy server, allowing it to transmit the request further.
... the proxy-authenticate header is sent along with a 407 proxy authentication required.
...And 3 more matches
WWW-Authenticate - HTTP
the http www-authenticate response header defines the authentication method that should be used to gain access to a resource.
... the www-authenticate header is sent along with a 401 unauthorized response.
... header type response header forbidden header name no syntax www-authenticate: <type> realm=<realm>[, charset="utf-8"] directives <type> authentication type.
...And 3 more matches
AuthenticatorResponse.clientDataJSON - Web APIs
the clientdatajson property of the authenticatorresponse interface stores a json string in an arraybuffer, representing the client data that was passed to credentialscontainer.create() or credentialscontainer.get().
... this property is only accessed on one of the child objects of authenticatorresponse, specifically authenticatorattestationresponse or authenticatorassertionresponse.
... syntax var arraybuffer = authenticatorattestationresponse.clientdatajson; var arraybuffer = authenticatorassertionresponse.clientdatajson; value an arraybuffer.
...And 2 more matches
AuthenticatorResponse - Web APIs
the authenticatorresponse interface of the web authentication api is the base interface for interfaces that provide a cryptographic root of trust for a key pair.
... interfaces based on authenticatorresponse below is a list of interfaces based on the authenticatorresponse interface.
... authenticatorassertionresponse authenticatorattestationresponse properties authenticatorresponse.clientdatajson a json string in an arraybuffer, representing the client data that was passed to credentialscontainer.create() or credentialscontainer.get().
...And 2 more matches
AuthenticatorAssertionResponse.userHandle - Web APIs
the userhandle read-only property of the authenticatorassertionresponse interface is an arraybuffer object which is an opaque identifier for the given user.
... note: an authenticatorassertionresponse instance is available on publickeycredential.response after calling navigator.credentials.get().
... syntax userhandle = authenticatorassertionresponse.userhandle value an arraybuffer object which is an opaque identifier for the current user.
...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 api for accessing public key credentials level 1the definition of 'userhandle' in that specification.
NPN_GetAuthenticationInfo - Archive of obsolete content
« gecko plugin api reference « browser side plug-in api summary the function is called by plugins to get http authentication information from the browser.
... syntax #include <npapi.h> nperror npn_getauthenticationinfo(npp instance, const char *protocol, const char *host, int32_t port, const char *scheme, const char *realm, char **username, uint32_t *ulen, char **password, uint32_t *plen); parameters this function has the following parameters: instance pointer to the current plug-in instance protocol protocol name (uri scheme) host host name port port number scheme http authentication scheme name realm http authentication realm user...
...this function allows the plugin to ask the browser for http authentication information for a domain.
BluetoothCharacteristicProperties.authenticatedSignedWrites - Web APIs
the authenticatedsignedwrites read-only property of the bluetoothcharacteristicproperties interface returns a boolean that is true if signed writing to the characteristic value is permitted.
... syntax var aboolean = bluetoothcharacteristicproperties.authenticatedsignedwrites; value a boolean.
... specifications specification status comment web bluetooththe definition of 'authenticatedsignedwrites' in that specification.
407 Proxy Authentication Required - HTTP
WebHTTPStatus407
the http 407 proxy authentication required client error status response code indicates that the request has not been applied because it lacks valid authentication credentials for a proxy server that is between the browser and the server that can access the requested resource.
... this status is sent with a proxy-authenticate header that contains information on how to authorize correctly.
... status 407 proxy authentication required example response http/1.1 407 proxy authentication required date: wed, 21 oct 2015 07:28:00 gmt proxy-authenticate: basic realm="access to internal site" specifications specification title rfc 7235, section 3.2: 407 proxy authentication required http/1.1: authentication ...
511 Network Authentication Required - HTTP
WebHTTPStatus511
the http 511 network authentication required response status code indicates that the client needs to authenticate to gain network access.
... network operators sometimes require some authentication, acceptance of terms, or other user interaction before granting access (for example in an internet café or at an airport).
... status 511 network authentication required specifications specification title rfc 6585, section 6: 511 network authentication required additional http status codes ...
Challenge-response authentication - MDN Web Docs Glossary: Definitions of Web-related terms
the http authentication protocol is challenge-response based, though the "basic" protocol isn't using a real challenge (the realm is always the same).
... learn more challenge-response authentication on wikipedia.
Index - Web APIs
WebAPIIndex
once put into an audiobuffer, the audio can then be played by being passed into an audiobuffersourcenode.
...if no time is specified, then the sound stops playing immediately.
... 216 authenticatorassertionresponse api, authentication, authenticatorassertionresponse, interface, reference, web authentication api, webauthn the authenticatorassertionresponse interface of the web authentication api is returned by credentialscontainer.get() when a publickeycredential is passed, and provides proof to a service that it has a key pair and that the authentication request is valid an...
...And 136 more matches
Introduction to SSL - Archive of obsolete content
ssl has been universally accepted on the world wide web for authenticated and encrypted communication between clients and servers.
...it uses tcp/ip on behalf of the higher-level protocols, and in the process allows an ssl-enabled server to authenticate itself to an ssl-enabled client, allows the client to authenticate itself to the server, and allows both machines to establish an encrypted connection.
... these capabilities address fundamental concerns about communication over the internet and other tcp/ip networks: ssl server authentication allows a user to confirm a server's identity.
...And 64 more matches
Introduction to Public-Key Cryptography - Archive of obsolete content
authentication allows the recipient of information to determine its origin-that is, to confirm the sender's identity.
... certificates and authentication managing certificates certificates and authentication a certificate identifies someone or something authentication confirms an identity how certificates are used contents of a certificate how ca certificates are used to establish trust a certificate identifies someone or something a certificate is an electronic document used to identify an individual, a server, a company, or some other entity and to associate that identity with a public key.
... authentication confirms an identity authentication is the process of confirming an identity.
...And 63 more matches
sslfnc.html
warning: if you turn this option off, the session will not be an ssl session and will not have certificate-based authentication, tamper detection, or encryption.
... ssl_request_certificate is a server option that requests a client to authenticate itself.
... ssl_require_certificate is a server option that requires a client to authenticate itself (only if ssl_request_certificate is also on).
...And 57 more matches
Graceful asynchronous programming with Promises - Learn web development
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() to update a status display with the message "calling...", indica...
...it then calls getusermedia(), asking for a stream that has both video and audio tracks, then once that's been obtained, sets up a video element to show the stream coming from the camera as a "self view," then takes each of the stream's tracks and adds them to the webrtc rtcpeerconnection representing a connection to another user.
... you then place your order.
...And 42 more matches
Eclipse CDT
set an initial heap space of 1 gb and max heap space of 5 gb, say, by modifying the values of the following two lines in eclipse.ini: -xms1g -xmx5g if you fail to increase these limits, then you will likely find that eclipse either hangs when it tries to index the mozilla source or else that the code intelligence is very broken after the indexing "completes".
... once your build is complete, mach can then generate a useful eclipse project on your behalf.
...then, to create the eclipse project and open it, run: ./mach ide eclipse or to create the eclipse project without opening it yet, run: ./mach build-backend -b cppeclipse building the eclipse project should only take a few seconds.
...And 35 more matches
Index - Archive of obsolete content
the issue that is commonly overlooked here is that the rss feed could contain some malicious javascript code and it would then execute with the privileges of the extension — meaning that it would get full access to the browser (cookies, history etc) and to user’s files.
...rdf a multiple item package provides the ability to package multiple installable bundles which can then be downloaded and installed by a user, or provided pre-packaged with an application or by an external program.
...some items mentioned are strict guidelines, meaning that if you don't follow them then your add-on will not be approved on mozilla add-ons.
...And 34 more matches
Index
MozillaTechXPCOMIndex
but then, you can't use the venkman ui.
... 84 using nsiclassinfo xpcom if you use a c++ class which implements nsiclassinfo from javascript, then you don't have to explicitly call queryinterface on the javascript object to access the object's interfaces.
...hashtables may seem like arrays, but there are important differences: 114 how to build an xpcom component in javascript add-ons, extensions, javascript, tutorial, xpcom if you are looking for add-on sdk solution for xpcom javascript components then check out platform/xpcom module first.
...And 34 more matches
Client-side storage - Learn web development
previous overview: client-side web apis modern web browsers support a number of ways for web sites to store data on the user's computer — with the user's permission — then retrieve it when necessary.
...most major modern web sites are dynamic — they store data on the server using some kind of database (server-side storage), then run server-side code to retrieve needed data, insert it into static page templates, and serve the resulting html to the client to be displayed by the user's browser.
...on the user's machine) and then retrieve it when needed.
...And 25 more matches
Using Service Workers - Web APIs
however, it made many assumptions about what you were trying to do and then broke horribly when your app didn’t follow those assumptions exactly.
...using a service worker you can easily set an app up to use cached assets first, thus providing a default experience even when offline, before then getting more data from the network (commonly known as offline first).
...when the service worker is installed, it then receives an activate event.
...And 25 more matches
Setting up your own test automation environment - Learn web development
paste the following into the bottom of your file (updating the path as it actually is on your machine): #add webdriver browser drivers to path export path=$path:/users/bob save and close this file, then restart your terminal/command prompt to reapply your bash configuration.
... create a new file inside your project directory called google_test.js: give it the following contents, then save it: const webdriver = require('selenium-webdriver'), by = webdriver.by, until = webdriver.until; const driver = new webdriver.builder() .forbrowser('firefox') .build(); driver.get('http://www.google.com'); driver.findelement(by.name('q')).sendkeys('webdriver'); driver.sleep(1000).then(function() { driver.findelement(by.name('q')).sendkeys(webdriver.key.tab); }); driv...
...er.findelement(by.name('btnk')).click(); driver.sleep(2000).then(function() { driver.gettitle().then(function(title) { if(title === 'webdriver - google search') { console.log('test passed'); } else { console.log('test failed'); } driver.quit(); }); }); in terminal, make sure you are inside your project folder, then enter the following command: node google_test you should see an instance of firefox automatically open up!
...And 24 more matches
Signaling and video calling - Web APIs
function sendtooneuser(target, msgstring) { var isunique = true; var i; for (i=0; i<connectionarray.length; i++) { if (connectionarray[i].username === target) { connectionarray[i].send(msgstring); break; } } } this function iterates over the list of connected users until it finds one matching the specified username, then sends the message to that user.
... once the two peers agree upon a mutually-compatible candidate, that candidate's sdp is used by each peer to construct and open a connection, through which media then begins to flow.
...your workflow may also demand login/authentication functionality, but such details will vary.
...And 24 more matches
Index
the programmer's task is to initialize nss with the required parameters (such as a database), and nss will then transparently manage the database files.
...then you attempt to verify the signature found in (a) using the public key found in (b).
...create a context handle while providing all the parameters required for the operation, then call an “update” function multiple times to pass subsets of the input to nss.
...And 23 more matches
core/promise - Archive of obsolete content
in the add-on sdk we follow commonjs promises/a specification and model a promise as an object with a then method, which can be used to get the eventual return (fulfillment) value or thrown exception (rejection): foo().then(function success(value) { // ...
... propagation the then method of a promise returns a new promise that is resolved with the return value of either handler.
... var bar = foo().then(function success(value) { // compute something from a value...
...And 22 more matches
Examples
components.utils.import("resource://gre/modules/osfile.jsm") let path = os.path.join(os.constants.path.tmpdir, "file.txt"); let promise = os.file.exists(path); let newpromise = promise.then(function onfulfill(aexists) { if (aexists) { console.log("you have file.txt in your temporary directory."); } else { throw new error("you don't have file.txt in your temporary directory."); } }); // unexpected errors should always be reported at the end of a promise chain.
... let lastpromise = newpromise.then(function onfulfill(){ }) .catch(function onreject(arejectreason) { console.warn('newpromise failed with reason: ', arejectreason); }); using a promise returned by a function (verbose) this example uses a verbose syntax, showing all the involved promises.
... components.utils.import("resource://gre/modules/osfile.jsm") let path = os.path.join(os.constants.path.tmpdir, "file.txt"); let promise = os.file.exists(path); let newpromise = promise.then(function onfulfill(aexists) { if (aexists) { console.log("you have file.txt in your temporary directory."); } else { console.log("you don't have file.txt in your temporary directory."); } }); // unexpected errors should always be reported at the end of a promise chain.
...And 21 more matches
Using IndexedDB - Web APIs
if the database doesn't already exist, it is created by the open operation, then an onupgradeneeded event is triggered and you create the database schema in the handler for this event.
...error events are targeted at the request that generated the error, then the event bubbles to the transaction, and then finally to the database object.
...if you need to change an existing object store (e.g., to change the keypath), then you must delete the old object store and create it again with the new options.
...And 21 more matches
Index - MDN Web Docs Glossary: Definitions of Web-related terms
63 callback function callback, callback function, codingscripting, glossary a callback function is a function passed into another function as an argument, which is then invoked inside the outer function to complete some kind of routine or action.
... 66 card sorting card sorting, design, glossary card sorting is a simple technique used in information architecture whereby people involved in the design of a website (or other type of product) are invited to write down the content / services / features they feel the product should contain, and then organize those features into categories or groupings.
...the name comes from the fact that often card sorting is carried out by literally writing the items to sort onto cards, and then arranging the cards into piles.
...And 20 more matches
Promise - JavaScript
when either of these options happens, the associated handlers queued up by a promise's then method are called.
... as the promise.prototype.then() and promise.prototype.catch() methods return promises, they can be chained.
... chained promises the methods promise.then(), promise.catch(), and promise.finally() are used to associate further action with a promise that becomes settled.
...And 20 more matches
Using readable streams - Web APIs
if not, we suggest that you first read the streams concepts and usage overview and dedicated streams api concepts article, then come back.
... as our simple stream pump example shows (see it live also), exposing it is a matter of just accessing the body property of the response: // fetch the original image fetch('./tortoise.png') // retrieve its body as readablestream .then(response => response.body) this provides us with a readablestream object.
...this is done using the readablestream.getreader() method: // fetch the original image fetch('./tortoise.png') // retrieve its body as readablestream .then(response => response.body) .then(body => { const reader = body.getreader(); invoking this method creates a reader and locks it to the stream — no other reader may read this stream until this reader is released, e.g.
...And 19 more matches
Inputs and input sources - Web APIs
in this guide, we'll look at how to use webxr's input device management features to determine what input sources are available and how to then monitor those sources for inputs in order to handle user interactivity with your virtual or augmented environment.
... to manage input sources, then, you need to be able to enumerate input sources, examine profile information about each input source, and decide how to use each input controller.
...not only would this controller then take the responsibility of clicking through the user interface of your app, but it would also be considered the "main hand," while other controllers would then be off-hand or additional controllers.
...And 19 more matches
Movement, orientation, and motion: A WebXR example - Web APIs
del-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 references are obtained to the four <div> blocks into which we'll output the current contents of each of the key matrices for informational purposes while our scene is running.
... then we look to see if navigator.xr is defined.
...And 19 more matches
Window.open() - Web APIs
WebAPIWindowopen
if the name doesn't exist, then a new browsing context is opened in a new tab or a new window, and the specified resource is loaded into it.
...if url is an empty string, then a new blank, empty window (url about:blank) is created with the default toolbars of the main window.
...s"; function openrequestedpopup() { windowobjectreference = window.open("http://www.cnn.com/", "cnn_windowname", windowfeatures); } var windowobjectreference; function openrequestedpopup() { windowobjectreference = window.open( "http://www.domainname.ext/path/imagefile.png", "descriptivewindowname", "resizable,scrollbars,status" ); } if a window with the name already exists, then url is loaded into the existing window.
...And 19 more matches
Fetching data from the server - Learn web development
ic.html and the four text files — verse1.txt, verse2.txt, verse3.txt, and verse4.txt.) inside the updatedisplay() function, find the xhr code: let request = new xmlhttprequest(); request.open('get', url); request.responsetype = 'text'; request.onload = function() { poemdisplay.textcontent = request.response; }; request.send(); replace all the xhr code with this: fetch(url).then(function(response) { response.text().then(function(text) { poemdisplay.textcontent = text; }); }); load the example in your browser (running it through a web server) and it should work just the same as the xhr version, provided you are running a modern browser.
... after that, you can see the .then() method chained onto the end of fetch() — this method is a part of promises, a modern javascript feature for performing asynchronous operations.
... fetch() returns a promise, which resolves to the response sent back from the server — we use .then() to run some follow-up code after the promise resolves, which is the function we've defined inside it.
...And 18 more matches
Promise
once you have a reference to a promise, you can call its then() method to execute an action when the value becomes available, or when an error occurs.
... method overview promise then([optional] function onfulfill, [optional] function onreject); promise catch([optional] function onreject); constructor creates a new promise, initially in the pending state, and provides references to the resolving functions that can be used to change its state.
... note: calling this method with a pending promise as the avalue argument, and then calling it again with another value before the promise is fulfilled or rejected, will have no effect the second time, as the associated promise is already resolved to the pending promise.
...And 17 more matches
nsIFile
if this nsifile does not reference a symbolic link, then the value of this attribute is undefined.
...if this nsifile does not reference a symbolic link, then the value of this attribute is undefined.
...if this nsifile does not reference a symbolic link, then the value of this attribute is undefined.
...And 17 more matches
Timing element visibility with the Intersection Observer API - Web APIs
in this article, we'll build a mock blog which has a number of ads interspersed among the contents of the page, then use the intersection observer api to track how much time each ad is visible to the user.
...then the "wrapper" class is defined; it wraps the entire blog, including the header, sidebar, and body content (articles and ads).
...then we set up an event listener for the visibilitychange event.
...And 17 more matches
HTTP Index - HTTP
WebHTTPIndex
http follows a classical client-server model, with a client opening a connection to make a request, then waiting until it receives a response.
... 22 reason: cors disabled authentication, authentication article, cors, cross-origin, disabled, errors, http, https, messages, resource, same origin, same-origin, security, sharing, validation, secure, troubleshooting a request that needs to use cors was attempted, but cors is disabled in the user's browser.
... 42 http authentication access control, authentication, guide, http, security http provides a general framework for access control and authentication.
...And 17 more matches
Introduction to automated testing - Learn web development
inside this file, put the following: const gulp = require('gulp'); gulp.task('default', function() { console.log('gulp running'); }); this requires the gulp module we installed earlier, and then runs a basic task that does nothing except for printing a message to the terminal — this is useful for letting us know that gulp is working.
... to use each plugin, you need to first install it via npm, then require any dependencies at the top of the gulpfile.js file, then add your test(s) to the bottom of it, and finally add the name of your task inside the default task.
...ion css(cb) { return gulp.src('src/style.css') .pipe(csslint()) .pipe(csslint.formatter('compact')) .pipe(autoprefixer({ browsers: ['last 5 versions'], cascade: false })) .pipe(gulp.dest('build')); cb(); } here we grab our style.css file, run csslint on it (which outputs a list of any errors in your css to the terminal), then runs it through autoprefixer to add any prefixes needed to make nascent css features run in older browsers.
...And 16 more matches
Attestation and Assertion - Web APIs
there are two different types of certificates used in webauthn for registration and authentication.
...the sections below describe attestation, which happens during registration, and assertion which happens during authentication.
... attestation when an authenticator registers a new key pair with a service, the authenticator signs the public key with an attestation certificate.
...And 16 more matches
passwords - Archive of obsolete content
usage a credential is the set of information a user supplies to authenticate herself with a service.
...you can then use the credentials to access their related service (for example, by logging into a web site).
... you can use the passwords api with three sorts of credentials: add-on credentials html form credentials http authentication credentials add-on credential these are associated with your add-on rather than a particular web site.
...And 15 more matches
Making asynchronous programming easier with async and await - Learn web development
to actually consume the value returned when the promise fulfills, since it is returning a promise, we could use a .then() block: hello().then((value) => console.log(value)) or even just shorthand such as hello().then(console.log) like we saw in the last article.
...this can be put in front of any async promise-based function to pause your code on that line until the promise fulfills, then return the resulting value.
... here is a trivial example: async function hello() { return greeting = await promise.resolve("hello"); }; hello().then(alert); of course, the above example is not very useful, although it does serve to illustrate the syntax.
...And 15 more matches
Introducing asynchronous JavaScript - Learn web development
we then give it some text content.
... function() { callback(xhr.response); }; xhr.send(); } function displayimage(blob) { let objecturl = url.createobjecturl(blob); let image = document.createelement('img'); image.src = objecturl; document.body.appendchild(image); } loadasset('coffee.jpg', 'blob', displayimage); here we create a displayimage() function that simply represents a blob passed to it as an object url, then creates an image to display the url in, appending it to the document's <body>.
... however, we then create a loadasset() function that takes a callback as a parameter, along with a url to fetch and a content type.
...And 15 more matches
Viewpoints and viewers: Simulating cameras in WebXR - Web APIs
our renderer needs to know where we imagine the camera to be, then alter the position of every visible object to simulate that position and orientation.
... when accelerating bitmapped graphics, the renderer would draw the 2d image into a webgl texture's buffer, then redraw the texture to refresh the screen.
...before we can do so, and before we can then simulate the movement of the camera, let's actually take a look at the virtual camera and how it can move, at the most fundamental level.
...And 15 more matches
Bytecode Descriptions
convert val to a numeric value, then push -val.
...val is converted to an integer, then bitwise negated.
...val is first converted with toboolean, then logically negated.
...And 14 more matches
nsIVariant
if the value was utf16 then the high bits are lost.
... if the value was utf8 then it is converted to utf16 and the high bits are discarded.
...return value if possible, the internal value is converted to a double, which is then compared to zero.
...And 14 more matches
Using DTMF with WebRTC - Web APIs
this article offers a brief high-level overview of how dtmf works over webrtc, then provides a guide for everyday developers about how to send dtmf over an rtcpeerconnection.
...the rtcrtpsender will then send the tones to the other peer as packets alongside the track's audio data.
... simple example this simple example constructs two rtcpeerconnections, establishes a connection between them, then waits for the user to click a "dial" button.
...And 14 more matches
Controlling Ratios of Flex Items Along the Main Axis - CSS: Cascading Style Sheets
.item { flex: 2 1 auto; } if you have read the article basic concepts of flexbox, then you will have already had an introduction to the properties.
...this then, is the min-content size of that string.
...for example, if i have a 500 pixel-wide container, flex-direction is row, and i have three flex items each 100 pixels wide, then i have 200 pixels of positive free space, which could be distributed between the items if i wanted them to fill the container.
...And 14 more matches
Using Promises - JavaScript
+ result); } function failurecallback(error) { console.error("error generating audio file: " + error); } createaudiofileasync(audiosettings, successcallback, failurecallback); modern functions return a promise that you can attach your callbacks to instead: if createaudiofileasync() were rewritten to return a promise, using it could be as simple as this: createaudiofileasync(audiosettings).then(successcallback, failurecallback); that's shorthand for: const promise = createaudiofileasync(audiosettings); promise.then(successcallback, failurecallback); we call this an asynchronous function call.
... callbacks added with then(), as above, will be called even after the success or failure of the asynchronous operation.
... multiple callbacks may be added by calling then() several times.
...And 14 more matches
Drawing graphics - Learn web development
you could use css, but the trouble then is that the sizing is done after the canvas has rendered, and just like any other image (the rendered canvas is just an image), the image could become pixellated/distorted.
...add the following lines at the bottom of your javascript: ctx.fillstyle = 'rgb(0, 0, 0)'; ctx.fillrect(0, 0, width, height); here we are setting a fill color using the canvas' fillstyle property (this takes color values just like css properties do), then drawing a rectangle that covers the entire area of the canvas with thefillrect method (the first two parameters are the coordinates of the rectangle's top left hand corner; the last two are the width and height you want the rectangle drawn at — we told you those width and height variables would be useful)!
... drawing shapes tends to be done using the rectangle shape primitive, or by tracing a line along a certain path and then filling in the shape.
...And 13 more matches
HTTP Cache
important difference in behavior from the old cache: when the cache entry object is already present in memory or open as “force-new” (a.k.a “open-truncate”) this callback is invoked sooner then the asyncopenuri method returns (i.e.
... the consumer then indicates the cache entry needs to be revalidated by returning entry_needs_revalidation from oncacheentrycheck.
... the consumer is then responsible to validate the partial content cache entry with the network server and attempt to load the rest of the data.
...And 13 more matches
WebIDL bindings
note that if you're adding new interfaces, then the test at dom/tests/mochitest/general/test_interfaces.html will most likely fail.
...ns_impl_cycle_collection_wrappercache_0(myclass) ns_impl_cycle_collecting_addref(myclass) ns_impl_cycle_collecting_release(myclass) ns_interface_map_begin_cycle_collection(myclass) ns_wrappercache_interface_map_entry ns_interface_map_entry(nsisupports) ns_interface_map_end if your class doesn't inherit from a class that implements getparentobject, then add a function of that name that, for a given instance of your class, returns the same object every time (unless you write explicit code that handles your parent object changing by reparenting js wrappers, as nodes do).
...if the type is not in the header file one gets by replacing '::' with '/' and appending '.h', then add a corresponding 'headerfile' annotation (or headerfile annotation to the .webidl file).
...And 13 more matches
WebGL model view projection - Web APIs
clip space in a webgl program, data is typically uploaded to the gpu with its own coordinate system and then the vertex shader transforms those points into a special coordinate system known as clip space.
...however, if a triangle straddles the border of this space then it is chopped up into new triangles, and only the parts of the new triangles that are in clip space are kept.
...normally model data is used that is in some arbitrary coordinate system, and is then transformed using a matrix, converting the model coordinates into the clip space coordinate system.
...And 13 more matches
Anonymous Content - Archive of obsolete content
an element declared in a bound document using a single tag can then be constructed out of multiple child elements, and this implementation is hidden from the bound document.
...if the binding specifies no insertion points for explicit content, then anonymous content will only be constructed if the bound element has no explicit children.
...if no insertion point is found for the newly-inserted child, then the binding is no longer a fit for the bound element, and all anonymous content will be destroyed.
...And 12 more matches
The Implementation of the Application Object Model - Archive of obsolete content
the data itself can be fed in from any number of different sources (e.g., from a local file system, from your bookmarks file, or from some remote downloadable rdf file), and can then be combined into a single graph.
...a site admin could add new bookmarks to the file, and then the user would pick them up.
...if nglayout's formatting objects aren't used to render the widgetry, then drawing code has to be written for each and every widget.
...And 12 more matches
Cooperative asynchronous JavaScript: Timeouts and intervals - Learn web development
if you execute code like settimeout(fn, 0) but then immediately after run a loop that counts from 1 to 10 billion, your callback will be executed after a few seconds.
... in the following example, the browser will wait two seconds before executing the anonymous function, then will display the alert message (see it running live, and see the source code): let mygreeting = settimeout(function() { alert('hello, mr.
...the following function creates a new date() object, extracts a time string out of it using tolocaletimestring(), and then displays it in the ui.
...And 12 more matches
Eclipse CDT Manual Setup
if that is not the case, then get your build going now so that it can be running while you continue with the instructions below.
...if eclipse can successfully identify which source file was being compiled, then it can associate with that file the resolvable include paths, preprocessor defines, and pre-include files that were passed to the compiler.
... conversely, note this very carefully: if you configure eclipse to invoke a build process that is parallelized, silenced, or that fails to identify the directory that the compiler is being run from, then it will mess up the compiler options that eclipse associates with your files, and that in turn will significantly degrade the quality of the code assistance that eclipse will provide after it next re-indexes the code.
...And 12 more matches
Index
the allocation will then be retried (and may still fail.) 68 js::setoutofmemorycallback jsapi reference, reference, référence(2), spidermonkey unlike the error reporter, which is only called if the exception for an oom bubbles up and is not caught, the js::outofmemorycallback is called immediately at the oom site to allow the embedding to capture the current state of heap allocation before anything...
... 103 jsextendedclass.wrappedobject jsapi reference, obsolete, spidermonkey if a class has the jsclass_is_extended bit set in its jsclass.flags and has a non-null jsextendedclass.wrappedobject, then objects of that class may be wrappers.
...the intent is to support interactive compilation - accumulate lines in a buffer until js_bufferiscompilableunit is true, then pass it to the compiler.
...And 12 more matches
Capabilities, constraints, and settings - Web APIs
the result has been a lot of very fragile code, or a reliance on libraries which figure this stuff out for you, then implement polyfills to patch the holes in the implementation on your behalf.
... once the script knows whether the property or properties it wishes to use are supported, it can then check the capabilities of the api and its implementation by examining the object returned by the track's getcapabilities() method; this object lists each supported constraint and the values or range of values which are supported.
... the prioritization of the properties is simple: if two properties' requested values are mutually exclusive, then the one listed first in the constraint set will be used.
...And 12 more matches
A basic 2D WebGL animation example - Web APIs
then the final position is computed by multiplying the rotated position by the scaling vector provided by the javascript code in uscalingfactor.
... the standard webgl global gl_position is then set to the transformed and rotated vertex's position.
...then we set the global gl_fragcolor to the value of the uniform uglobalcolor, which is set by the javascript code to the color being used to draw the square.
...And 12 more matches
MCD, Mission Control Desktop, AKA AutoConfig - Archive of obsolete content
all users have a personal account on a windows server (ad) and an ldap account for linux authentication.
... thunderbird.cfg (version 1) here's the complete file, first we get the user login name from environment variables, then configure the ldap address book, create an email account, and configure imap and smtp: [root@calaz /usr/lib/thunderbird] $ cat thunderbird.cfg //put everything in a try/catch try { // 1) env variables if(getenv("user") != "") { // *nix settings var env_user = getenv("user"); var env_home = getenv("home"); } else { // windows settings var env_user = getenv("username"); var env_home =...
...g works fine, we just set to env variable to check the read of thunderbird.cfg file: $ export nspr_log_modules=mcd:5 $ export nspr_log_file=/tmp/thunderbird-log.txt when thunderbird has started, you should read: $ cat /tmp/thunderbird-log.txt -1209403040[808a788]: general.config.filename = thunderbird.cfg -1209403040[808a788]: evaluating .cfg file thunderbird.cfg with obscurevalue 0 clean then, to be sure to start with a fresh thunderbird account, don't do this if you already have one and want to preserve your emails and preferences!
...And 11 more matches
Choosing the right approach - Learn web development
asynchronous callbacks generally found in old-style apis, involves a function being passed into another function as a parameter, which is then invoked when an asynchronous operation has been completed, so that the callback can in turn do something with the result.
... single delayed operation repeating operation multiple sequential operations multiple simultaneous operations yes yes (recursive timeouts) yes (nested timeouts) no code example here the browser will wait two seconds before executing the anonymous function, then will display the alert message (see it running live, and see the source code): let mygreeting = settimeout(function() { alert('hello, mr.
...epeatedly in a similar fashion to setinterval(), using code like this: let i = 1; settimeout(function run() { console.log(i); i++; settimeout(run, 100); }, 100); there is a difference between recursive settimeout() and setinterval(): recursive settimeout() guarantees at least the specified amount of time (100ms in this example) will elapse between the executions; the code will run and then wait 100 milliseconds before it runs again.
...And 11 more matches
Handling common JavaScript problems - Learn web development
the trouble with javascript historically, javascript was plagued with cross-browser compatibility problems — back in the 1990s, the main browser choices back then (internet explorer and netscape) had scripting implemented in different language flavours (netscape had javascript, ie had jscript and also offered vbscript as an option), and while at least javascript and jscript were compatible to some degree (both based on the ecmascript specification), things were often implemented in conflicting, incompatible ways, causing developers many nightmares.
...jquery (or whatever library you are using) will then handle the differences in the background, so you don't have to.
... things have improved significantly since then; modern browsers do a good job of supporting "classic javascript features", and the requirement to use such code has diminished as the requirement to support older browsers has lessened (although bear in mind that they have not gone away altogether).
...And 11 more matches
Debugging on Mac OS X
creating an xcode project if you try to create a new xcode project in an existing directory then xcode will delete its existing contents (xcode will warn you beforehand).
... to work around that, the steps below have you initialize the project outside the mozilla source tree, close the project, copy the .xcodeproj project "file" into the source tree, and then reopen the project to finish setting it up.
...if you try to do that then xcode will simply copy the source files under the project directory rather than link to them (still the case in xcode 10?) which breaks debugging and the possibility to modify-rebuild-relaunch from inside xcode.
...And 11 more matches
GCIntegration - SpiderMonkey Redirect 1
if, in the middle of an incremental gc, a pointer to an object x is destroyed (meaning overwritten or no longer traced for some reason), then x will be marked.
... to understand the problem more, let's consider some reasons why barriers are not needed in common areas of firefox: if a pointer is never changed after it's initialized, then there's no need for a write barrier.
... if a pointer is not traced via js_call_tracer or any similar mechanism, then there's no need for a write barrier (although see below about read barriers).
...And 11 more matches
JSAPI User Guide
then it adds whatever custom classes, functions, and variables (like window) the application wants to provide; see custom objects below.
...then call js_definefunctions.
...instead, spidermonkey simply returns false or nullptr to the application, which can then handle the error as it chooses—or just return false to let it propagate further up the stack.
...And 11 more matches
Adding 2D content to a WebGL context - Web APIs
the vertex shader must perform the needed transforms on the vertex's position, make any other adjustments or calculations it needs to make on a per-vertex basis, then return the transformed vertex by saving it in a special variable provided by glsl, called gl_position.
...this information can then be stored in varyings or attributes as appropriate to be shared with the fragment shader.
...that position is then multiplied by two 4x4 matrices we provide called uprojectionmatrix and umodelviewmatrix; gl_position is set to the result.
...And 11 more matches
Basic Concepts of grid layout - CSS: Cascading Style Sheets
the features shown in this overview will then be explained in greater detail in the rest of this guide.
...this layering may then be controlled with the z-index property.
...click this and then the grid on this element will be overlaid in the browser window.
...And 11 more matches
background-position - CSS: Cascading Style Sheets
the other dimension is then set to 50%, so the item is placed in the middle of the edge specified.
...if left or right are given here, then this defines x and the other given value defines y.
... if top or bottom are given, then this defines y and the other value defines x.
...And 11 more matches
Space Manager Detailed Design - Archive of obsolete content
if more than ns_space_manager_cache_size are allocated at a time,then standard allocation is used.
...if the collection is too small, then an error is returned and the count is updated to indicate the size required.
... the algorithm to provide the band data is as follows: get a vertical offset in world coordinates (instead of frame-relative coordinates) by adding the y-origin of the spacemanager to the y offset passed in if the (adjusted) y value passed in is greater than the greatest band being managed, then all space is available so a single trapezoid is returned,marked as available and sized to the maximum size value (passed in).
...And 10 more matches
Organizing your CSS - Learn web development
keep it consistent if you get to set the rules for the project or are working alone, then the most important thing to do is to keep things consistent.
... then we can add everything that is used sitewide.
... article.main p.box { border: 1px solid #ccc; } if you then wanted to apply the same rules to something outside of main, or to something other than a <p>, you would have to add another selector to these rules or create a whole new ruleset.
...And 10 more matches
Third-party APIs - Learn web development
note: you might want to just get all our code examples at once, in which case you can then just search the repo for the example files you need in each section.
...this typically involves first linking to a javascript library available on the server via a <script> element, as seen in our mapquest example: <script src="https://api.mqcdn.com/sdk/mapquest-js/v1.3.2/mapquest.js"></script> <link type="text/css" rel="stylesheet" href="https://api.mqcdn.com/sdk/mapquest-js/v1.3.2/mapquest.css"/> you can then start using the objects available in that library.
... for example: let map = l.mapquest.map('map', { center: [53.480759, -2.242631], layers: l.mapquest.tilelayer('map'), zoom: 12 }); here we are creating a variable to store the map information in, then creating a new map using the mapquest.map() method, which takes as its parameters the id of a <div> element you want to display the map in ('map'), and an options object containing the details of the particular map we want to display.
...And 10 more matches
Aprender y obtener ayuda - Learn web development
focused thinking is great for concentrating hard on specific subjects, getting into deep problem solving, and improving your mastery of the techniques required — strengthening the neural pathways in your brain where that information is stored.
...this is the opposite of focus — you let your brain wander around the wider landscape, searching around for connections you didn't have before, touching on new things (or new combinations of things) that you can then focus on later, to strengthen them and start to really understand what they mean.
... it is also why you can sometimes get really stuck on a problem, but then figure out the answer when you go for a coffee break (or a walk).
...And 10 more matches
Application cache implementation overview
nsiapplicationcache is then queried a client id (= the manifest url + a unique time stamp).
... then, nsicacheservice is asked to open nsicachesession with store_offline policy and the given client id.
...nshttpchannel::onofflinecacheentryavailable is then invoked.
...And 10 more matches
IME handling guide
then, converts each clause with chinese characters: "私の", "名前は" and "中野です" (in the following screenshot each clause is underlined and not connected adjacently.
...then, startcomposition(), setpendingcomposition(), flushpendingcomposition(), commitcomposition(), etc.
...then, it sends the events and the event target to imestatemanager.
...And 10 more matches
JIT Optimization Strategies
it then directly inlines the value of the property into hot code that accesses it.
...if a property has always contained the same uniquely-typed object, then the engine can use the unique type to map back to a specific object, and eliminate the property access, replacing it with a constant reference to the object.
... consider the following constructor: function point(x, y) { this.x = x; this.y = y; } if only integers are ever stored in the x and y properties, then the instances of point will be represented in an "unboxed" mode - with the property values stored as raw 4-byte values within the object.
...And 10 more matches
nsITransport
flags have the following meaning: open_blocking if specified, then the resulting stream will have blocking stream semantics.
... this means that if the stream has no data and is not closed, then reading from it will block the calling thread until at least one byte is available or until the stream is closed.
... if this flag is not specified, then the stream has non-blocking stream semantics.
...And 10 more matches
Add to iPhoto
to do that, we first need to declare the cfarraycallbacks structure: this.cfarraycallbacks = new ctypes.structtype("cfarraycallbacks", [ {'version': cfindex}, {'retain': ctypes.voidptr_t}, {'release': ctypes.voidptr_t}, {'copydescription': ctypes.voidptr_t}, {'equal': ctypes.voidptr_t} ]); having done this, we can then import the kcftypearraycallbacks structure.
...text menu is clicked when the user right-clicks an image, our handler gets called: onpopup: function() { var node = iphoto.getcurrentnode(); var item = document.getelementbyid("add-to-iphoto_menuitem"); if (item) { item.hidden = (node == null); // hide it if we're not on an image } } this code finds the image node the user right-clicked in by calling our getcurrentnode() method, then sets the hidden state of the "add image to iphoto" menu item based on whether or not an image node was found.
... add: function() { var node = iphoto.getcurrentnode(); if (node) { var src = node.getattribute("src"); // get the url of the image if (src && src != "") { iphoto.addimagebyurl(src); } } } this fetches the node representing the image the user wants to add, and, if it's an image, fetches the image's url from its src attribute, then passes it into our addimagebyurl() method, which will do all the heavy lifting.
...And 10 more matches
Using the Payment Request API - Web APIs
this returns a promise that fulfills with a paymentresponse object if the payment is successful: request.show().then(function(paymentresponse) { // here we would process the payment.
... for this demo, simulate immediate success: paymentresponse.complete('success') .then(function() { // for demo purposes: intropanel.style.display = 'none'; successpanel.style.display = 'block'; }); }) this object provides the developer with access to details they can use to complete the logical steps required after the payment completes, such as an email address to contact the customer, a shipping address for mailing goods out to them, etc.
...it returns a promise that fulfills with a boolean indicating whether it is or not, for example: // dummy payment request to check whether payment can be made new paymentrequest(buildsupportedpaymentmethoddata(), {total: {label: 'stub', amount: {currency: 'usd', value: '0.01'}}}) .canmakepayment() .then(function(result) { if(result) { // real payment request var request = new paymentrequest(buildsupportedpaymentmethoddata(), checkoutobject); request.show().then(function(paymentresponse) { // here we would process the payment.
...And 10 more matches
Realizing common layouts using CSS Grid Layout - CSS: Cascading Style Sheets
in a responsive design, you may want to display the layout as a single column, adding a sidebar at a certain breakpoint and then bring in a three-column layout for wider screens.
...we go to a two column layout, and then to a three column layout by redefining the grid, and the placement of items on the grid.</p> </article> <aside class="side">sidebar</aside> <div class="ad">advertising</div> <footer class="main-footer">the footer</footer> </div> as we are using grid-template-areas to create the layout.
...in the fourth row track i have chosen to place my ad content – so it appears under the sidebar, then the footer next to it under the content.
...And 10 more matches
How to make PWAs re-engageable using Notifications and Push - Progressive web apps (PWAs)
instead of showing the notification immediately though, best practice dictates that we should show the popup when the user requests it by clicking on a button: var button = document.getelementbyid("notifications"); button.addeventlistener('click', function(e) { notification.requestpermission().then(function(result) { if(result === 'granted') { randomnotification(); } }); }); this shows a popup using the operating system’s own notifications service: when the user confirms to receive notifications, the app can then show them.
... push push is more complicated than notifications — we need to subscribe to a server that will then send the data back to the app.
... the app's service worker will receive data from the push server, which can then be shown using the notifications system, or another mechanism if desired.
...And 10 more matches
Understanding WebAssembly text format - WebAssembly
thus you could rewrite our previous signature like so: (func (param $p1 i32) (param $p2 f32) (local $loc f64) …) and then could write local.get $p1 instead of local.get 0, etc.
... the webassembly validation rules ensure the stack matches exactly: if you declare a (result f32), then the stack must contain exactly one f32 at the end.
... so our final module (for now) looks like this: (module (func $add (param $lhs i32) (param $rhs i32) (result i32) local.get $lhs local.get $rhs i32.add) (export "add" (func $add)) ) if you want to follow along with the example, save the above our module into a file called add.wat, then convert it into a binary file called add.wasm using wabt (see converting webassembly text format to wasm for details).
...And 10 more matches
Index - Learn web development
you can then collaborate on code projects, and the system is open-source by default, meaning that anyone in the world can find your github code, use it, learn from it, and improve on it.
...then it steps through one method that can work right away for many readers.
... 53 graceful asynchronous programming with promises beginner, codingscripting, guide, javascript, learn, promises, async, asynchronous, catch, finally, then promises are a comparatively new feature of the javascript language that allow you to defer further actions until after a previous action has completed, or respond to its failure.
...And 9 more matches
What is JavaScript? - Learn web development
we can mark it up using html to give it structure and purpose: <p>player 1: chris</p> then we can add some css into the mix to get it looking nice: p { font-family: 'helvetica neue', helvetica, sans-serif; letter-spacing: 1px; text-transform: uppercase; text-align: center; border: 2px solid rgba(0,0,200,0.6); background: rgba(0,0,200,0.3); color: rgba(0,0,200,0.6); box-shadow: 1px 1px 2px rgba(0,0,200,0.4); border-radius: 10px; padding: 3px 10px; display: inline-...
...in the above example for instance, we ask for a new name to be entered then store that name in a variable called name.
...we used a click event in our example above to detect when the button is clicked and then run the code that updates the text label.
...And 9 more matches
Mozilla accessibility architecture
given that there is a fair amount of commonality between accessibility api toolkits, it made sense to write of the code in a cross platform manner, and then deal with the platform differences on a consistent manner.
...the toolkit-specific classes then use these xpcom interfaces to gather information about the objects they want to expose, make any necessary changes, and then expose the information using microsoft com on windows, or through gtk2's atk api's on linux and unix.
... the assistive technology can then use this information in a number of ways.
...And 9 more matches
OS.File for the main thread
let decoder = new textdecoder(); // this decoder can be reused for several reads let promise = os.file.read("file.txt"); // read the complete file as an array promise = promise.then( function onsuccess(array) { return decoder.decode(array); // convert this array to a text } ); this example requires firefox 18 or a more recent version.
... example: rename a file you have to use os.file.move to rename a file: let promise = os.file.move("oldname.txt", "newname.txt", {nooverwrite:true}); here's a working example which renames test.txt to testrenamed.txt if the file is located in directory c:\jean\ var promise = os.file.move(os.path.join('c:', 'jean', 'test.txt'), os.path.join('c:', 'jean', 'testrenamed.txt')); promise.then( function() { console.log('rename successful') }, function(arejectreason) { console.log('rename failed, arejectreason = ', arejectreason) } ) the nooverwrite true is important, as default is false which means if a file in the directory exists already with the same name it will no longer be there after this "rename" operation, which is a "move".
... example: determine if a file is a directory the following snippet determines if some path represents a file or a directory: let promise = os.file.stat(somepath); promise = promise.then( function onsuccess(stat) { if (stat.isdir) { // the path represents a directory } else { // the path represents a file, not a directory } }, function onfailure(reason) { if (reason instanceof os.file.error && reason.becausenosuchfile) { // the file does not exist } else { // some other error throw reason; } } ); example: copy a file...
...And 9 more matches
Mozilla DOM Hacking Guide
in this document i will try to outline the main aspects of the implementation, beginning with the class info mechanism, which lies at the heart of the dom, then with the description of various interfaces and classes.
...similarly, then return type of the c++ function will be wrapped by xpconnect so that javascript can use it safely.
...so xpconnect will then try to find a method named getelementbyid() on the nsidomdocument interface.
...And 9 more matches
Property cache
shape native objects have a shape, a 24-bit unsigned integer such that: basic layout guarantee — if at time t0 the object x has shape s and at time t1 the object y has shape s, and no shape-regenerating gc occurred, then y at t1 has the same jsclass, jsobjectops, prototype, and property specs as x had at t0.
...shape have the same prototype, class, and layout.) prototype chain shadowing guarantee — if at t0 the object x has shape s and a property x.p of x is found along the prototype chain on object x' of shape s', where x !== x', and the lookup called no resolve hooks or non-native lookup ops, and at t1 the object x has shape s, the object x' has shape s', and no shape-regenerating gc occurred, then at t1 the lookup for x.p still finds the same property on x'.
... for p starting at scope chain head x finds p on an object x' of shape s', where x !== x'; and the lookup called no resolve hooks or non-native lookup ops; and each object examined along the parent chain, except possibly the one along whose prototype chain x' was found, had no prototype or was a block object; and at time t1 x has shape s and x' has shape s'; and no shape-regenerating gc occurred; then at t1 the lookup for p in x still finds the same property on x'.
...And 9 more matches
PublicKeyCredentialCreationOptions.extensions - Web APIs
extensions are values requesting additional processing by the client and by the authenticator.
...also chrome doesn't plan to support any other extension in future extension identifier type description authnsel array of buffersource authenticator selection.
... restricts the list of authenticator models which may be used.
...And 9 more matches
Rendering and the WebXR frame animation callback - Web APIs
this article covers the process of driving the frames of the xr scene to the device in the rendering loop, using the xrsession to obtain an xrframe object representing each frame, which is then used to prepare the framebuffer for delivery to the xr device.
...rencespace( new xrrigidtransform(viewerstartposition, viewerstartorientation)); animationframerequestid = xrsession.requestanimationframe(mydrawframe); } } after getting a reference space for the immersive world, this creates an offset reference space representing the position and orientation of the viewer by creating an xrrigidtransform representing that position and orientation, then calling the xrreferencespace method getoffsetreferencespace().
... then the first animation frame is scheduled by calling the xrsession method requestanimationframe(), providing a callback function, mydrawframe(), whose job is to render the frame.
...And 9 more matches
Layout using named grid lines - CSS: Cascading Style Sheets
then defined the centre block of the grid as content-start and content-end again, both for columns and rows although you do not need to name all of the lines on your grid.
...naming lines is useful when creating a responsive design where you redefine the grid, rather than then needing to redefine the content position by changing the line number in your media queries, you can ensure that the line is always named the same in your definitions.
...you can then refer to that line by either of the names.
...And 9 more matches
jpm - Archive of obsolete content
jpm post package your add-on as an xpi file, and then post it to some url.
... jpm sign package your add-on as an xpi file, and then retrieve a new xpi signed by mozilla.
... mkdir my-addon cd my-addon jpm init you'll then be asked to supply some information about your add-on: this will be used to create your add-on's package.json file.
...And 8 more matches
SSL and TLS - Archive of obsolete content
the secure sockets layer (ssl) and transport layer security (tls) protocols are universally accepted standards for authenticated and encrypted communication between clients and servers.
... both client and server authentication occur over ssl/tls.
...symmetric-key encryption is much faster than public-key encryption, but public-key encryption provides better authentication techniques.
...And 8 more matches
Anatomy of a video game - Game development
if your game loops based on time then this will be its authority that your simulations will adhere to.
...if something looks like it should be attached to a more infrequent event then it is often a good idea to break it out of the main loop (but not always).
...if you demand per-frame control then you will need to determine how frequently your game will update and draw.
...And 8 more matches
Mobile accessibility - Learn web development
to turn it on, look up what phone model and android version you have, and then look up where the talkback menu is.
...if you've set a passcode or pattern for unlocking your device, you will then be taken to the relevant entry screen to enter it.
... you can also explore by touch to find the unlock button at the bottom middle of the screen, and then double-tap.
...And 8 more matches
Working with Svelte stores - Learn web development
code along with us git clone the github repo (if you haven't already done it) with: git clone https://github.com/opensas/mdn-svelte-tutorial.git then to get to the current app state, run cd mdn-svelte-tutorial/06-stores or directly download the folder's content: npx degit opensas/mdn-svelte-tutorial/06-stores remember to run npm install && npm run dev to start your app in development mode.
...if you’ve already worked with redux or vuex, then you'll be familiar with how this kind of store works.
...we then export the store.
...And 8 more matches
Gecko Profiler FAQ
to stop the profiler from gathering more samples after the “startup end” marker that you’re interested in, you can call services.profiler.pause(); or you can insert a marker with a special string and then write a script that filters out all samples that were gathered after your marker.
... to increase the amount of data, you should run your automated gathering procedure many times, and then combine multiple profiles into one.
...that tree is then displayed in the usual way, with weights in decreasing order from top to bottom.
...And 8 more matches
sslintro.html
upgraded documentation may be found in the current nss reference overview of an ssl application chapter 1 overview of an ssl application ssl and related apis allow compliant applications to configure sockets for authenticated, tamper-proof, and encrypted communications.
... configuration the configuration portion of an ssl-enabled application typically begins by opening a new socket and then importing the new socket into the ssl environment: pr_newtcpsocket.
... callbacks and helper functions allow you to specify such things as how authentication is accomplished and what happens if it fails.
...And 8 more matches
Web Replay
an easy way to see this is to open the debugger developer tool, press the pause button and then the rewind button.
... to resume recording and interacting with the tab, press the pause button and then the play button to run forward to the end of the recording.
... rewind to breakpoint when paused, if there are any breakpoints set then the rewind button will run back and stop at the last time a breakpoint was set.
...And 8 more matches
Introduction to XPCOM for the DOM
i learned c++ by reading "c++ primer" from stanley lippman and josee lajoie, then experimenting on the dom code.
... an instance of a class (called an object) can be allocated dynamically (on the heap, or free store), using the syntax nsfoo *fooptr = new nsfoo; that object can then be manipulated only through fooptr.
...a pointer to an interface nsifoo implemented by nsfoo can be declared as follows nsifoo *fooptr = new nsfoo; a pointer such as fooptr is then called a "pointer to an interface nsifoo implemented by an instance of the nsfoo class", or "pointer to nsifoo" in short.
...And 8 more matches
Background Tasks API - Web APIs
then we call settimeout(), passing into it a function which runs the callback passed into our implementation of requestidlecallback().
... to enqueue the task, we push an object onto the tasklist array; the object contains the taskhandler and taskdata values under the names handler and data, respectively, then increment totaltaskcount, which reflects the total number of tasks which have ever been enqueued (we don't decrement it when tasks are removed from the queue).
... if the current maximum value of the progress bar is different from the current total number of enqueued tasks (totaltaskcount), then we update the contents of the displayed total number of tasks (totaltaskcountelem) and the maximum value of the progress bar, so that it scales properly.
...And 8 more matches
SVGSVGElement - Web APIs
when the browser is actually rendering the content, then the position and size values represent the actual values when rendering.
...if no parent element exists (i.e., <svg> element represents the root of the document tree), if this svg document is embedded as part of another document (e.g., via the html <object> element), then the position and size are unitless values in the coordinate system of the parent document.
... (if the parent uses css or xsl layout, then unitless values represent pixel units for the current css or xsl viewport.) svgsvgelement.pixelunittomillimeterx a float representing the size of the pixel unit (as defined by css2) along the x-axis of the viewport, which represents a unit somewhere in the range of 70dpi to 120dpi, and, on systems that support this, might actually match the characteristics of the target medium.
...And 8 more matches
Index - HTTP
WebHTTPHeadersIndex
an http header consists of its case-insensitive name followed by a colon ':', then by its value (without line breaks).
...using content negotiation, the server then selects one of the proposals, uses it and informs the client of its choice with the content-type response header.
...using content negotiation, the server then selects one of the proposals, uses it and informs the client of its choice within the content-type response header.
...And 8 more matches
Digital audio concepts - Web media technologies
the granularity of an audio wave in the real world, then, is that of an individual molecule of the medium through which the sound wave is traveling.
... the sounds a person hears every day are, then, actually vibrations in the air which cause the inner workings of the ear.
...this analog signal is then converted into digital form by a circuit that captures the incoming wave's amplitude at regular intervals, converting that data into a number in a form that is understood by the audio recording system.
...And 8 more matches
Web video codec guide - Web media technologies
the artifacts generated by the encoder then introduce strange, swirling effects in the source image's pattern upon decoding.
...then that shift is stored, along with a description of the pixels that have moved that can't be described just by that shift.
... in essence, the encoder finds the moving objects, then builds an internal frame of sorts that looks like the original but with all the objects translated to their new locations.
...And 8 more matches
The building blocks of responsive design - Progressive web apps (PWAs)
it is usually much better to create a single version of your code which doesn't care about what browser or platform is accessing the site, but instead uses feature tests to find out what code features the browser supports or what the values of certain browser features are, and then adjusts the code appropriately.
... we've written a simple-but-fun prototype for an application called snapshot, which takes a video stream from your webcam (using getusermedia()) then allows you to capture stills from that video stream (using html5 <canvas>), and save them to a gallery.
... you can then view previously-captured images and delete them.
...And 8 more matches
Using the WebAssembly JavaScript API - WebAssembly
note: if you are unfamiliar with the basic concepts mentioned in this article and need more explanation, read webassembly concepts first, then come back.
... add the following to your script, below the first block: webassembly.instantiatestreaming(fetch('simple.wasm'), importobject) .then(obj => obj.instance.exports.exported_func()); the net result of this is that we call our exported webassembly function exported_func, which in turn calls our imported javascript function imported_func, which logs the value provided inside the webassembly instance (42) to the console.
... the equivalent code would look like this: fetch('simple.wasm').then(response => response.arraybuffer() ).then(bytes => webassembly.instantiate(bytes, importobject) ).then(results => { results.instance.exports.exported_func(); }); viewing wasm in developer tools in firefox 54+, the developer tool debugger panel has functionality to expose the text representation of any wasm code included in a web page.
...And 8 more matches
Extension Versioning, Update and Compatibility - Archive of obsolete content
if the application has a targetapplication entry but it is for an incompatible version then the application will retrieve updated compatibility information from the add-on's updateurl.
... if the install.rdf contains any targetplatform entries then the platform of the currently running application must be listed or the installation will be rejected.
... note: starting in gecko 2.0, the automatic add-on update process properly supports cases in which the add-on's guid changes by uninstalling the old version and then installing the new one.
...And 7 more matches
XForms Input Element - Archive of obsolete content
if "false", or the incremental attribute is omitted on this element then the bound instance node will be updated when the control loses the focus.
... specific handling of attributes incremental - if "true" or this attribute is omitted from this element, then the instance node will be updated when the user checks or un-checks the checkbox.
... if "false" then the instance node will be updated when the checkbox loses the focus.
...And 7 more matches
Cascade and inheritance - Learn web development
let's start by taking a quick look at the key things we are dealing with, then we'll look at each in turn and see how they interact with each other and your css.
...we have then added a class of special to the second nested list and applied a different color to it.
... this then inherits down through its children.
...And 7 more matches
A first splash into JavaScript - Learn web development
it should choose a random number between 1 and 100, then challenge the player to guess the number in 10 turns.
... once the game restarts, make sure the game logic and ui are completely reset, then go back to step 1.
...then go into the developer tools javascript console, and enter the following line: checkguess(); after pressing return/enter, you should see an alert come up that says "i am a placeholder"; we have defined a function in our code that creates an alert whenever we call it.
...And 7 more matches
Working with JSON - Learn web development
n reflexes" ] }, { "name": "eternal flame", "age": 1000000, "secretidentity": "unknown", "powers": [ "immortality", "heat immunity", "inferno", "teleportation", "interdimensional travel" ] } ] } if we loaded this object into a javascript program, parsed in a variable called superheroes for example, we could then access the data inside it using the same dot/bracket notation we looked at in the javascript object basics article.
...try loading this up and then accessing data inside the variable via your browser's javascript console.
...then we send the request with the send() method: request.responsetype = 'json'; request.send(); the last bit of this section involves waiting for the response to return from the server, then dealing with it.
...And 7 more matches
Object building practice - Learn web development
the first part of the script looks like so: const canvas = document.queryselector('canvas'); const ctx = canvas.getcontext('2d'); const width = canvas.width = window.innerwidth; const height = canvas.height = window.innerheight; this script gets a reference to the <canvas> element, then calls the getcontext() method on it to give us a context on which we can start to draw.
... open the browser's javascript console, and then refresh the page so that the canvas size changes to the smaller visible viewport that remains when the console opens.
...so for example, if the ball was traveling upwards (positive vely), then the vertical velocity is changed so that it starts to travel downwards instead (negative vely).
...And 7 more matches
Client-Server Overview - Learn web development
you might for example use a head request to find out the last time a resource was updated, and then only use the (more "expensive") get request to download the resource if it has changed.
...url parameters are inherently "insecure" as they can be changed by users and then resubmitted.
...use any of the linked tools, and then navigate through a site and edit profile information to see the different requests and responses.
...And 7 more matches
TypeScript support in Svelte - Learn web development
then we'll see how to configure our project to work with typescript files.
... code along with us git clone the github repo (if you haven't already done it) with: git clone https://github.com/opensas/mdn-svelte-tutorial.git then to get to the current app state, run cd mdn-svelte-tutorial/07-typescript-support or directly download the folder's content: npx degit opensas/mdn-svelte-tutorial/07-typescript-support remember to run npm install && npm run dev to start your app in development mode.
...all you have to do is run the following terminal commands (run them somewhere where you are storing your svelte test projects — it creates a new directory): npx degit sveltejs/template svelte-typescript-app cd svelte-typescript-app node scripts/setuptypescript.js this creates a starter project that includes typescript support, which you can then modify as you wish.
...And 7 more matches
Advanced Svelte: Reactivity, lifecycle, accessibility - Learn web development
code along with us git clone the github repo (if you haven't already done it) with: git clone https://github.com/opensas/mdn-svelte-tutorial.git then to get to the current app state, run cd mdn-svelte-tutorial/05-advanced-concepts or directly download the folder's content: npx degit opensas/mdn-svelte-tutorial/05-advanced-concepts remember to run npm install && npm run dev to start your app in development mode.
... add the following import statement below the existing ones: import moreactions from './moreactions.svelte' then add the described functions at the end of the <script> section: const checkalltodos = (completed) => todos.foreach(t => t.completed = completed) const removecompletedtodos = () => todos = todos.filter(t => !t.completed) now go to the bottom of the todos.svelte markup section and replace the btn-group <div> that we copied into moreactions.svelte with a call to the moreactions component, ...
...the framework updates this virtual representation which is then synced with the "real" dom.
...And 7 more matches
certutil
the key and certificate management process generally begins with creating keys in the key database, then generating and managing certificates in the certificate database.
... -c issuer identify the certificate of the ca from which a new certificate will derive its authenticity.
...if the prefix sql: is not used, then the tool assumes that the given databases are in the old format.
...And 7 more matches
Hacking Tips
#25157 0x7fffefbbc250 typein:2 (0x7fffef1231c0 @ 24) #25158 0x7fffefbbc1c8 typein:3 (0x7fffef1231c0 @ 47) #25159 0x7fffefbbc140 typein:2 (0x7fffef1231c0 @ 24) #25160 0x7fffefbbc0b8 typein:3 (0x7fffef1231c0 @ 47) #25161 0x7fffefbbc030 typein:5 (0x7fffef123280 @ 9) note, you can do the exact same exercise above using lldb (necessary on osx after apple removed gdb) by running lldb -f js then following the remaining steps.
...then you can display the instructions around pc with x/20i $pc, and execute instruction by instruction with stepi.
... adding spew for compilations & bailouts & invalidations (from gdb) if you are in rr, and forgot to record with the spew enabled with ionflags or because this is an optimized build, then you can add similar spew with extra breakpoints within gdb.
...And 7 more matches
Starting WebLock
if the object has only registered for one notification, then you can ignore the atopic string and simply handle the event as it occurs.
...you can then use the service manager to add the component to the category: nsresult rv; nscomptr<nsiservicemanager> servman = do_queryinterface((nsisupports*)acompmgr, &rv); if (ns_failed(rv)) return rv; do_queryinterface the previous code uses the special nscomptr function do_queryinterface that lets you queryinterface without having to worry about reference counting, error handling, and other ...
...if you do not, the component will be created and then released after the notification, which may cause the component to be deleted.
...And 7 more matches
SubtleCrypto.exportKey() - Web APIs
if format was jwk, then the promise fulfills with a json object containing the key.
...*/ async function exportcryptokey(key) { const exported = await window.crypto.subtle.exportkey( "raw", key ); const exportedkeybuffer = new uint8array(exported); const exportkeyoutput = document.queryselector(".exported-key"); exportkeyoutput.textcontent = `[${exportedkeybuffer}]`; } /* generate an encrypt/decrypt secret key, then set up an event listener on the "export" button.
... */ window.crypto.subtle.generatekey( { name: "aes-gcm", length: 256, }, true, ["encrypt", "decrypt"] ).then((key) => { const exportbutton = document.queryselector(".raw"); exportbutton.addeventlistener("click", () => { exportcryptokey(key); }); }); pkcs #8 export this example exports an rsa private signing key as a pkcs #8 object.
...And 7 more matches
Writing WebSocket servers - Web APIs
this means that you don't have to bloat your server code with cookie and authentication handlers (for example).
...also, common headers like user-agent, referer, cookie, or authentication headers might be there as well.
... note: the server can send other headers like set-cookie, or ask for authentication or redirects via other status codes, before sending the reply handshake.
...And 7 more matches
Working with objects - JavaScript
alternatively, you can first create a constructor function and then instantiate an object invoking that function in conjunction with the new operator.
...then the value of mycar.make is the string "eagle", mycar.year is the integer 1993, and so on.
...for example, suppose you define an object called person as follows: function person(name, age, sex) { this.name = name; this.age = age; this.sex = sex; } and then instantiate two new person objects as follows: var rand = new person('rand mckinnon', 33, 'm'); var ken = new person('ken jones', 39, 'm'); then, you can rewrite the definition of car to include an owner property that takes a person object, as follows: function car(make, model, year, owner) { this.make = make; this.model = model; this.year = year; this.owner = owner; } to instantiate...
...And 7 more matches
Mobile first - Progressive web apps (PWAs)
this article offers some related ideas, looking at the concept of mobile first — the practice of designing a website so that the default layout/configuration is for mobile devices, and layouts and features for desktop browsers are then layered on top of that default.
... first things first — mobile as a default you may think that concentrating on the mobile experience first sounds pointless, as we are more used to dealing with desktop sites, and we surely need to consider the full gamut of features for the overall experience across desktop, mobile, etc., before then paring it down to a mobile experience that is simpler, more streamlined, or whatever.
...then at implementation stage, we present the mobile layout and functionality as the default configuration provided, before additional information is loaded on top of that, whenever appropriate.
...And 7 more matches
xlink:href - SVG: Scalable Vector Graphics
if the reference is to a <glyph> element and that glyph is available, then that glyph is rendered instead of the characters that are inside of the <altglyph> element.
... if the reference is to an <altglyphdef> element, then if an appropriate set of alternate glyphs is located from processing the <altglyphdef> element, then those alternate glyphs are rendered instead of the characters that are inside of the <altglyph> element.
...if this element has no defined filter nodes, and the referenced element has defined filter nodes (possibly due to its own xlink:href attribute), then this element inherits the filter nodes defined from the referenced <filter> element.
...And 7 more matches
ui/button/toggle - Archive of obsolete content
at the root is the global state, then there's a state you can set for each window, then a state you can set for each tab.
...initially the buttons in all tabs and windows will display the label value inherited from the global state: browser: label = "my default" w1 t1 > displays "my default" t2 > displays "my default" w2 t3 > displays "my default" t4 > displays "my default" if you then set a label specific to t3 as "my t3 label", then set a label state specific to w2 as "my w2 label", then the button displayed when t3 is the active tab will still show "my t3 label", but the button displayed when t4 is the active tab will show "my w2 label": browser: label = "my default" w1 t1 > displays "my default" t2 > displays "my default" w2 ...
...if badgecolor is omitted and badge is specified, then the badge is red.
...And 6 more matches
cfx - Archive of obsolete content
use this flag to reverse that behavior: if this flag is set and the add-on includes its own copies of the sdk modules, then the add-on will use the sdk modules in the add-on, not the ones built into firefox.
... --e10s if this option is set then the add-on runs in a separate process.
... for example: if your add-on depends on modules from the sdk, then cfx will run the unit tests for the sdk's modules as well as yours.
...And 6 more matches
How to convert an overlay extension to restartless - Archive of obsolete content
step 2b: audit any remaining resource:// uri usage internal to your extension if you don't need resource:// uris for anything else, then you may be able to skip the next step.
...if you want to also make your add-on extractionless then you may need "step 3" if you're loading files with nsifileinputstream or something similar, or a jar: uri might work.
...worst case would be that you extract a file to a temporary location and then use nsifile operations upon the extracted file.
...And 6 more matches
Chapter 6: Firefox extensions and XUL applications - Archive of obsolete content
then select tools:quicknote:float to display it in its own window.
... using venkman read in source code activate venkman, and then select open windows:quicknote.xul:files on the top-left of the screen.
... fixme: figure 3: inserting a breakpoint start debugger type in some text into the quicknote screen, and then select save current tab from the menu.
...And 6 more matches
JavaScript crypto - Archive of obsolete content
you can then register event handlers for these events with the document.addeventlistener() method.
...doctype html> <h2>request a cert</h2> <form name="reqform" method="post" action="http://your.ra.site.org"> <p><input type=hidden name=cert_request value=""> <p>name: <input type=text name=name value=""> <p>password: <input type=password name="password" value=""> <p><input type=submit name="send" value="submit"> </form> <script> /* the following values could be filled in by the server cgi */ var authenticator = "server_magic"; var keytransportcert = null; var crmfobject = null; var form = document.forms[0]; function validate() { // generate keys for nsm.
... if (typeof(crypto.version) != "undefined") { crmfobject = crypto.generatecrmfrequest( "cn=" + form.name.value, form.password.value, authenticator, keytransportcert, "setcrmfrequest();", 1024, null, "rsa-dual-use"); } return false; } function setcrmfrequest() { form.cert_request.value = crmfobject.request; form.submit(); } form.onsubmit = validate; </script> on completion of the request, the ca may submit a page that looks something like this: <!doctype html> <h2>certificate request successful</h2> <p>hit 'load' to load your certificate</p> <form name="reqform"> <p><input type=submit name="load" value="submit"></p> </form> <script> /* the following values could be filled in by the server cgi */ var nickname= "mycertnickname"; v...
...And 6 more matches
Beginner's guide to media queries - Learn web development
in this lesson you will first learn about the syntax used in media queries, and then move on to use them in a worked example showing how a simple design might be made responsive.
... note: media types are optional; if you do not indicate a media type in your media query then the media query will default to being for all media types.
... media feature rules after specifying the type, you can then target a media feature with a rule.
...And 6 more matches
Introduction to events - Learn web development
the keypress event refers to a general press (button down and then up), while keydown and keyup refer to just the key down and key up parts of the keystroke, respectively.
... note: you can use any name you like for the event object — you just need to choose a name that you can then use to reference it inside the event handler function.
...we then select all of them using document.queryselectorall(), then loop through each one, adding an onclick handler to each that makes it so that a random color is applied to each one when selected: const divs = document.queryselectorall('div'); for (let i = 0; i < divs.length; i++) { divs[i].onclick = function(e) { e.target.style.backgroundcolor = bgchange(); } } the output is as follows (try...
...And 6 more matches
Basic math in JavaScript — numbers and operators - Learn web development
hexadecimal — base 16, uses 0–9 and then a–f in each column.
... first of all, let's declare a couple of variables and initialize them with an integer and a float, respectively, then type the variable names back in to check that everything is in order: let myint = 5; let myfloat = 6.667; myint; myfloat; number values are typed in without quote marks — try declaring and initializing a couple more variables containing numbers before you move on.
... operator precedence let's look at the last example from above, assuming that num2 holds the value 50 and num1 holds the value 10 (as originally stated above): num2 + num1 / 8 + 2; as a human being, you may read this as "50 plus 10 equals 60", then "8 plus 2 equals 10", and finally "60 divided by 10 equals 6".
...And 6 more matches
Server-side web frameworks - Learn web development
we then explain some of the criteria you can use for choosing a web framework, and then list some of your options.
... work directly with http requests and responses as we saw in the last article, web servers and browsers communicate via the http protocol — servers wait for http requests from the browser and then return information in http responses.
...inside the html skeleton we have an expression that first checks if the youngest_teams variable exists, and then iterates it in a for loop.
...And 6 more matches
Handling common accessibility problems - Learn web development
chrome: install the web developer toolbar extension, then restart the browser.
... click the gear icon that will appear, then select css > disable all styles.
... you can then press enter/return to follow a focused link or press a button (we've included some javascript to make the buttons alert a message), or start typing to enter text in a text input (other form elements have different controls, for example the <select> element can have its options displayed and cycled between using the up and down arrow keys).
...And 6 more matches
Handling common HTML and CSS problems - Learn web development
if you have a widget, make sure it has a distinct class, and then start the selectors that select elements inside the widget with this class, so conflicts are less likely.
...these allows you to paste your code into a window, and it will flag up any errors with crosses, which can then be hovered to get an error message informing you what the problem is.
...we find that it is helpful to inspect the element you are trying to style using your browser's dev tools, then look at the dom tree breadcrumb trail that dom inspectors tend to provide to see if your selector makes sense compared to it.
...And 6 more matches
Deploying our app - Learn web development
this step isn't necessary, but it is a good best practice to get into the habit of setting up — across all our projects, we can then rely on npm run build to always do the complete build step, without needing to remember the specific build command arguments for each project.
...if you get the error fatal: not a git repository returned, then the working directory is not a git working directory and you’ll need to initialise git using git init.
...if you want finer control over what you add, then use git add -p for an interactive process, or add individual files using git add path/to/file.
...And 6 more matches
Introducing a complete toolchain - Learn web development
once you've signed up for github (click the sign up link on the homepage if you don't already have an account, and follow the instructions), you can use your github account for authentication on netlify (click sign up, then choose github from the "sign up with one of the following" list), so technically you only need to create one new account.
...jsx or typescript) in our development process, and then transforms our code so that the production version still runs on a wide variety of browsers, modern and older.
...if you followed the directions in the installing prettier section then you might already have prettier installed.
...And 6 more matches
Performance best practices for Firefox front-end engineers
return window.getcomputedstyle(node).display; }); return display == "none"; } see detecting and avoiding synchronous reflow for a more advanced example of getting layout information, and then setting it safely, without causing flushes.
... it should be possible to write a test that gets the nsidomwindowutils for a browser window, records the number of styleflushes, then synchronously calls the function that you want to test, and immediately after checks the styleflushes attribute again.
... the first time a document (xul or html) loads, we parse the markup, and then apply styles.
...And 6 more matches
Encrypt Decrypt_MAC_Using Token
*/ pk11symkey * generatesymkey(pk11slotinfo *slot, ck_mechanism_type mechanism, int keysize, secitem *keyid, secupwdata *pwdata) { secstatus rv; pk11symkey *key; if (pk11_needlogin(slot)) { rv = pk11_authenticate(slot, pr_true, pwdata); if (rv != secsuccess) { pr_fprintf(pr_stderr, "could not authenticate to token %s.\n", pk11_gettokenname(slot)); return null; } } /* generate the symmetric key.
... */ pk11symkey* findkey(pk11slotinfo *slot, ck_mechanism_type mechanism, secitem *keybuf, secupwdata *pwdata) { secstatus rv; pk11symkey *key; if (pk11_needlogin(slot)) { rv = pk11_authenticate(slot, pr_true, pwdata); if (rv != secsuccess) { pr_fprintf(pr_stderr, "could not authenticate to token %s.\n", pk11_gettokenname(slot)); if (slot) { pk11_freeslot(slot); } return null; } } key = pk11_findfixedkey(slot, mechanism, keybuf, 0); if (!key) { ...
... goto cleanup; } cleanup: return rv; } /* * decryptfile */ secstatus decryptfile(pk11slotinfo *slot, const char *dbdir, const char *outfilename, const char *headerfilename, char *encryptedfilename, secupwdata *pwdata, prbool ascii) { /* * the db is open read only and we have authenticated to it: * open input file, read in header, get iv and cka_ids of two keys from it.
...And 6 more matches
NSS tools : certutil
-c issuer identify the certificate of the ca from which a new certificate will derive its authenticity.
...if nss_default_db_type is not set then dbm: is the default.
...ach category position, use none, any, or all of the attribute codes: + p - valid peer + p - trusted peer (implies p) + c - valid ca + t - trusted ca to issue client certificates (implies c) + c - trusted ca to issue server certificates (ssl only) (implies c) + u - certificate can be used for authentication or signing + w - send warning (use with other attributes to include a warning when the certificate is used in that context) the attribute codes for the categories are separated by commas, and the entire set of attributes enclosed by quotation marks.
...And 6 more matches
sslerr.html
ssl_error_no_certificate -12285 "unable to find the certificate or key necessary for authentication." this error has many potential causes; for example: certificate or key not found in database.
... ssl_error_bad_certificate -12284 "unable to communicate securely with peer: peers's certificate was rejected." a certificate was received from the remote system and was passed to the certificate authentication callback function provided by the local application.
... that callback function returned secfailure, and the bad certificate callback function either was not configured or did not choose to override the error code returned by the certificate authentication callback function.
...And 6 more matches
nsIAuthPrompt2
it can be used to prompt users for authentication information, either synchronously or asynchronously.
...this means prompts that are guaranteed to want the same authentication information from the user.
... a single prompt will be shown; then the callbacks for all the coalesced prompts will be notified with the resulting authentication information.
...And 6 more matches
nsIFocusManager
if the current focus within the new focusedwindow is a frame element, then the focusedwindow will actually be set to the child window and the current element within that set as the focused element.
...void focusplugin( in nsicontent aplugin ); parameters aplugin getfocusedelementforwindow() nsidomelement getfocusedelementforwindow( in nsidomwindow awindow, in prbool adeep, out nsidomwindow afocusedwindow ); parameters awindow if equal to the current value of focusedwindow, then the returned element will be the application-wide focused element (the value of focusedelement).
... adeep if true, then child frames are traversed and the return value may be the element within a child descendant window that is focused.
...And 6 more matches
Using Fetch - Web APIs
have a look at the following code: fetch('http://example.com/movies.json') .then(response => response.json()) .then(data => console.log(data)); here we are fetching a json file across the network and printing it to the console.
...cy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url body: json.stringify(data) // body data type must match "content-type" header }); return response.json(); // parses json response into native javascript objects } postdata('https://example.com/answer', { answer: 42 }) .then(data => { console.log(data); // json data parsed by `data.json()` call }); note that mode: "no-cors" only allows a limited set of headers in the request: accept accept-language content-language content-type with a value of application/x-www-form-urlencoded, multipart/form-data, or text/plain sending a request with credentials included to cause browsers to send a request with cred...
... const data = { username: 'example' }; fetch('https://example.com/profile', { method: 'post', // or 'put' headers: { 'content-type': 'application/json', }, body: json.stringify(data), }) .then(response => response.json()) .then(data => { console.log('success:', data); }) .catch((error) => { console.error('error:', error); }); uploading a file files can be uploaded using an html <input type="file" /> input element, formdata() and fetch().
...And 6 more matches
Using bounded reference spaces - Web APIs
introduction a bounded reference space is one which represents an xr environment in which the user is able to move around physically in the real world while being tracked by the xr hardware, with their movements being then transposed into the simulation.
... the boundaries established by the bounded reference space, then, represent the edges of the safely passable, tracked space in the user's real world environment that are available for their movement while in the simulation.
... the requirements, then, for a bounded reference space are: xr hardware that can track the user's movement in the real world, such as a camera-based system.
...And 6 more matches
Using the Web Speech API - Web APIs
speech recognition speech recognition involves receiving speech through a device's microphone, which is then checked by a speech recognition service against a list of grammar (basically, the vocabulary you want to have recognised in a particular app.) when a word or phrase is successfully recognised, it is returned as a result (or list of results) as a text string, and further actions can be initiated as a result.
... <h1>speech color changer</h1> <p>tap/click then say a color to change the background color of the app.</p> <div> <p class="output"><em>...diagnostic messages</em></p> </div> the css provides a very simple responsive styling so that it looks ok across devices.
... speechrecognitionlist.addfromstring(grammar, 1); we then add the speechgrammarlist to the speech recognition instance by setting it to the value of the speechrecognition.grammars property.
...And 6 more matches
Using Web Workers - Web APIs
here we simply multiply together the two numbers then use postmessage() again, to post the result back to the main thread.
...any global objects from each script may then be used by the worker.
...queryableworker(url, defaultlistener, onerror) { var instance = this, worker = new worker(url), listeners = {}; this.defaultlistener = defaultlistener || function() {}; if (onerror) {worker.onerror = onerror;} this.postmessage = function(message) { worker.postmessage(message); } this.terminate = function() { worker.terminate(); } } then we add the methods of adding/removing listeners: this.addlisteners = function(name, listener) { listeners[name] = listener; } this.removelisteners = function(name) { delete listeners[name]; } here we let the worker handle two simple operations for illustration: getting the difference of two numbers and making an alert after three seconds.
...And 6 more matches
Basic concepts of flexbox - CSS: Cascading Style Sheets
if your main axis is column or column-reverse then the cross axis runs along the rows.
... if the flex-direction is row and i am working in english, then the start edge of the main axis will be on the left, the end edge on the right.
... if i were to work in arabic, then the start edge of my main axis would be on the right and the end edge on the left.
...And 6 more matches
CSS Grid Layout and Progressive Enhancement - CSS: Cascading Style Sheets
if they tend to use up-to-date versions of firefox, chrome, opera, and safari, then it would make sense to start using css grids once those browsers update.
...to create gaps between the cards, i use a margin on the items, and then a negative margin on the container: * {box-sizing: border-box;} .wrapper { border: 2px solid #f76707; border-radius: 5px; background-color: #fff4e6; max-width: 600px; margin: 0 auto; } .wrapper li { border: 2px solid #ffa94d; border-radius: 5px; background-color: #ffd8a8; padding: 1em; color: #d9480f; } .wrapper ul { overflow: hidden; margin:...
... i then enhance the layout using grid.
...And 6 more matches
Overview of CSS Shapes - CSS: Cascading Style Sheets
if you then apply a circle shape, the text would then wrap round the line of the circle.
...i have then applied the shape-outside property to it with a value of circle(50%).
...if they do have shapes support then the visual display is enhanced.
...And 6 more matches
Applying color to HTML elements using CSS - HTML: Hypertext Markup Language
then we'll wrap things up with a brief discussion of how to use color wisely: how to select appropriate colors, keeping in mind the needs of people with differing visual capabilities.
...among the options for the shadow is the shadow's base color (which is then blurred and blended with the background based on the other parameters).
...for example, if the box's text is being rendered right-to-left, then the border-inline-start-color is applied to the right side of the border.
...And 6 more matches
Using HTTP cookies - HTTP
WebHTTPCookies
the cookie is usually stored by the browser, and then the cookie is sent with requests made to the same server inside a cookie http header.
...a simple cookie is set like this: set-cookie: <cookie-name>=<cookie-value> this shows the server sending headers to tell the client to store a pair of cookies: http/2.0 200 ok content-type: text/html set-cookie: yummy_cookie=choco set-cookie: tasty_cookie=strawberry [page content] then, with every subsequent request to the server, the browser sends back all previously stored cookies to the server using the cookie header.
... if your site authenticates users, it should regenerate and resend session cookies, even ones that already exist, whenever the user authenticates.
...And 6 more matches
Inheritance and the prototype chain - JavaScript
properties can then be added onto this object.
... if dosomeinstancing does not have the property, then the browser looks for the property in the __proto__ of dosomeinstancing (a.k.a.
...if the __proto__ of dosomeinstancing has the property being looked for, then that property on the __proto__ of dosomeinstancing is used.
...And 6 more matches
dev/panel - Archive of obsolete content
then the panel document can communicate with the debugger server.
... then(listtabs).
... then(writetablist); }); function listtabs(root) { return root.listtabs(); } function writetablist(tablist) { content.textcontent = tablist.tabs[tablist.selected].url; } we don't have detailed documentation for volcan.js, but it's coming soon.
...And 5 more matches
Enhanced Extension Installation - Archive of obsolete content
first it must locate the firefox executable, then run it with the -install-global-extension command line flag, which installs from a xpi into the firefox application directory.
...the finalization process then notifies the startup process that finalization has changed this manifest, and that the application must be restarted to pick up changes specified therein.
...this is a list of all installed items, disabled or not, keyed first by install location name, then by guid.
...And 5 more matches
Frequently Asked Questions - Archive of obsolete content
if there's a grey area at the top of the source with the text "this xml file does not appear to have any style information associated with it" then the problem is with the svg file.
... if source code is displayed without a gray area at the top, or if you just see gibberish, then the problem is server misconfiguration.
...if that isn't the problem, then it may be that the server hosting the website is misconfigured.
...And 5 more matches
Scratchpad - Archive of obsolete content
unlike the web console, which is designed for interpreting a single line of code at a time, scratchpad lets you edit larger chunks of javascript code, then execute it in various ways depending on how you want to use the output.
... usage opening scratchpad in its own window there are several different ways to open scratchpad in its own window: press shift + f4, or go to the web developer menu (which is a submenu in the tools menu on macos and linux), then select scratchpad click the wrench icon (), which is in the main toolbar or under the hamburger menu (), then select "scratchpad".
... for example, try typing d, then pressing ctrl + space.
...And 5 more matches
Desktop gamepad controls - Game development
then, if the buttons are available we loop through them; if the pressed property is set to true, then we add them to the buttonspressed array for later processing.
...if it is, then the function returns true; false otherwise.
...h; i<s; i++) { if(gamepadapi.buttons.status[i] == button) { newpress = true; if(!hold) { for(var j=0,p=gamepadapi.buttons.cache.length; j<p; j++) { if(gamepadapi.buttons.cache[j] == button) { newpress = false; } } } } } return newpress; }, it loops through pressed buttons and if the button we're looking for is pressed, then the corresponding boolean variable is set to true.
...And 5 more matches
Debugging CSS - Learn web development
this is the value that takes the size you give the element and then adds on the padding and border width.
...if the property or value you are using is not supported by the browser you are testing in then nothing will break, but that css won't be applied.
... make a reduced test case of the problem if the issue isn't solved by the steps above, then you will need to do some more investigating.
...And 5 more matches
Supporting older browsers - Learn web development
if you have no analytics or this is a brand new site, then there are sites such as statcounter that can provide statistics filtered by location.
...couple this information with the knowledge that browsers ignore css that they don’t understand, and you have a way to create simple layouts using the legacy techniques we have already covered, which are then overwritten by your grid layout in modern browsers that understand it.
... 1fr; } .item { float: left; border-radius: 5px; background-color: rgb(207,232,220); padding: 1em; } <div class="wrapper"> <div class="item">item one</div> <div class="item">item two</div> <div class="item">item three</div> </div> note: the clear property also has no effect once the cleared item becomes a grid item, so you could have a layout with a cleared footer, which is then turned into a grid layout.
...And 5 more matches
UI pseudo-classes - Learn web development
then we give the generated content the content "required", which is what we wanted our label to say, and style and position it as we want.
...we then absolutely position different generated content depending on whether the form's data is valid or invalid — a green check or a red cross, respectively.
...you can try it here: it is possible for the number input to be both required and out-of-range at the same time, so what happens then?
...And 5 more matches
Understanding client-side JavaScript frameworks - Learn web development
getting started with ember in our first ember article we will look at how ember works and what it's useful for, install the ember toolchain locally, create a sample app, and then do some initial setup to get it ready for development.
...ember app structure and componentization in this article we'll get right on with planning out the structure of our todomvc ember app, adding in the html for it, and then breaking that html structure into components.
...in this article we'll look at adding a set of todo item data to our app.vue component, which we'll then loop through and display inside todoitem components using the v-for directive.
...And 5 more matches
Implementing feature detection - Learn web development
the concept of feature detection the idea behind feature detection is that you can run a test to determine whether a feature is supported in the current browser, and then conditionally run code to provide an acceptable experience both in browsers that do support the feature, and browsers that don't.
...} property on element create an element in memory using document.createelement() and then check if a property exists on it.
...} method on element return value create an element in memory using document.createelement() and then check if a method exists on it.
...And 5 more matches
Client-side tooling overview - Learn web development
if you have found yourself struggling in the past, then don’t worry — you are not alone.
... in these articles, we won’t answer every question about web tooling, but we will provide you with a useful starting point of understanding the fundamentals, which you can then build from.
...you then "push" changes to a "master" version of the code inside a remote repository stored on a server somewhere.
...And 5 more matches
Adding a new CSS property
then, unless you're implementing a shorthand property, you need to decide which style struct the computed value of the property should go in.
... you then need to add code to nsrulenode::compute*data (where the * is for the style struct) to transform a specified value of the property into a computed value of the property.
... then you need to change nsstyle*::calcdifference (in nsstylestruct.cpp) to describe how dynamic changes of your new css property need to be handled.
...And 5 more matches
How Mozilla's build system works
config.status starts with the main moz.build file and then recurses into all referenced files and directories.
...these data structures are then read by a build backend generator, which then converts them into files, function calls, and so on.
...the 1,276 data structures were fed into the build backend, which then determined it had to manage 2,188 files derived from those data structures.
...And 5 more matches
McCoy
if you want to learn about the technical details of mccoy then visit the project wiki.
...the simplest way to do this is to select the key then click the install toolbar button.
... you must then locate your install.rdf for mccoy and the public part of the key will be added directly to the file.
...And 5 more matches
JSS FAQ
MozillaProjectsNSSJSSJSS FAQ
for jss 3.2 and higher, if you use jdk 1.4 or higher you will not need to install the jce, but if you using an earlier version of the jdk then you will also have to install jce 1.2.1.
... nss's three ssl cert callbacks are: ssl_authcertificatehook sets a callback to authenticate the peer's certificate.
... it is called instead of nss's routine for authenticating certificates.
...And 5 more matches
Shell global objects
loadbytecode if true, and if the source is a cacheentryobject, the bytecode would be loaded and decoded from the cache entry instead of being parsed, then it would be executed as usual.
... asserteqbytecode if true, and if both loadbytecode and savebytecode are true, then the loaded bytecode and the encoded bytecode are compared.
...subsequent calls without an argument then read from this buffer line by line.
...And 5 more matches
Mozilla internal string guide
if a string is defined as a const nsastring then the data in the string cannot be manipulated.
...if a string less than 64 code units is assigned to an nsautostring, then no extra storage will be allocated.
...if handlestring assigns its input into another nsstring, then the string buffer will be shared in this case negating the cost of the intermediate temporary.
...And 5 more matches
nsIAuthModule
netwerk/base/public/nsiauthmodule.idlscriptable this interface is intended to be used as server and client authentication service.
... req_mutual_auth (1 << 0) client and server will be authenticated.
... methods getnexttoken() this method is called to get the next token in a sequence of authentication steps.
...And 5 more matches
Working with data
the resulting data is then copied into a new cdata object.
... if the value is a javascript array object and it has a non-negative length, a new array is created and the contents of the array specified by value are converted to cdata objects and copied into the new array, which is then returned.
... as review, making a null-terminated string happens like this: var cstr_nullterminated = ctypes.jschar.array()('rawr'); console.log(cstr_nullterminated); // outputs to browserconsole: `cdata { length: 5 }` console.log(cstr_nullterminated.tostring()); // outputs to browser console: `"ctypes.char16_t.array(5)(["r", "a", "w", "r", "\x00"])"` the console.log shows that the length is greater then the length of "rawr" which is 4, doing a .tostring on it shows there is a null terminator of \x00 on the end.
...And 5 more matches
Using the CSS Painting API - Web APIs
the css paint api is designed to enable developers to programmatically define images which can then be used anywhere a css image can be invoked, such as css background-image, border-image, mask-image, etc.
... we have then used the paint() function to paint to our canvas.
... we define the fillstyle as being hsla(55, 90%, 60%, 1.0), which is a shade of yellow, and then call fillrect() to create a rectangle of that color.
...And 5 more matches
Drag Operations - Web APIs
to see this in effect, select an area of a webpage, and then click and hold the mouse and drag the selection.
...if the drag contains no drag data items, or all of the items have been subsequently cleared, then no drag will occur.
...if you don't change the effectallowed property, then any operation is allowed, just like with the 'all' value.
...And 5 more matches
PublicKeyCredentialCreationOptions - Web APIs
the publickeycredentialcreationoptions dictionary of the web authentication api holds options passed to navigators.credentials.create() in order to create a publickeycredential.
...this value will be signed by the authenticator and the signature will be sent back as part of authenticatorattestationresponse.attestationobject.
... publickeycredentialcreationoptions.authenticatorselection optional an object whose properties are criteria used to filter out the potential authenticators for the creation operation.
...And 5 more matches
SubtleCrypto.wrapKey() - Web APIs
this means that it exports the key in an external, portable format, then encrypts the exported key.
...*/ async function wrapcryptokey(keytowrap) { // get the key encryption key const keymaterial = await getkeymaterial(); salt = window.crypto.getrandomvalues(new uint8array(16)); const wrappingkey = await getkey(keymaterial, salt); return window.crypto.subtle.wrapkey( "raw", keytowrap, wrappingkey, "aes-kw" ); } /* generate an encrypt/decrypt secret key, then wrap it.
... */ window.crypto.subtle.generatekey( { name: "aes-gcm", length: 256, }, true, ["encrypt", "decrypt"] ) .then((secretkey) => { return wrapcryptokey(secretkey); }) .then((wrappedkey) => { console.log(wrappedkey); }); pkcs #8 wrap this example wraps an rsa private signing key.
...And 5 more matches
Using textures in WebGL - Web APIs
// until then put a single pixel in the texture so we can // use it immediately.
...it then uploads a single blue pixel using teximage2d().
... to load the texture from the image file, it then creates an image object and assigns the src to the url for our image we wish to use as our texture.
...And 5 more matches
Establishing a connection: The WebRTC perfect negotiation pattern - Web APIs
a polite peer, essentially, is one which may send out offers, but then responds if an offer arrives from the other peer with "okay, never mind, drop my offer and i'll consider yours instead." an impolite peer, which always ignores incoming offers that collide with its own offers.
...however you make the determination, once these roles are assigned to the two peers, they can then work together to manage signaling in a way that doesn't deadlock and doesn't require a lot of extra code to manage.
...the resulting media tracks are then added to the rtcpeerconnection by passing them into addtrack().
...And 5 more matches
A simple RTCDataChannel sample - Web APIs
first, we have a couple of buttons for establishing and closing the connection: <button id="connectbutton" name="connectbutton" class="buttonleft"> connect </button> <button id="disconnectbutton" name="disconnectbutton" class="buttonright" disabled> disconnect </button> then there's a box which contains the text input box into which the user can type a message to transmit, with a button to send the entered text.
...we grab references to all the page elements we'll need to access, then set event listeners on the three buttons.
... localconnection.createoffer() .then(offer => localconnection.setlocaldescription(offer)) .then(() => remoteconnection.setremotedescription(localconnection.localdescription)) .then(() => remoteconnection.createanswer()) .then(answer => remoteconnection.setlocaldescription(answer)) .then(() => localconnection.setremotedescription(remoteconnection.localdescription)) .catch(handlecreatedescriptionerror); let's go t...
...And 5 more matches
Example and tutorial: Simple synth keyboard - Web APIs
then we establish a box that will be presented on the left side of the bar and place a label and an <input> element of type "range".
...if the note's name is only one character, then we call createkey(), specifying the note string, octave, and frequency.
... then a new custom waveform is built using audiocontext.createperiodicwave().
...And 5 more matches
Visualizations with Web Audio API - Web APIs
one of the most interesting features of the web audio api is the ability to extract frequency, waveform, and other data from your audio source, which can then be used to create visualizations.
... basic concepts to extract data from your audio source, you need an analysernode, which is created using the audiocontext.createanalyser() method, for example: var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); var analyser = audioctx.createanalyser(); this node is then connected to your audio source at some point between your source and your destination, for example: source = audioctx.createmediastreamsource(stream); source.connect(analyser); analyser.connect(distortion); distortion.connect(audioctx.destination); note: you don't need to connect the analyser's output to another node for it to work, as long as the input is connected to the source, either direc...
... the analyser node will then capture audio data using a fast fourier transform (fft) in a certain frequency domain, depending on what you specify as the analysernode.fftsize property value (if no value is specified, the default is 2048.) note: you can also specify a minimum and maximum power value for the fft data scaling range, using analysernode.mindecibels and analysernode.maxdecibels, and different data averaging constants using analysernode.smoothingtimeconstant.
...And 5 more matches
Mastering Wrapping of Flex Items - CSS: Cascading Style Sheets
items will then wrap in the container.
...if flex-direction is set to row-reverse then the items will start from the end edge of the container and lay themselves out in reverse ordered lines.
...we start on the right then go onto the second line and again start from the right.
...And 5 more matches
Typical use cases of Flexbox - CSS: Cascading Style Sheets
if i wanted all of my navigation items to have equal width, then i might use flex: auto, which is the shorthand for flex: 1 1 auto — all items grow and shrink from a flex-basis of auto.
...as in the above example, make a container into a flex container, and then use either align-items on the parent element or target the flex item itself with align-self.
...we then set the content area to flex: 1, which is the shorthand for flex: 1 1 0 — the item can grow and shrink from a flex basis of 0.
...And 5 more matches
Auto-placement in CSS Grid Layout - CSS: Cascading Style Sheets
if you have created additional rows using the grid-template-rows property then grid will continue placing items in these rows.
...padding: 1em; color: #d9480f; } <div class="wrapper"> <div>one</div> <div>two</div> <div>three</div> <div>four</div> <div>five</div> </div> .wrapper { display: grid; grid-template-columns: repeat(3, 1fr); grid-gap: 10px; grid-auto-rows: 100px; } you can use minmax() in your value for grid-auto-rows enabling the creation of rows that are a minimum size but then grow to fit content if it is taller.
...i am auto-placing by column and the columns created will be a column width of 300 pixels, then a column width of 100 pixels until there are enough column tracks to hold all of the items.
...And 5 more matches
<input>: The Input (Form Input) element - HTML: Hypertext Markup Language
WebHTMLElementinput
if the value of the max attribute isn't a number, then the element has no maximum value.
...if the value of the min attribute isn't a number, then the element has no minimum value.
... warning: avoid giving form elements a name that corresponds to a built-in property of the form, since you would then override the predefined property or method with this reference to the corresponding input.
...And 5 more matches
HTTP headers - HTTP
WebHTTPHeaders
an http header consists of its case-insensitive name followed by a colon (:), then by its value.
... headers can also be grouped according to how proxies handle them: connection keep-alive proxy-authenticate proxy-authorization te trailer transfer-encoding upgrade (see also protocol upgrade mechanism).
... authentication www-authenticate defines the authentication method that should be used to access a resource.
...And 5 more matches
Promise.resolve() - JavaScript
if the value is a promise, that promise is returned; if the value is a thenable (i.e.
... has a "then" method), the returned promise will "follow" that thenable, adopting its eventual state; otherwise the returned promise will be fulfilled with the value.
...can also be a promise or a thenable to resolve.
...And 5 more matches
Making PWAs work offline with Service workers - Progressive web apps (PWAs)
lifecycle of a service worker when registration is complete, the sw.js file is automatically downloaded, then installed, and finally activated.
... var gamesimages = []; for(var i=0; i<games.length; i++) { gamesimages.push('data/img/'+games[i].slug+'.jpg'); } var contenttocache = appshellfiles.concat(gamesimages); then we can manage the install event itself: self.addeventlistener('install', (e) => { console.log('[service worker] install'); e.waituntil( caches.open(cachename).then((cache) => { console.log('[service worker] caching all: app shell and content'); return cache.addall(contenttocache); }) ); }); there are two things that need an explanation here: what extendableevent.wa...
... here, we open a cache with a given name, then add all the files our app uses to the cache, so they are available next time it loads (identified by request url).
...And 5 more matches
Structural overview of progressive web apps - Progressive web apps (PWAs)
the best results tend to come when you use both client-side and server-side rendering; you can render a web site on the server, cache its contents, and then update the rendering on the client side as needed.
... the app shell concept the app shell concept is concerned with loading a minimal user interface and content as soon as possible, caching it so it's available offline for subsequent visits before then loading the remainder of the app's contents.
...the app displays its title, a description, and then a place for the app content to be shown (a <section> element with the id content.
...And 5 more matches
mimeTypes.rdf corruption - SVG: Scalable Vector Graphics
if the blue square with the white cross displays when you load this scripting across embed demo, then you are not experiencing this problem.
... if it doesn't, then you almost certainly are.
...if either of these things happen, then mozilla can end up with a media type for files that it doesn't recognize, but which the user knows it should.
...And 5 more matches
Loading and running WebAssembly code - WebAssembly
this article provides a reference for the different mechanisms that can be used to fetch webassembly bytecode, as well as how to compile/instantiate then run it.
... the older webassembly.compile/webassembly.instantiate methods require you to create an arraybuffer containing your webassembly module binary after fetching the raw bytes, and then compile/instantiate it.
... the quickest, most efficient way to fetch a wasm module is using the newer webassembly.instantiatestreaming() method, which can take a fetch() call as its first argument, and will handle fetching, compiling, and instantiating the module in one step, accessing the raw byte code as it streams from the server: webassembly.instantiatestreaming(fetch('simple.wasm'), importobject) .then(results => { // do something with the results!
...And 5 more matches
Content Scripts - Archive of obsolete content
this enables you to load a javascript library like jquery by url, then pass in a simple script inline that can use jquery: // main.js var data = require("sdk/self").data; var pagemod = require("sdk/page-mod"); var contentscriptstring = '$("body").html("<h1>page matches ruleset</h1>");'; pagemod.pagemod({ include: "*.mozilla.org", contentscript: contentscriptstring, contentscriptfile: data.url("jquery.js") }); unless your content script is extremely simpl...
... this insulation means that, for example, if a web page loads the jquery library, then the content script won't be able to see the jquery object added by the library - but the content script can add its own jquery object, and it won't clash with the page script's version.
... event listeners you can listen for dom events in a content script just as you can in a normal page script, but there are two important differences: first, if you define an event listener by passing it as a string into setattribute(), then the listener is evaluated in the page's context, so it will not have access to any variables defined in the content script.
...And 4 more matches
tabs - Archive of obsolete content
(see the modifying the page hosted by a tab tutorial): var tabs = require("sdk/tabs"); tabs.on('activate', function(tab) { var worker = tab.attach({ contentscript: 'self.port.emit("html", document.body.innerhtml);' }); worker.port.on("html", function(message) { console.log(message) }) }); note that tab.attach is tab-centric: if the user navigates to a new page in the same tab, then the worker and content scripts will be reattached to the new page.
...require("sdk/ui/button/toggle"); var style = style({ uri: './style.css' }); var button = togglebutton({ id: "stylist", label: "stylist", icon: "./icon-16.png", onchange: function(state) { if (state.checked) { attach(style, tabs.activetab); } else { detach(style, tabs.activetab); } } }); private windows if your add-on has not opted into private browsing, then you won't see any tabs that are hosted by private browser windows.
... here's an example converting from a high-level tab to a xul tab and then back the other way: var { modelfor } = require("sdk/model/core"); var { viewfor } = require("sdk/view/core"); var tabs = require("sdk/tabs"); var tab_utils = require("sdk/tabs/utils"); function maphighleveltolowlevel(tab) { // get the xul tab that corresponds to this high-level tab var lowleveltab = viewfor(tab); // now we can, for example, access the tab's content directly var browser...
...And 4 more matches
widget - Archive of obsolete content
we can then use a content script to listen for clicks on those buttons.
... but because content scripts can't use the sdk's apis, we'll want the content script to send messages to the main add-on code, which can then implement the media player functions using the sdk.
... private windows if your add-on has not opted into private browsing, then your widget will not appear in any private browser windows.
...And 4 more matches
cfx to jpm - Archive of obsolete content
the sdk expects the latter format, and if the id in package.json doesn't contain "@", then cfx xpi will append "@jetpack" to the package.json field, and make that the add-on id.
... so: if you never did anything with ids when using cfx, then the value in your add-on's package.json will be something like "jid1-f3boogbjqje67a", and the corresponding id in the install.rdf will be "jid1-f3boogbjqje67a@jetpack".
... id handling with jpm when you create an xpi with jpm xpi: if the package.json does not include an id field, then the id written into the install.rdf is the value of the name field prepended with "@".
...And 4 more matches
Bootstrapped extensions - Archive of obsolete content
you need to look up the relevant application ui elements by their id by calling document.getelementbyid(), then manipulate them to inject your ui.
... creating a bootstrapped extension to mark an extension as bootstrappable, you need to add the following element to its install manifest: <em:bootstrap>true</em:bootstrap> then you need to add a bootstrap.js file that contains the required functions; this should be alongside the install.rdf file in the extension's package.
...create your extension as a bootstrappable extension, then add the traditional overlays as well.
...And 4 more matches
Chapter 5: Let's build a Firefox extension - Archive of obsolete content
type chrome://browser/content/browser.xul into the url input field at the top, then click the inspect button.
... click the spots numbered 1 and 2 in figure 5, in that order; the menu element (3) will then be selected.
... suppose you have these strings nested in a .js file: if ( password == userpassword ) { oprefs.setboolpref("access.authenticated", true); } else { alert ("invalid password"); ......
...And 4 more matches
Mozilla Crypto FAQ - Archive of obsolete content
if you wish to develop and distribute cryptographic software, particularly for commercial sale or distribution, then you should consult an attorney with expertise in the particular laws and regulations that apply in your jurisdiction.
... this new rsa-capable version of nss will then be included in a future version of the open source psm software, which will provide ssl support for mozilla.
... support for pgp and other security-related protocols and formats can potentially be added to mozilla in the same manner as ssl and s/mime; if anyone is interested in working on such support within the mozilla project then they are welcome to do so.
...And 4 more matches
The life of an HTML HTTP request - Archive of obsolete content
the webshell then tells its documentloader to load (command "view") the specified url.
...this factory is then told to create a nsicontentviewer.
...the contentviewer is then embed():ed into the contentviewercontainer (the webshell).
...And 4 more matches
Building accessible custom components in XUL - Archive of obsolete content
we define the grid, then define the headers for each row (numbered 1 through 7), then define the column header and cells for each column.
...we will need to declare this namespace as well (xmlns:wairole="http://www.w3.org/2005/01/wai-rdf/guiroletaxonomy#"), and then use this namespace prefix (wairole:) as part of the role attribute value.
...we can declare both of them at the top of our .xul file and then reuse them as often as we need.
...And 4 more matches
Desktop mouse and keyboard controls - Game development
to do that we'll hold the information on whether the keys we are interested in are pressed or not: var rightpressed = false; var leftpressed = false; var uppressed = false; var downpressed = false; then we will listen for the keydown and keyup events and act accordingly in both handler functions.
... inside them we can get the code of the key that was pressed from the keycode property of the event object, see which key it is, and then set the proper variable.
...then the pressed key variables are checked and the playerx and playery variables (that we define earlier just after leftpressed and the others) holding the position of the ship are adjusted by a given amount, let's say 5 pixels.
...And 4 more matches
Creating hyperlinks - Learn web development
if a title's information is truly important to the usability of page, then you should present it in a manner that will be accessible to all users, for example by putting it in the regular text.
...this is done by specifying the directory's name, then a forward slash, then the name of the file.
... the url you would use is projects/index.html: <p>visit my <a href="projects/index.html">project homepage</a>.</p> moving back up into parent directories: if you wanted to include a hyperlink inside projects/index.html pointing to pdfs/project-brief.pdf, you'd have to go up a directory level, then back down into the pdf directory.
...And 4 more matches
General asynchronous programming concepts - Learn web development
in our simple-sync.html example (see it running live), we add a click event listener to a button so that when clicked, it runs a time-consuming operation (calculates 10 million dates then logs the final one to the console) and then adds a paragraph to the dom: const btn = document.queryselector('button'); btn.addeventlistener('click', () => { let mydate; for(let i = 0; i < 10000000; i++) { let date = new date(); mydate = date } console.log(mydate); let pelem = document.createelement('p'); pelem.textcontent = 'this is a newly-added paragraph.'; document.bod...
...y.appendchild(pelem); }); when running the example, open your javascript console then click the button — you'll notice that the paragraph does not appear until after the dates have finished being calculated and the console message has been logged.
...peration() { for(let i = 0; i < 1000000; i++) { ctx.fillstyle = 'rgba(0,0,255, 0.2)'; ctx.beginpath(); ctx.arc(random(0, canvas.width), random(0, canvas.height), 10, degtorad(0), degtorad(360), false); ctx.fill() } } fillbtn.addeventlistener('click', expensiveoperation); alertbtn.addeventlistener('click', () => alert('you clicked me!') ); if you click the first button and then quickly click the second one, you'll see that the alert does not appear until the circles have finished being rendered.
...And 4 more matches
Introduction to web APIs - Learn web development
angular and ember) tend to be packages of html, css, javascript, and other technologies that you install and then use to write an entire web application from scratch.
...ioctx.creategain(); volumeslider.addeventlistener('input', function() { gainnode.gain.value = this.value; }); the final thing to do to get this to work is to connect the different nodes in the audio graph up, which is done using the audionode.connect() method available on every node type: audiosource.connect(gainnode).connect(audioctx.destination); the audio starts in the source, which is then connected to the gain node so the audio's volume can be adjusted.
... the gain node is then connected to the destination node so the sound can be played on your computer (the audiocontext.destination property represents whatever is the default audiodestinationnode available on your computer's hardware, e.g.
...And 4 more matches
Getting started with Svelte - Learn web development
then we will learn how to setup our development environment, create a sample app, understand the structure of the project, and see how to run it locally and build it for production.
...and then there's also svelte native, which lets you build native mobile applications.
...label, and choosing inspect: when compiling the app, svelte changes our h1 styles definition to h1.svelte-1tky8bj, and then modifies every <h1> element in our component to <h1 class="svelte-1tky8bj">, so that it picks up the styles as required.
...And 4 more matches
Vue conditional rendering: editing existing todos - Learn web development
aliased; -moz-osx-font-smoothing: grayscale; color: #0b0c0c; display: block; margin-bottom: 5px; } input { display: inline-block; margin-top: 0.4rem; width: 100%; min-height: 4.4rem; padding: 0.4rem 0.8rem; border: 2px solid #565656; } form { display: flex; flex-direction: row; flex-wrap: wrap; } form > * { flex: 0 0 100%; } </style> note: walk through the above code then read the below description to make sure you understand everything the component is doing before moving on.
... result: onsubmit() method is invoked, which checks that the new label is not empty, then emits the todo-added event (which is then listened for inside app.vue, see above), and finally clears the new label <input>.
... result: checkbox-changed event emitted when the checkbox is checked/unchecked (which is then listened for inside app.vue; see above).
...And 4 more matches
Focus management with Vue refs - Learn web development
to understand what's currently happening: reload your page, then press tab.
...any updates are first performed on the in-memory nodes, and then all the changes that need to be made to the actual nodes on the page are synced in a batch.
...inside it, assign your ref to a variable, and then call the focus() method on the ref.
...And 4 more matches
Introduction to cross browser testing - Learn web development
as long as the site owner is happy with this, then you have done your job.
...you might then further subdivide these — implement common site header and footer, implement product page detail view, implement persistent shopping cart widget, etc.
...this may involve writing different code paths that reproduce functionality in different ways aimed at different browsers, or using a polyfill to mimic any missing support using javascript or other technologies, or using a library that allows you to write a single bit of code and then does different things in the background depending on what the browser supports.
...And 4 more matches
Strategies for carrying out testing - Learn web development
instead, you should try to make sure your site works on the most important target browsers and devices, and then code defensively to give your site the widest support reach it can be expected to have.
...certain countries, or locales), then you will probably have different common browsers to test.
... once you've finished filling in everything, press the get tracking id button, then accept the terms of service that appear.
...And 4 more matches
Gecko info for Windows accessibility vendors
if it is role_pane or role_document then this should be treated as a document for the default modality of the screen reader.
... if it is a role_application, role_dialog or role_alert then stay in focus tracking mode -- there is no need to parse the document.
...here is an algorithm for iterating through the nodes, looking for an item of a particular type: store a pointer to the start_item if the current item has a flows_to relation, follow that relation otherwise, go to the next item in depth first search order if the current item matches your criteria, then return current_item if the current_item == start_item, return null (no item found) if the end has been reached, go back to the start if wrapping is desired, otherwise return null (no item found) go to step 2 checkable, required and invalid states are supported gecko defines three state constants using previously unused states: const unsigned long state_check...
...And 4 more matches
Multiprocess on Windows
ideally, we would like to receive rpcs via threads in the mta, and then forward them in a thread-safe way to gecko's main thread.
...both types of metadata are then made available from within the same dll.
... this is achieved by specifying rcinclude in the dll's moz.build, and then specifying the resources in an .rc file.
...And 4 more matches
Old Thunderbird build
so firstly complete the instructions for your os and then continue following these build instructions.
... get the latest source code from mozilla's comm-central mercurial code repository: hg clone https://hg.mozilla.org/comm-central then, get all the repositories it depends on.
...first, cd into the comm-central subdirectory (created automatically by the previous command): cd comm-central then run: python client.py checkout on some types of network connections, "hg clone" might fail because it gets interrupted.
...And 4 more matches
mozbrowserusernameandpasswordrequired
the mozbrowserusernameandpasswordrequired event is fired when the content within a browser <iframe> requires an http authentification.
... the embedder is supposed to retrieve the necessary credentials, usually using a dialog or a database of username/passwords, and then call authenticate() or cancel() as appropriate.
... details the details property returns an anonymous javascript object with the following members: host a domstring representing the host requesting the http authentification.
...And 4 more matches
Bootstrapping a new locale
when a localization team is registered and your hg repository is set up for a locale, you can then clone the existing mozilla release branch (i.e.
... where active development of the upcoming release of firefox occurs) and then begin the necessary work for translation.
... hg allows localizers to work locally on their machines and then "push" changes to their official mozilla repository.
...And 4 more matches
Mozilla Web Services Security Model
if no such file exists, then access will be denied.
... the allow element if no delegate elements are present or if the web service is in the same directory as the web-script-access.xml file, then the allow elements will be processed.
... if the file exists but contains no allow elements, then all access will be allowed.
...And 4 more matches
Phishing: a short definition
another solution is to strengthen logins with pictures, or colored words, often chosen when signing up for a service.
... two-factor authentication none of the above anti-phishing measures address the basic problem: username/password combinations are often enough to impersonate users.
...a second factor is something a user possesses to further authenticate with a service.
...And 4 more matches
Encrypt Decrypt MAC Keys As Session Objects
); pr_fprintf(pr_stderr, "could not read symkey cka_id attribute\n"); return rv; } return rv; } /* * generate a symmetric key */ pk11symkey * generatesymkey(pk11slotinfo *slot, ck_mechanism_type mechanism, int keysize, secitem *keyid, secupwdata *pwdata) { secstatus rv; pk11symkey *key; if (pk11_needlogin(slot)) { rv = pk11_authenticate(slot, pr_true, pwdata); if (rv != secsuccess) { pr_fprintf(pr_stderr, "could not authenticate to token %s.\n", pk11_gettokenname(slot)); return null; } } /* generate the symmetric key */ key = pk11_tokenkeygen(slot, mechanism, null, keysize, keyid, pr_true, pwdata); if (!key) { ...
...context(ctxmac, pr_true); } if (ctxenc != null) { pk11_destroycontext(ctxenc, pr_true); } return rv; } /* * find the key for the given mechanism */ pk11symkey* findkey(pk11slotinfo *slot, ck_mechanism_type mechanism, secitem *keybuf, secupwdata *pwdata) { secstatus rv; pk11symkey *key; if (pk11_needlogin(slot)) { rv = pk11_authenticate(slot, pr_true, pwdata); if (rv != secsuccess) { pr_fprintf(pr_stderr, "could not authenticate to token %s.\n", pk11_gettokenname(slot)); if (slot) { pk11_freeslot(slot); } return null; } } key = pk11_findfixedkey(slot, mechanism, keybuf, 0); if (!key) { ...
... goto cleanup; } cleanup: return rv; } /* * decryptfile */ secstatus decryptfile(pk11slotinfo *slot, const char *dbdir, const char *outfilename, const char *headerfilename, char *encryptedfilename, secupwdata *pwdata, prbool ascii) { /* * the db is open read only and we have authenticated to it * open input file, read in header, get iv and cka_ids of two keys from it * find those keys in the db token * open output file * loop until eof(input): * read a buffer of ciphertext from input file, * save last block of ciphertext * decrypt ciphertext buffer using cbc and iv, * compute and check mac, then remove mac from plainte...
...And 4 more matches
Encrypt and decrypt MAC using token
); pr_fprintf(pr_stderr, "could not read symkey cka_id attribute\n"); return rv; } return rv; } /* * generate a symmetric key */ pk11symkey * generatesymkey(pk11slotinfo *slot, ck_mechanism_type mechanism, int keysize, secitem *keyid, secupwdata *pwdata) { secstatus rv; pk11symkey *key; if (pk11_needlogin(slot)) { rv = pk11_authenticate(slot, pr_true, pwdata); if (rv != secsuccess) { pr_fprintf(pr_stderr, "could not authenticate to token %s.\n", pk11_gettokenname(slot)); return null; } } /* generate the symmetric key */ key = pk11_tokenkeygen(slot, mechanism, null, keysize, keyid, pr_true, pwdata); if (!key) { ...
...context(ctxmac, pr_true); } if (ctxenc != null) { pk11_destroycontext(ctxenc, pr_true); } return rv; } /* * find the key for the given mechanism */ pk11symkey* findkey(pk11slotinfo *slot, ck_mechanism_type mechanism, secitem *keybuf, secupwdata *pwdata) { secstatus rv; pk11symkey *key; if (pk11_needlogin(slot)) { rv = pk11_authenticate(slot, pr_true, pwdata); if (rv != secsuccess) { pr_fprintf(pr_stderr, "could not authenticate to token %s.\n", pk11_gettokenname(slot)); if (slot) { pk11_freeslot(slot); } return null; } } key = pk11_findfixedkey(slot, mechanism, keybuf, 0); if (!key) { ...
... goto cleanup; } cleanup: return rv; } /* * decryptfile */ secstatus decryptfile(pk11slotinfo *slot, const char *dbdir, const char *outfilename, const char *headerfilename, char *encryptedfilename, secupwdata *pwdata, prbool ascii) { /* * the db is open read only and we have authenticated to it * open input file, read in header, get iv and cka_ids of two keys from it * find those keys in the db token * open output file * loop until eof(input): * read a buffer of ciphertext from input file, * save last block of ciphertext * decrypt ciphertext buffer using cbc and iv, * compute and check mac, then remove mac from plainte...
...And 4 more matches
NSS Sample Code Sample_3_Basic Encryption and MACing
); pr_fprintf(pr_stderr, "could not read symkey cka_id attribute\n"); return rv; } return rv; } /* * generate a symmetric key */ pk11symkey * generatesymkey(pk11slotinfo *slot, ck_mechanism_type mechanism, int keysize, secitem *keyid, secupwdata *pwdata) { secstatus rv; pk11symkey *key; if (pk11_needlogin(slot)) { rv = pk11_authenticate(slot, pr_true, pwdata); if (rv != secsuccess) { pr_fprintf(pr_stderr, "could not authenticate to token %s.\n", pk11_gettokenname(slot)); return null; } } /* generate the symmetric key */ key = pk11_tokenkeygen(slot, mechanism, null, keysize, keyid, pr_true, pwdata); if (!key) { ...
...context(ctxmac, pr_true); } if (ctxenc != null) { pk11_destroycontext(ctxenc, pr_true); } return rv; } /* * find the key for the given mechanism */ pk11symkey* findkey(pk11slotinfo *slot, ck_mechanism_type mechanism, secitem *keybuf, secupwdata *pwdata) { secstatus rv; pk11symkey *key; if (pk11_needlogin(slot)) { rv = pk11_authenticate(slot, pr_true, pwdata); if (rv != secsuccess) { pr_fprintf(pr_stderr, "could not authenticate to token %s.\n", pk11_gettokenname(slot)); if (slot) { pk11_freeslot(slot); } return null; } } key = pk11_findfixedkey(slot, mechanism, keybuf, 0); if (!key) { ...
... goto cleanup; } cleanup: return rv; } /* * decrypt a file */ secstatus decryptfile(pk11slotinfo *slot, const char *dbdir, const char *outfilename, const char *headerfilename, char *encryptedfilename, secupwdata *pwdata, prbool ascii) { /* * the db is open read only and we have authenticated to it * open input file, read in header, get iv and cka_ids of two keys from it * find those keys in the db token * open output file * loop until eof(input): * read a buffer of ciphertext from input file * save last block of ciphertext * decrypt ciphertext buffer using cbc and iv * compute and check mac, then remove mac from plaintext...
...And 4 more matches
EncDecMAC using token object - sample 3
ess) { pr_fprintf(pr_stderr, "pk11_readrawattribute returned (%d)\n", rv); pr_fprintf(pr_stderr, "could not read symkey cka_id attribute\n"); return rv; } return rv; } /* * generate a symmetric key */ pk11symkey * generatesymkey(pk11slotinfo *slot, ck_mechanism_type mechanism, int keysize, secitem *keyid, secupwdata *pwdata) { secstatus rv; pk11symkey *key; if (pk11_needlogin(slot)) { rv = pk11_authenticate(slot, pr_true, pwdata); if (rv != secsuccess) { pr_fprintf(pr_stderr, "could not authenticate to token %s.\n", pk11_gettokenname(slot)); return null; } } /* generate the symmetric key */ key = pk11_tokenkeygen(slot, mechanism, null, keysize, keyid, pr_true, pwdata); if (!key) { pr_fprintf(pr_stderr, "symmetric key generation failed \n"); } return key; } /* * macinit */ secstatus macinit(pk1...
...o cleanup; } rv = secsuccess; cleanup: if (ctxmac != null) { pk11_destroycontext(ctxmac, pr_true); } if (ctxenc != null) { pk11_destroycontext(ctxenc, pr_true); } return rv; } /* * find the key for the given mechanism */ pk11symkey* findkey(pk11slotinfo *slot, ck_mechanism_type mechanism, secitem *keybuf, secupwdata *pwdata) { secstatus rv; pk11symkey *key; if (pk11_needlogin(slot)) { rv = pk11_authenticate(slot, pr_true, pwdata); if (rv != secsuccess) { pr_fprintf(pr_stderr, "could not authenticate to token %s.\n", pk11_gettokenname(slot)); if (slot) { pk11_freeslot(slot); } return null; } } key = pk11_findfixedkey(slot, mechanism, keybuf, 0); if (!key) { pr_fprintf(pr_stderr, "pk11_findfixedkey failed (err %d)\n", pr_geterror()); pk11_freeslot(slot); return null; } return key; } /* * decrypt...
..., mackeyitem, pr_true); if (rv != secsuccess) { pr_fprintf(pr_stderr, "could not retrieve mac cka_id from cipher file\n"); goto cleanup; } cleanup: return rv; } /* * decryptfile */ secstatus decryptfile(pk11slotinfo *slot, const char *dbdir, const char *outfilename, const char *headerfilename, char *encryptedfilename, secupwdata *pwdata, prbool ascii) { /* * the db is open read only and we have authenticated to it * open input file, read in header, get iv and cka_ids of two keys from it * find those keys in the db token * open output file * loop until eof(input): * read a buffer of ciphertext from input file, * save last block of ciphertext * decrypt ciphertext buffer using cbc and iv, * compute and check mac, then remove mac from plaintext * replace iv with saved last block of ciphertext * wr...
...And 4 more matches
PKCS11 FAQ
MozillaProjectsNSSPKCS11FAQ
there have been cases where nss would then use this handle to try to do some operation.
...nss itself uses two tokens internally--one that provides generic cryptographic services without authentication, and one that provides operations based on the keys stored in the user's database and do need authentication.
... if the token is marked read-only, then it will be treated as such.
...And 4 more matches
PKCS #11 Module Specs
if the value is quoted, then the value is terminated with and ending quote of the form ', ", ), ], }, or > matching the respective starting quote.
... publiccerts - the certificates on this token can be read without authenticating to this token, and any user certs on this token have a matching public key which is also readable without authenticating.
... setting this flags means nss will not try to authenticate to the token when searching for certificates.
...And 4 more matches
nsIAuthInformation
netwerk/base/public/nsiauthinformation.idlscriptable a object that holds authentication information.
... 1.0 66 introduced gecko 1.9 inherits from: nsisupports last changed in gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) the caller of nsiauthprompt2.promptusernameandpassword() or nsiauthprompt2.promptpasswordasync() provides an object implementing this interface; the prompt implementation can then read the values here to prefill the dialog.
... after the user entered the authentication information, it should set the attributes of this object to indicate to the caller what was entered by the user.
...And 4 more matches
nsICache
if the cache entry is validated, then a descriptor for that entry will be created and returned.
... if the cache entry was doomed, then a descriptor will be created for a new cache entry for the key.
...if the cache entry is validated, then a descriptor for that entry will be created and returned.
...And 4 more matches
nsIProtocolProxyService
if the protocol handler for the given uri supports nsiproxiedprotocolhandler, then the nsiproxyinfo instance returned from resolve may be passed to the nsiproxiedprotocolhandler.newproxiedchannel() method to create a nsichannel to the given uri that uses the specified proxy.
... however, if the nsiproxyinfo type is "http", then it means that the given uri should be loaded using the http protocol handler, which also supports nsiproxiedprotocolhandler.
... note: if pac is configured, and the pac file has not yet been loaded, then this method will return a nsiproxyinfo instance with a type of "unknown" to indicate to the consumer that asyncresolve should be used to wait for the pac file to finish loading.
...And 4 more matches
XPIDL
idls make it possible to define interfaces which can then be processed by tools to autogenerate language-dependent interface specifications.
... astring const nsastring& nsastring& string full unicode set permitted jsval const jsval& jsval* anything jsid jsid jsid* not allowed promise mozilla::dom::promise* mozilla::dom::promise** promise typedefs in idl are basically as they are in c or c++: you define first the type that you want to refer to and then the name of the type.
...most native types are not scriptable: if it is not present in the list above, then it is certainly not scriptable (some of the above, particularly jsid, are not scriptable).
...And 4 more matches
Address Book examples
use the address book manager to get an nsisimpleenumerator, then progress through the enumerator, looking for nsiabitem, nsiabcollection or nsiabdirectory interfaces as you require.
...assuming you have the uri, then use the address book manager to get an nsiabdirectory representing the address book: let abmanager = components.classes["@mozilla.org/abmanager;1"] .getservice(components.interfaces.nsiabmanager); let oneaddressbook = abmanager.getdirectory(addressbookuri); how do i search for a particular contact property (name, email)?
...once you have the nsiabcard object you can modify the names and description of it like this: maillistcard.displayname = "new list name"; maillistcard.lastname = maillistcard.displayname; maillistcard.setproperty("nickname", "new nickname for list"); maillistcard.setproperty("notes", "new list description"); then you need to get the equivalent mailing list object that implements nsiabdirectory: let abmanager = components.classes["@mozilla.org/abmanager;1"] .getservice(components.interfaces.nsiabmanager); let maillistdirectory = abmanager.getdirectory(maillistcard.maillisturi); you can then adjust the items in the actual mailing list: maillistdirectory.addresslists.appendelem...
...And 4 more matches
Debugger.Object - Firefox Developer Tools
if the referent uses destructuring parameters, then the array's elements reflect the structure of the parameters.
...} then this debugger.object instance's parameternames property would have the value: ["a", ["b", "c"], {d:"d", e:"f"}] script if the referent is a function that is debuggee code, this is that function's script, as a debugger.script instance.
... ifcode is not strict mode code, then variable declarations incode affect the referent global object.
...And 4 more matches
Using microtasks in JavaScript with queueMicrotask() - Web APIs
the microtask queue is, then, processed multiple times per iteration of the event loop, including after handling events and other callbacks.
...consider code such as this: customelement.prototype.getdata = url => { if (this.cache[url]) { this.data = this.cache[url]; this.dispatchevent(new event("load")); } else { fetch(url).then(result => result.arraybuffer()).then(data => { this.cache[url] = data; this.data = data; this.dispatchevent(new event("load")); }); } }; the problem introduced here is that by using a task in one branch of the if...else statement (in the case in which the image is available in the cache) but having promises involved in the else clause, we have a situation in which the ord...
... we can ensure consistent ordering of these operations by using a microtask in the if clause to balance the two clauses: customelement.prototype.getdata = url => { if (this.cache[url]) { queuemicrotask(() => { this.data = this.cache[url]; this.dispatchevent(new event("load")); }); } else { fetch(url).then(result => result.arraybuffer()).then(data => { this.cache[url] = data; this.data = data; this.dispatchevent(new event("load")); }); } }; this balances the clauses by having both situations handle the setting of data and firing of the load event within a microtask (using queuemicrotask() in the if clause and using the promises used by fetch() in the else clause).
...And 4 more matches
Checking when a deadline is due - Web APIs
the main example application we will be referring to in this article is to-do list notifications, a simple to-do list application that stores task titles and deadline times and dates via indexeddb, and then provides users with notifications when deadline dates are reached, via the notification, and vibration apis.
... the basic problem in the to-do app, we wanted to first record time and date information in a format that is both machine readable and human understandable when displayed, and then check whether each time and date is occurring at the current moment.
... basically, we want to check what the time and date is right now, and then check each stored event to see if any of their deadlines match the current time and date.
...And 4 more matches
Recording a media element - Web APIs
ngthinms) { let recorder = new mediarecorder(stream); let data = []; recorder.ondataavailable = event => data.push(event.data); recorder.start(); log(recorder.state + " for " + (lengthinms/1000) + " seconds..."); let stopped = new promise((resolve, reject) => { recorder.onstop = resolve; recorder.onerror = event => reject(event.name); }); let recorded = wait(lengthinms).then( () => recorder.state == "recording" && recorder.stop() ); return promise.all([ stopped, recorded ]) .then(() => data); } startrecording() takes two input parameters: a mediastream to record from and the length in milliseconds of the recording to make.
... 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 => { let recordedblob = new blob(recordedchunks, { type: "video/webm" }); ...
...the "download" button's link is then set to refer to the stream as well.
...And 4 more matches
PublicKeyCredentialRequestOptions.extensions - Web APIs
extensions are values requesting additional processing by the client and by the authenticator.
...this text is displayed on a prompt of the authenticator before verifying the user or testing their presence.
...this is used to display an image or some non-textual content on the authenticator before verifying the user or testing their presence.
...And 4 more matches
RTCConfiguration - Web APIs
certificates optional an array of objects of type rtccertificate which are used by the connection for authentication.
...if this value is set (it defaults to null), the rtcpeerconnection will not connect to a remote peer unless it can successfully authenticate with the given name.
...if the remote endpoint is not bundle-aware, then each of these dtls transports then handles all the communication for one type of data.
...And 4 more matches
RTCPeerConnection.addTrack() - Web APIs
since streams are specific to each peer, specifying one or more streams means the other peer will create a corresponding stream (or streams) automatically on the other end of the connection, and will then automatically add the received track to those streams.
... streamless tracks if no streams are specified, then the track is streamless.
... 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 assoc...
...And 4 more matches
RTCPeerConnection - Web APIs
the answer is delivered to the returned promise, and should then be sent to the source of the offer to continue the negotiation process.createdatachannel() the createdatachannel() method on the rtcpeerconnection interface creates a new channel linked with the remote peer, over which any kind of data may be transmitted.createoffer()the createoffer() method of the rtcpeerconnection interface initiates the creation of an sdp offer for the purpose of starting a n...
...ew webrtc connection to a remote peer.generatecertificate()the generatecertificate() method of the rtcpeerconnection interface creates and stores an x.509 certificate and corresponding private key then returns an rtccertificate, providing access to it.getconfiguration() the rtcpeerconnection.getconfiguration() method returns an rtcconfiguration object which indicates the current configuration of the rtcpeerconnection on which the method is called.getidentityassertion() the rtcpeerconnection.getidentityassertion() method initiates the gathering of an identity assertion.
...a track is isolated if its content cannot be accessed by the owning document due to lack of authentication or if the track comes from a cross-origin source.
...And 4 more matches
Request.cache - Web APIs
WebAPIRequestcache
reload — the browser fetches the resource from the remote server without first looking in the cache, but then will update the cache with the downloaded resource.
...fetch("some.json", {cache: "no-store"}) .then(function(response) { /* consume the response */ }); // download a resource with cache busting, but update the http // cache with the downloaded resource.
... fetch("some.json", {cache: "reload"}) .then(function(response) { /* consume the response */ }); // download a resource with cache busting when dealing with a // properly configured server that will send the correct etag // and date headers and properly handle if-modified-since and // if-none-match request headers, therefore we can rely on the // validation to guarantee a fresh response.
...And 4 more matches
SubtleCrypto.deriveKey() - Web APIs
if algorithm is ecdh, then this will be the ecdh private key.
...they can then use this shared secret as a symmetric key to secure their communication, or can use the secret as an input to derive such a key (for example, using the hkdf algorithm).
... ecdh in this example alice and bob each generate an ecdh key pair, then exchange public keys.
...And 4 more matches
Taking still photos with WebRTC - Web APIs
try this sample then read on to learn how it works.
... next, we have a <canvas> element into which the captured frames are stored, potentially manipulated in some way, and then converted into an output image file.
... initialization we start by wrapping the whole script in an anonymous function to avoid global variables, then setting up various variables we'll be using.
...And 4 more matches
Web Video Text Tracks Format (WebVTT) - Web APIs
on the same line, we then have a string of "-->".
... we can then have one or more lines that start with a hyphen (-), each containing part of the text track to be shown.
...example 6 consists of the header, a blank line, and then five cues separated by blank lines.
...And 4 more matches
Spaces and reference spaces: Spatial tracking in WebXR - Web APIs
getpose() computes the position of an xrreferencespace relative to the origin of a specified xrspace and then creates a pose representing the resulting position and orientation.
... for example, if you wish to draw a hand controller's representation using the controller's gripspace, you can get the pose needed like this: let controlpose = frame.getpose(worldrefspace, inputsource.gripspace); this converts the position and orientation of the input's grip space to use the world's coordinate system, then generates the corresponding xrpose, storing it in controlpose.
... you can then apply controlpose's transform to the vertices in the object model representing the controller to calculate the webgl coordinates to use when rendering the controller's representation to the framebuffer.
...And 4 more matches
Aligning Items in a Flex Container - CSS: Cascading Style Sheets
if your flex container has a height set, then the items will stretch to that height, regardless of how much content is in the item.
...if you have a wrapped multiple-line flex container then you might also want to use the align-content property to control the distribution of space between the rows.
...it then works on all the items as a set, and dictates what happens with that free space, and the alignment of the entire set of items within it.
...And 4 more matches
Ordering Flex Items - CSS: Cascading Style Sheets
if you are working in a right-to-left language like arabic then row would start on the right, row-reverse on the left.
...this allows authors to manipulate the visual presentation while leaving the source order intact for non-css uas and for linear models such as speech and sequential navigation.” - ordering and orientation if your items were links or some other element that the user could tab to, then the tabbing order would be the order that these items appear in the document source — not your visual order.
...the items are then placed in the visual order according to that integer, lowest values first.
...And 4 more matches
Relationship of flexbox to other layout methods - CSS: Cascading Style Sheets
flexbox and other layout methods the flexbox specification contains a definition of what happens if an item uses another layout method and then becomes a flex item.
... for example, if an item is floated and then its parent becomes a flex container.
... with regard to flex items, if an item was floated or cleared and then becomes a flex item due to the parent having display: flex applied, the floating and clearing will no longer happen, and the item will not be taken out of normal flow in the way that floats are.
...And 4 more matches
Grid template areas - CSS: Cascading Style Sheets
we can also define an area by giving it a name and then specify the location of that area in the value of the grid-template-areas property.
... .header { grid-area: hd; } .footer { grid-area: ft; } .content { grid-area: main; } .sidebar { grid-area: sd; } having defined these names i then create my layout.
...dius: 5px; background-color: #ffd8a8; padding: 1em; color: #d9480f; } .header { grid-area: hd; } .footer { grid-area: ft; } .content { grid-area: main; } .sidebar { grid-area: sd; } .wrapper { display: grid; grid-auto-rows: minmax(100px, auto); grid-template-columns: 1fr; grid-template-areas: "hd" "main" "sd" "ft"; } we can then redefine that layout inside media queries to go to our two columns layout, and perhaps take it to a three column layout if the available space is even wider.
...And 4 more matches
Visual formatting model - CSS: Cascading Style Sheets
if the viewport is smaller than the size of the document then the user agent needs to offer a way to scroll to the parts of the document that are not displayed.
... then, for each element, css generates zero or more boxes as specified by that element’s display property value.
...it will then behave as a flex item, however, it cannot be targeted and styled like a regular box because there is no element to target.
...And 4 more matches
Audio and Video Delivery - Developer guides
javascript audio var myaudio = document.createelement('audio'); if (myaudio.canplaytype('audio/mpeg')) { myaudio.setattribute('src','audiofile.mp3'); } else if (myaudio.canplaytype('audio/ogg')) { myaudio.setattribute('src','audiofile.ogg'); } myaudio.currenttime = 5; myaudio.play(); we set the source of the audio depending on the type of audio file the browser supports, then set the play-head 5 seconds in and attempt to play it.
... javascript video var myvideo = document.createelement('video'); if (myvideo.canplaytype('video/mp4')) { myvideo.setattribute('src','videofile.mp4'); } else if (myvideo.canplaytype('video/webm')) { myvideo.setattribute('src','videofile.webm'); } myvideo.width = 480; myvideo.height = 320; we set the source of the video depending on the type of video file the browser supports we then set the width and height of the video.
... 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 { alert('getusermedia is not supported in this browser.'); } to find out more, read our me...
...And 4 more matches
<input type="datetime-local"> - HTML: Hypertext Markup Language
if the value of the max attribute isn't a valid string which follows the format yyyy-mm-ddthh:mm, then the element has no maximum value.
...if the value of the min attribute isn't a valid string which follows the format yyyy-mm-ddthh:mm, then the element has no minimum value.
... we'll look at basic and more complex uses of <input type="datetime-local">, then offer advice on mitigating the browser support issue later on (see handling browser support).
...And 4 more matches
An overview of HTTP - HTTP
WebHTTPOverview
it then parses this file, making additional requests corresponding to execution scripts, layout information (css) to display, and sub-resources contained within the page (usually images and videos).
... the web browser then mixes these resources to present to the user a complete document, the web page.
...proxies may perform numerous functions: caching (the cache can be public or private, like the browser cache) filtering (like an antivirus scan or parental controls) load balancing (to allow multiple servers to serve the different requests) authentication (to control access to different resources) logging (allowing the storage of historical information) basic aspects of http http is simple http is generally designed to be simple and human readable, even with the added complexity introduced in http/2 by encapsulating http messages into frames.
...And 4 more matches
Details of the object model - JavaScript
then, when you create a new manager, it inherits the name and dept properties from the employee object.
... adding and removing properties in class-based languages, you typically create a class at compile time and then you instantiate instances of the class either at compile time or at run time.
...in javascript, you add a prototypical instance as the value of the prototype property of the constructor function, then override the prototype.constructor to the constructor function.
...And 4 more matches
Array.prototype.sort() - JavaScript
the default sort order is ascending, built upon converting the elements into strings, then comparing their sequences of utf-16 code units values.
...if omitted, the array elements are converted to strings, then sorted according to each character's unicode code point value.
...if a and b are two elements being compared, then: if comparefunction(a, b) returns less than 0, sort a to an index lower than b (i.e.
...And 4 more matches
Promise.prototype.catch() - JavaScript
it behaves the same as calling promise.prototype.then(undefined, onrejected) (in fact, calling obj.catch(onrejected) internally calls obj.then(undefined, onrejected)).
... return value internally calls promise.prototype.then on the object upon which it was called, passing the parameters undefined and the received onrejected handler.
... demonstration of the internal call: // overriding original promise.prototype.then/catch just to add some logs (function(promise){ var originalthen = promise.prototype.then; var originalcatch = promise.prototype.catch; promise.prototype.then = function(){ console.log('> > > > > > called .then on %o with arguments: %o', this, arguments); return originalthen.apply(this, arguments); }; promise.prototype.catch = function(){ console.error...
...And 4 more matches
async function - JavaScript
for example: async function foo() { await 1 } ...is equivalent to: function foo() { return promise.resolve(1).then(() => undefined) } code after each await expression can be thought of as existing in a .then callback.
...progress through foo is then suspended and control is yielded back to the function that called foo.
...this runs 2 seconds after 1., immediately after 2., since fast is already resolved } function concurrentpromise() { console.log('==concurrent start with promise.all==') return promise.all([resolveafter2seconds(), resolveafter1second()]).then((messages) => { console.log(messages[0]) // slow console.log(messages[1]) // fast }) } async function parallel() { console.log('==parallel with await promise.all==') // start 2 "jobs" in parallel and wait for both of them to complete await promise.all([ (async()=>console.log(await resolveafter2seconds()))(), (async()=>console.log(await resolveafter1second()))() ]) ...
...And 4 more matches
Authoring MathML - MathML
if you need only basic mathematical constructions such as those used on this mdn wiki then a small mathml.css stylesheet might be enough.
...for example, here is a minimal stylesheet to use latin modern for the text and latin modern math for the mathematics: @namespace url('http://www.w3.org/1999/xhtml'); @namespace m url('http://www.w3.org/1998/math/mathml'); body, m|mtext { font-family: latin modern; } m|math { font-family: latin modern math; } you can then use the @font-face rule as usual to provide woff fallback for latin modern and latin modern math.
... gecko-based instant messaging clients can integrate a javascript-based text-to-mathml converter (mentioned below) and then render the mathml expressions generated from the (plaintext) instant messages.
...And 4 more matches
Codecs used by WebRTC - Web media technologies
however, if this isn't signaled as supported in the sdp, then it's encouraged that browsers support display orientation sei messages, though not required.
... if the connection is in the process of starting up, you can use the icegatheringstatechange event to watch for the completion of ice candidate gathering, then fetch the list.
...we then call that sender's getparameters() method and, from the returned rtcrtpsendparameters object, we set codeclist to the codecs property and return to the caller.
...And 4 more matches
Transport Layer Security - Web security
http over tls tls provides three primary services that help ensure the safety and security of data exchanged with it: authentication authentication lets each party to the communication verify that the other party is who they claim to be.
... in tls 1.2 and earlier, the negotiated cipher suite includes a set of cryptographic algorithms that together provide the negotiation of the shared secret, the means by which a server is authenticated, and the method that will be used to encrypt data.
... the cipher suite in tls 1.3 primarily governs the encryption of data, separate negotiation methods are used for key agreement and authentication.
...And 4 more matches
page-mod - Archive of obsolete content
its event handler sends the getelements message to the content script, and then adds a listener to the gotelement message.
... if multiple documents that match the page-mod's include pattern are loaded, then each document is loaded into its own execution context with its own copy of the content scripts.
...ontentscriptfile: data.url("eaten.js") }); the content script replaces the page contents, but restores the original contents when it receives detach: // eaten.js var oldinnerhtml = window.document.body.innerhtml; window.document.body.innerhtml = "eaten!"; self.port.on("detach", function() { window.document.body.innerhtml = oldinnerhtml; }); try running the add-on, loading some pages, and then disabling the add-on in the add-ons manager.
...And 3 more matches
/loader - Archive of obsolete content
les/commonjs/toolkit/', // resolve all other non-relative module requirements as follows: // devtools/gcli -> resource:///modules/devtools/gcli.js // panel -> resource:///modules/panel.js '': 'resource:///modules/', } }) all relative url require() statements (those that start with ".") are first resolved relative to the requirer module id and the result of it is then resolved using the paths option.
...for example in the sdk, the loader is loaded at bootstrap as a jsm module but is then exposed as a pseudo-module to avoid the overhead of subsequent loads: let loadermodule = cu.import('resource://gre/modules/commonjs/toolkit/loader.js'); let loader = loadermodule.loader({ modules: { // overlay `toolkit/loader` so that `require('toolkit/loader')` // will return our `loadermodule`.
... resolve is assigned a function that takes: the id of the module passed into require() the id of the module that called require() on each require() call, the supplied function is then called with the id of the required module and that of the requiring module.
...And 3 more matches
ui/button/action - Archive of obsolete content
if badgecolor is omitted and badge is specified, then the badge is red.
... by default, a button's properties are global, meaning that they are the same across all open windows and tabs, and that if you update these properties, then they are updated across all windows and tabs.
...for example, if you have a window with two tabs, and you set a tab-specific label, then set the window-specific label, this will not overwrite the tab-specific label: var { actionbutton } = require('sdk/ui/button/action'); var tabs = require("sdk/tabs"); var button = actionbutton({ id: "my-button", label: "default label", icon: "./firefox-16.png" }); tabs.open({ url: "https://mozilla.org/", onopen: onnewtab }); function onnewtab(tab) { // modify the label only for th...
...And 3 more matches
Creating custom Firefox extensions with the Mozilla build system - Archive of obsolete content
focus on the fact that once you get the build working, it'll probably work effortlessly from then on.
... then open the generated header file for your interface from /mozilla/$(moz_objdir)/dist/include/.
...(if something goes wrong, figure out what, fix it and then come back here and add it to this article.) to make sure that the build really finished, launch firefox and check that your extension is listed when you select tools/extensions.
...And 3 more matches
Appendix B: Install and Uninstall Scripts - Archive of obsolete content
window.addeventlistener( "load", function() { xulschoolchrome.browseroverlay.init(); }, false); then all we need is some persistent flag that ensures that the first run code is only run once.
...and then do a version comparison to decide which code to run.
... uninstalling an add-on happens in 2 stages: first the add-on is flagged to be uninstalled, and then the add-on is actually removed.
...And 3 more matches
Style System Overview - Archive of obsolete content
1 matching rule: use value 2+ matching rules: cascade decides which wins: sort by origin (ua, user, author) & weight (!important), then specificity of selector, then order example document source <doc> <title>a few quotes</title> <para class="emph"> franklin said that <quote>"a penny saved is a penny earned."</quote> </para> <para> fdr said <quote>"we have nothing to fear but <span class="emph">fear itself.</span>"</quote> </para> </doc> example document tree ...
... cssruleprocessor one cssruleprocessor per origin (ua, user, author) css rule processor sorts all the rules in cascade order, and then puts them in rulehash, which remembers order and then hashes by first of id, class, tag, namespace, or unhashed.
... to match rules, we do lookups in the rulehash's tables, remerge the lists of rules using stored indices, and then call selectormatchestree to find which selectors really match.
...And 3 more matches
Migrate apps from Internet Explorer to Mozilla - Archive of obsolete content
you can deal with this by having an onload handler in the new window and then call back into the opener window (using window.opener).
...if the page is in strict standards mode, and no units are used, then mozilla ignores the style: <doctype html public "-//w3c//dtd html 4.01//en" "http://www.w3.org/tr/html4/strict.dtd"> <html> <head> <meta http-equiv="content-type" content="text/html; charset=iso-8859-1"> <title>css and units example</title> </head> <body> // works in strict mode <div style="width: 40px; border: 1px solid black;"> text </div> // will fail in s...
...it then walks the dom using the most direct route toward the target, which is the capturing phase.
...And 3 more matches
New Security Model for Web Services - Archive of obsolete content
if the sandbox is unable to distinguish the common uri substring of the domain to be trusted from similar uris of untrusted domains, then it could allow a script loaded from an indistinguishable domain to exploit firewall-protected resources.
... the root element the first element of the file should be the following: <wsa:webscriptaccess xmlns:wsa="http://www.mozilla.org/2002/soap/security"> delegation if the <delegate/> element is present then "web-scripts-access.xml" is required in the subdirectory for uris which are in a subdirectory.
... for example, if the script in question is "http://www.example.com/foo/bar.xml", then the declarations file http://www.example.com/web-scripts-access.xml which contains the "delegate" keyword delegates to http://www.example.com/foo/web-scripts-access.xml.
...And 3 more matches
Space Manager High Level Design - Archive of obsolete content
in this case the space manager is also asked if there is any float damage, and if there is then the block further checks to see if that damage intersects the area of the non-dirty line, marking it dirty if there is intersection.
... if the block has any block children, then translate the space manager to the child block's origin and update the space manager in the context for the child block, recursively.
... blockbanddata then gets the band data from the space manager via a call to the space manager associated with the blockbanddata instance.
...And 3 more matches
Elements - Archive of obsolete content
this name can then be used to reference the implementation.
...if no name attribute is specified then the binding's document uri and id are used to uniquely reference the binding's implementation.
...if present in the list, then the modifier key must be set in the dom event object in order for the handler to be matched.
...And 3 more matches
Using XPInstall to Install Plugins - Archive of obsolete content
you can create an xpinstall file by first zipping all the items you want installed with winzip (create a zip archive) and then renaming it with the xpi file extension instead of the zip file extension.
... if the plugin is scriptable, then it will also consist of an xpt file.
...often, the smartupdate download was triggered via the pluginurl attribute of the embed tag: <embed type="application/x-randomtype" src="myfile.typ" width="50" height="50" pluginurl="http://mytypecompany.xyz/jarpacks/mytypeplugin.jar"></embed> in the example above, the pluginurl attribute points to the signed jar file, which netscape communicator 4.x would then download (subject to the security dialog boxes) if the plugin was not located on the user's machine.
...And 3 more matches
Encryption and Decryption - Archive of obsolete content
symmetric-key encryption also provides a degree of authentication, since information encrypted with one symmetric key cannot be decrypted with any other symmetric key.
...if anyone else discovers the key, it affects both confidentiality and authentication.
... symmetric-key encryption plays an important role in the ssl protocol, which is widely used for authentication, tamper detection, and encryption over tcp/ip networks.
...And 3 more matches
Sunbird Theme Tutorial - Archive of obsolete content
note: if your theme is for a version of sunbird later than 0.4, then also change the maxversion.
...go to the <tt>skin</tt> directory that has just been created, then to the <tt>classic</tt> directory there.
... fixing bug 320823 if you are using the sunbird 0.3a1 release, or a test build before 2005-12-21, then you must apply a fix for bug 320823 to allow sunbird to use themes.
...And 3 more matches
XForms Custom Controls - Archive of obsolete content
for example, if mediatype='image/*' then the user should see the image that the bytes represent rather than just the byte sequence.
... xf|output[mediatype^="image"] { -moz-binding: url('chrome://xforms/content/xforms-xhtml.xml#xformswidget-output-mediatype-anyuri'); } custom data types if you define a new schema data type or you use a built-in data type and find the current xforms control for this type to be insufficient, then you should write a new custom control.
...for example, if a control is bound to a node of type xsd:integer then the typelist attribute will be "http://www.w3.org/2001/xmlschema#integer http://www.w3.org/2001/xmlschema#decimal".
...And 3 more matches
2D maze game with device orientation - Game development
now we will add the ability to control the ball with the keyboard on the desktop devices, and then we will move to the implementation of the device orientation api.
...then, to load the level we'll parse the data and show the blocks specific for that level.
...then the arcade body type is set for that group to enable physics calculations.
...And 3 more matches
Backgrounds and borders - Learn web development
if you specify a background color in addition to a background image then the image displays on top of the color.
...you can create a gradient then copy and paste out the source code that generates it.
...the first two position values will be applied to the first two images, then they will cycle back around again — image3 will be given the first position value, and image4 will be given the second position value.
...And 3 more matches
Responsive design - Learn web development
a common approach when using media queries is to create a simple single-column layout for narrow-screen devices (e.g mobile phones), then check for larger screens and implement a multiple-column layout when you know that you have enough screen width to handle it.
...the browser then works out the size of these, a size that will change according to the screen size.
...the browser will create as many columns of that width as will comfortably fit into the container, then share out the remaining space between all the columns.
...And 3 more matches
How CSS works - Learn web development
the browser then fetches most of the resources that are linked to by the html document, such as embedded images and videos ...
...the span nodes are also parents, with text nodes as their children: p ├─ "let's use:" ├─ span | └─ "cascading" ├─ span | └─ "style" └─ span └─ "sheets" this is how a browser interprets the previous html snippet —it renders the above dom tree and then outputs it in the browser like so: p {margin:0;} applying css to the dom let's say we added some css to our document, to style it.
... again, the html is as follows: <p> let's use: <span>cascading</span> <span>style</span> <span>sheets</span> </p> let's suppose we apply the following css to it: span { border: 1px solid black; background-color: lime; } the browser will parse the html and create a dom from it, then parse the css.
...And 3 more matches
JavaScript basics - Learn web development
then load index.html in your browser.
...you did this by using a function called queryselector() to grab a reference to your heading, and then store it in a variable called myheading.
...if values couldn't change, then you couldn't do anything dynamic, like personalize a greeting message or change an image displayed in an image gallery.
...And 3 more matches
Publishing your website - Learn web development
then it steps through one method that can work right away for many readers.
...then the program shows you your local files and the web server's files in two windows, and provides a way for you to transfer files back and forth.
...you can then collaborate on code projects, and the system is open-source by default, meaning that anyone in the world can find your github code, use it, learn from it, and improve on it.
...And 3 more matches
Responsive images - Learn web development
this kind of problem didn't exist when the web first existed, in the early to mid 90s — back then the only devices in existence to browse the web were desktops and laptops, so browser engineers and spec writers didn't even think to implement solutions.
... note: in the <head> of the example linked above, you'll find the line <meta name="viewport" content="width=device-width">: this forces mobile browsers to adopt their real viewport width for loading web pages (some mobile browsers lie about their viewport width, and instead load pages at a larger viewport width then shrink the loaded page down, which is not very helpful for responsive images or design).
...so, you could offer multiple images via a <picture> element, but then also offer multiple resolutions of each one.
...And 3 more matches
Looping code - Learn web development
in pseudocode, this would look something like the following: loop(food = 0; foodneeded = 10) { if (food >= foodneeded) { exit loop; // we have enough food; let's go home } else { food += 2; // spend an hour collecting 2 more food // loop will then run again } } so the amount of food needed is set at 10, and the amount the farmer currently has is set at 0.
...after each time the loop has run, 1 will be added to i (i++), then the process will start again.
... we store the value entered into the text input in a variable called searchname, before then emptying the text input and focusing it again, ready for the next search.
...And 3 more matches
Making decisions in your code — conditionals - Learn web development
for example, in a game, if the player's number of lives is 0, then it's game over.
...we then use a conditional statement to show different text inside the paragraph depending on what the value of choice is.
... let's look at a quick or example: if (icecreamvanoutside || housestatus === 'on fire') { console.log('you should leave the house quickly.'); } else { console.log('probably should just stay in then.'); } the last type of logical operator, not, expressed by the !
...And 3 more matches
React interactivity: Events and state - Learn web development
instead, we can write a function in <app /> that will expect some data from our form as an input, then pass that function to <form /> as a prop.
... we then need to make a new array with this new task added to it and then update the state of the tasks data to this new state.
...we then pass this array into settasks() to update the state.
...And 3 more matches
Deployment and next steps - Learn web development
code along with us git clone the github repo (if you haven't already done it) with: git clone https://github.com/opensas/mdn-svelte-tutorial.git then to get to the current app state, run cd mdn-svelte-tutorial/08-next-steps or directly download the folder's content: npx degit opensas/mdn-svelte-tutorial/08-next-steps remember to run npm install && npm run dev to start your app in development mode.
... first you'll have to register at gitlab and then create a new project.
... with these instructions we initialize a local git repository, then set our remote origin (where we will push our code to) as our repo on gitlab.
...And 3 more matches
Simple Instantbird build
so firstly complete the instructions for your os and then continue following these build instructions.
... get the latest source code from mozilla's comm-central mercurial code repository: hg clone http://hg.mozilla.org/comm-central then, get all the repositories it depends on.
...first, cd into the comm-central subdirectory (created automatically by the previous command): cd comm-central then run: python client.py checkout note: unless you have a very good network connection, "hg clone" might fail because it gets interrupted.
...And 3 more matches
Cross Process Object Wrappers
however, if an add-on passes a cpow into a platform api, and that platform api then attempts an unsafe operation on it, this will throw an exception.
... chrome code can load frame scripts into the content process using the message manager, and can then communicate with them using a message-passing api.
...this is because the chrome process runs the firefox ui, so if it were blocked by the content process, then a slow content process could cause firefox to become unresponsive to users.
...And 3 more matches
HTML parser threading
nshtml5owningutf16buffer objects are then passed to the tokenizer in sequence by the parseavailabledata() method.
...the method then enters a loop that has a bunch of return conditions (including parser termination).
...the outer loop then has an inner loop that iterates over the tree ops in the executor's queue and calls perform on each one.
...And 3 more matches
JNI.jsm
there also exists a jenv variable in the window scope, so if you need to run jni from the global scope, use a different variable name then jenv.
... if it is the sig of a typed array such as '[i' then adeclares must not be declared.
... if it is the name of a class, then adeclares must be declared.
...And 3 more matches
Application Translation with Mercurial
if it is a red text consisting of a number and the word 'missing', then there are untranslated texts and you can move on with this guide.
...by pressing the windows key and r on the keyboard or by calling the "run..." command from the windows "start" button, and then typing cmd and pressing the enter key.
...c:\mozilla\coding\buildtools\mozillabuild\start-shell-msvc2010.bat you can autocomplete the file path after typing a few characters and then pressing the tabulator key.
...And 3 more matches
Localizing extension descriptions
each has at least one em:locale property marking the locale that the information should be used for and then all the various strings for the locale.
... the process for selecting the em:localized property to use for a given locale is as follows: if a property exists with an em:locale that matches the locale exactly, then use that.
... if we have inexact matches then use the one with the most matching parts, parts being separated by a dash (e.g., es would match for es-es and vice versa).
...And 3 more matches
Investigating leaks using DMD heap scan mode
if you are investigating a leak of www.example.com, then from $logdir you can do "grep nsglobalwindow cc-edges* | grep example.com".
... this looks through all of the windows in all of the cc logs (which may leaked, this late in shutdown), and then filters out windows where the url contains example.com.
...the goal is to eventually shrink down the “something else” category until there are only as many things in it as there are unknown references to the leaking object, and then you have your leaker.
...And 3 more matches
Profiling with the Firefox Profiler
you can then select corresponding call tree entries and watch the timeline for entries in the content process main thread that get darker as you select call tree entries.
...while looking for performance problems, you're looking for the processes that are taking the most time; then you can figure out how to optimize them.
... then capture the profile using the add-on as usual.
...And 3 more matches
NSS Certificate Download Specification
if the private key associated with the certificate does not exist in the user's local key database, then an error dialog is generated and the certificate is not imported.
... if a certificate chain is being imported then the first certificate in the chain must be the user certificate, and any subsequent certificates will be added as untrusted ca certificates to the local database.
...if a certificate chain is being imported then the first certificate in the chain must be the ca certificate, and any subsequent certificates will be added as untrusted ca certificates to the local database.
...And 3 more matches
Enc Dec MAC Output Public Key as CSR
/* * get the private key corresponding to public key */ seckeyprivatekey * getrsaprivatekey(pk11slotinfo *slot, secupwdata *pwdata, seckeypublickey *pubkey) { seckeyprivatekey *privkey = null; secitem *cka_id; if (slot == null) { fprintf(stderr, "empty slot\n"); goto cleanup; } if (pk11_authenticate(slot, pr_true, pwdata) != secsuccess) { fprintf(stderr, "could not authenticate to token %s.", pk11_gettokenname(slot)); goto cleanup; } cka_id = &pubkey->u.rsa.modulus; cka_id = pk11_makeidfrompubkey(cka_id); privkey = pk11_findkeybykeyid(slot, cka_id, pwdata); cleanup: return privkey; } /* * generate the certificate request with sub...
...tail from header file\n"); goto cleanup; } cleanup: return rv; } /* * decryptfile */ secstatus decryptfile(pk11slotinfo *slot, const char *outfilename, const char *headerfilename, char *encryptedfilename, secupwdata *pwdata, prbool ascii) { /* * the db is open read only and we have authenticated to it * open input file, read in header, get iv and wrapped keys and * public key * unwrap the wrapped keys * loop until eof(input): * read a buffer of ciphertext from input file, * save last block of ciphertext * decrypt ciphertext buffer using cbc and iv, * compute and check mac, then remove mac from plaintext * replace iv ...
...encryptfile */ secstatus encryptfile(pk11slotinfo *slot, const char *infilename, const char *certreqfilename, const char *headerfilename, const char *encryptedfilename, const char *noisefilename, secupwdata *pwdata, prbool ascii) { /* * the db is open for read/write and we have authenticated to it.
...And 3 more matches
PKCS11 Implement
true true the device has been initialized and requires authentication.
...if a token has been removed and then the same or another token is inserted, c_getsessioninfo should return ckr_session_handle_invalid.
...for example, if a particular token can't do des encryption, nss decrypts the key, then copies it over to the token that can do des encryption.
...And 3 more matches
Rhino scopes and contexts
you can create a scope using one context and then evaluate a script using that scope and another context (either by exiting the current context and entering another, or by executing on a different thread).
...in general, variables are looked up by starting at the current variable object (which is different depending on what code is being executed in the program), traversing its prototype chain, and then traversing the parent chain.
...then all we need to do is create a new object and call its setprototypemethod to set the prototype to the shared object, and the parent of the new scope to null: scriptable newscope = cx.newobject(sharedscope); newscope.setprototype(sharedscope); newscope.setparentscope(null); the call to newobject simply creates a new javascript object with no properties.
...And 3 more matches
Garbage collection
an arena is one page (4096 bytes on almost all platforms) and contains an arenaheader, a few pad bytes, and then an array of aligned elements.
... marking todo incremental marking incremental marking means being able to do a bit of marking work, then let the mutator (javascript program) run a bit, then do another bit of marking work.
...if the mutator stores b into a, so that a contains a pointer to b, and deletes all existing pointers to b, then: b is live, because a is black and contains a pointer to b.
...And 3 more matches
Tracing JIT
the monitor then calls into the native code stored in the fragment.
...it then passes control back to the spidermonkey interpreter.
... it then imports the set of jsval values from the spidermonkey interpreter that the trace is known to read or write during its execution.
...And 3 more matches
XUL Accessibility
aggregating the text from element subtree if the child node is hidden then it's ignored excepting the case when the element used as label is hidden itself if the child node is text node then its rendered value is appended if the child node is element then if it implements nsidomxullabeledcontrolelement then the value of label property is appended otherwise if it's a label element then then value attribute is appended otherwise append tooltiptext attribute append the accessible value searching specific element in neighbour of the element search inside the elemen...
...t subtree go up through parents (max level is 5) and search inside theirs subtrees if the element is anonymous then search in whole anonymous subtree, here the attribute anonid is used instead of id attribute accessible properties this section describes common rules how accessibility properties are formed for xul elements.
...lowing rules to generate accessible name are applied: check aria-labelledby attribute, name is generated from elements pointed by aria-labelledby attribute <description id="descr1">label1</description> <description id="descr2">label2</description> <textbox aria-labelledby="descr1 descr2" /> if the element implements nsidomxullabeledcontrolelement or nsidomxulselectcontrolitemelement interface then it is used label property if the element doesn't implement nsidomxulselectcontrolelement then label attribute is used if neighbour of the element has label element pointing to this element by the control attribute, if the label element is found then use value attribute or its content.
...And 3 more matches
nsIIOService
if the given port is considered unsafe, then the protocol handler (corresponding to ascheme) will be asked whether it wishes to override the io service's decision to block the port.
...but if the load is coming from a js api (such as xmlhttprequest) or if the load might be coalesced across multiple elements (such as for ) then pass in the document node instead.
... nsichannel newchannelfromuri2( in nsiuri auri, in nsidomnode aloadingnode, in nsiprincipal aloadingprincipal, in nsiprincipal atriggeringprincipal, in unsigned long asecurityflags, in unsigned long acontentpolicytype ); please note, if you provide both a loadingnode and a loadingprincipal, then loadingprincipal must be equal to loadingnode->nodeprincipal().
...And 3 more matches
Xray vision
in cases like this you can waive xray protection, but then you can no longer rely on any properties or functions being, or doing, what you expect.
...components.utils.waivexrays(gbrowser.contentwindow); var transfer = waivedwindow.confirm("transfer all my money?"); // calls the redefined implementation // chrome code var waivedwindow = gbrowser.contentwindow.wrappedjsobject; var transfer = waivedwindow.confirm("transfer all my money?"); // calls the redefined implementation waivers are transitive: so if you waive xray vision for an object, then you automatically waive it for all the object's properties.
...for example, if content code creates a new date object, it will usually be created as a property of a dom object, and then it will be filtered out by the dom xray: // content code // redefine date.getfullyear() date.prototype.getfullyear = function() {return 1000}; var date = new date(); // chrome code // contentwindow is an xray, and date is an expando on contentwindow // so date is filtered out gbrowser.contentwindow.date.getfullyear() // -> typeerror: gbrowser.contentwindow.date is undefined the chrome code w...
...And 3 more matches
Declaring types
for example, to define a new 32-bit integer variable with the value 5: var i = ctypes.int32_t(5); you can then pass a pointer to this value to a c function that requires a pointer to a 32-bit integer, like this: some_c_function(i.address()); declaring new primitive types there are times when you want to create new types that are simply new names for existing primitive types.
...to declare this type, you can simply do: const dword = ctypes.uint32_t; after doing this, dword is a ctype that can then be used to represent 32-bit unsigned integers.
...the format, then, looks like this: [ { field1: type1 }, { field2: type2 }, ...
...And 3 more matches
ctypes.open
this native file can be placed in any folder of an addon and then loaded from js-ctypes.
...therefore, the path has to be converted and then the converted path is used for loading with ctypes.open.
... if the native file is located at chrome://youraddon/content/mysubfolder/mycfunctionsforunix.so then it is converted to a file uri like this: components.utils.import("resource://gre/modules/services.jsm"); var cr = components.classes['@mozilla.org/chrome/chrome-registry;1'].getservice(components.interfaces.nsichromeregistry); var chromeuri_mylib = services.io.newuri('chrome://youraddon/content/mysubfolder/mycfunctionsforunix.so', 'utf-8', null); var localfile_mylib = cr.convertchromeurl(chromeuri_mylib); var jarpath_mylib = localfile_mylib.spec; // "jar:file:///c:/users/vayeate/appdata/roaming/mozilla/firefox/profiles/aecgxse.unnamed%20profile%201/extensions/youraddon@jetpack.xpi!/mysubfolder/mycfunctionsforunix.so" var filepath_mylib = localfilemylib.path; // "file:///c:/users/vayeate/appd...
...And 3 more matches
Debugger - Firefox Developer Tools
the debugger instance does not hold a strong reference to its debuggee globals: if a debuggee global is not otherwise reachable, then it is dropped from the debugger’s set of debuggees.
...if this property’s value is a debugger.object instance belonging to this debugger instance, then its referent is used.
... if the object is not a global object, then the global in whose scope it was allocated is used.
...And 3 more matches
BaseAudioContext.decodeAudioData() - Web APIs
the decoded audiobuffer is resampled to the audiocontext's sampling rate, then passed to a callback or promise.
... example in this section we will first cover the older callback-based system and then the newer promise-based syntax.
... older callback syntax in this example, the getdata() function uses xhr to load an audio track, setting the responsetype of the request to arraybuffer so that it returns an array buffer as its response that we then store in the audiodata variable .
...And 3 more matches
Cache - Web APIs
WebAPICache
use cachestorage.open() to open a specific named cache object and then call any of the cache methods to maintain the cache.
...this is functionally equivalent to calling fetch(), then using put() to add the results to the cache.
... the code then uses cache.match() to see if there's already a matching font in the cache, and if so, returns it.
...And 3 more matches
Intersection Observer API - Web APIs
then, the api only reports changes to visibility which cross these thresholds.
...so if the top level of an <iframe> is reached, the intersection rectangle is clipped to the frame's viewport, then the frame's parent element is the next block recursed through toward the intersection root.
... the resulting rectangle is then updated by intersecting it with the root intersection rectangle.
...And 3 more matches
MediaDevices.getUserMedia() - Web APIs
if the user denies permission, or matching media is not available, then the promise is rejected with notallowederror or notfounderror respectively.
...ices 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().
...if the browser cannot find all media tracks with the specified types that meet the constraints given, then the returned promise is rejected with notfounderror.
...And 3 more matches
MediaStreamAudioSourceNode - Web APIs
track ordering for the purposes of the mediastreamtrackaudiosourcenode interface, the order of the audio tracks on the stream is determined by taking the tracks whose kind is audio, then sorting the tracks by their id property's values, in unicode code point order (essentially, in alphabetical or lexicographical order, for ids which are simple alphanumeric strings).
... the first track, then, is the track whose id comes first when the tracks' ids are all sorted by unicode code point.
... 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.
...And 3 more matches
PublicKeyCredential - Web APIs
it inherits from credential, and was created by the web authentication api extension to the credential management api.
... publickeycredential.response read only secure context an instance of an authenticatorresponse object.
... 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.
...And 3 more matches
RTCPeerConnection.setConfiguration() - Web APIs
the most common use case for this method (and even then, probably not a very common use case) is to replace the set of ice servers to be used.
...if, for example, the rtcpeerconnection() constructor was called with no parameters, you would have to then call setconfiguration() to add ice servers before ice negotiation could begin.
...in this situation, one might call setconfiguration() to switch to new regional ice servers, then initiate an ice restart.
...And 3 more matches
Streams API concepts - Web APIs
teeing even though only a single reader can read a stream at once, it is possible to split a stream into two identical copies, which can then be read by two separate readers.
... in javascript, this is achieved via the readablestream.tee() method — it outputs an array containing two identical copies of the original readable stream, which can then be read independently by two separate readers.
...if you want another writer to start writing to your stream, you typically need to abort it before you then attach another writer to it.
...And 3 more matches
Using writable streams - Web APIs
if not, we suggest that you first read the streams concepts and usage overview and dedicated streams api concepts article, then come back.
...e("hello, world.", writablestream); the sendmessage() definition looks like so: function sendmessage(message, writablestream) { // defaultwriter is of type writablestreamdefaultwriter const defaultwriter = writablestream.getwriter(); const encoder = new textencoder(); const encoded = encoder.encode(message, { stream: true }); encoded.foreach((chunk) => { defaultwriter.ready .then(() => { return defaultwriter.write(chunk); }) .then(() => { console.log("chunk written to sink."); }) .catch((err) => { console.log("chunk error:", err); }); }); // call ready again to ensure that all chunks are written // before closing the writer.
... defaultwriter.ready .then(() => { defaultwriter.close(); }) .then(() => { console.log("all chunks written"); }) .catch((err) => { console.log("stream error:", err); }); } so here we create a writer to write the chunks to the stream using writablestream.getwriter().
...And 3 more matches
Streams API - Web APIs
concepts and usage streaming involves breaking a resource that you want to receive over a network down into small chunks, then processing it bit by bit.
...previously, if we wanted to process a resource of some kind (be it a video, or a text file, etc.), we'd have to download the entire file, wait for it to be deserialized into a suitable format, then process the whole lot after it is fully received.
...for example, the response body returned by a successful fetch request can be exposed as a readablestream, and you can then read it using a reader created with readablestream.getreader(), cancel it with readablestream.cancel(), etc.
...And 3 more matches
WebGLRenderingContext.vertexAttribPointer() - Web APIs
first, we need to bind the webglbuffer we want to use to gl.array_buffer, then, with this method, gl.vertexattribpointer(), we specify in what order the attributes are stored, and what data type they are in.
...you can then provide this same index to gl.vertexattribpointer().
...depending on the graphics card, the index will vary, so you must call gl.getattriblocation() to find out the index, and then provide this index to gl.vertexattribpointer().
...And 3 more matches
Matrix math for the web - Web APIs
trix[ 5], c2r1 = matrix[ 6], c3r1 = matrix[ 7]; let c0r2 = matrix[ 8], c1r2 = matrix[ 9], c2r2 = matrix[10], c3r2 = matrix[11]; let c0r3 = matrix[12], c1r3 = matrix[13], c2r3 = matrix[14], c3r3 = matrix[15]; // now set some simple names for the point let x = point[0]; let y = point[1]; let z = point[2]; let w = point[3]; // multiply the point against each part of the 1st column, then add together let resultx = (x * c0r0) + (y * c0r1) + (z * c0r2) + (w * c0r3); // multiply the point against each part of the 2nd column, then add together let resulty = (x * c1r0) + (y * c1r1) + (z * c1r2) + (w * c1r3); // multiply the point against each part of the 3rd column, then add together let resultz = (x * c2r0) + (y * c2r1) + (z * c2r2) + (w * c2r3); // multiply the point ...
...against each part of the 4th column, then add together let resultw = (x * c3r0) + (y * c3r1) + (z * c3r2) + (w * c3r3); return [resultx, resulty, resultz, resultw]; } now using the function above we can multiply a point by the matrix.
... let x = 50; let y = 100; let z = 0; let translationmatrix = [ 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, x, y, z, 1 ]; place the distances along the three axes in the corresponding positions in the translation matrix, then multiply it by the point or matrix you need to move through 3d space.
...And 3 more matches
WebRTC connectivity - Web APIs
they will then send this offer to peer b using the chosen signal channel.
...they will then send this back to peer a along the signal channel.
...the recipient then responds with an answer, which is a description of their end of the call.
...And 3 more matches
Advanced techniques: Creating and sequencing audio - Web APIs
ple we want to make sure our file has loaded and been decoded into a buffer before we use it, so let's create an async function to allow us to do this: async function getfile(audiocontext, filepath) { const response = await fetch(filepath); const arraybuffer = await response.arraybuffer(); const audiobuffer = await audiocontext.decodeaudiodata(arraybuffer); return audiobuffer; } we can then use the await operator when calling this function, which ensures that we can only run subsequent code when it has finished executing.
... we can now use setupsample() like so: setupsample() .then((sample) => { // sample is our buffered file // ...
...we'll do that in the same sort of way as before: <label for="rate">rate</label> <input name="rate" id="rate" type="range" min="0.1" max="2" value="1" step="0.1" /> let playbackrate = 1; const ratecontrol = document.queryselector('#rate'); ratecontrol.addeventlistener('input', function() { playbackrate = number(this.value); }, false); the final playsample() function we'll then add a line to update the playbackrate property to our playsample() function.
...And 3 more matches
Background audio processing using AudioWorklet - Web APIs
the process of creating an audio processor using javascript, establishing it as an audio worklet processor, and then using that processor within a web audio application is the topic of this article.
... connect the created audioworkletnodes into your audio processing pipeline as you would any other node, then use your audio pipeline as usual.
... then, there can be multiple inputs, so the inputlist is an array of arrays of float32array objects.
...And 3 more matches
WindowOrWorkerGlobalScope.fetch() - Web APIs
you must use then handlers to check for http errors.
...instead, a then() handler must check the response.ok and/or response.status properties.
... examples in our fetch request example (see fetch request live) we create a new request object using the relevant constructor, then fetch it using a fetch() call.
...And 3 more matches
XRReferenceSpace.getOffsetReferenceSpace() - Web APIs
then, when drawing the scene, you can use the offset reference space to not only position objects relative to one another, but to apply the needed transforms to render objects properly based upon the viewer's position.
...these values are added to the position and orientation of the current reference space and then the result is used as the position and orientation of the newly created xrreferencespace.
... xrsession.requestreferencespace("local") .then((refspace) => { xrreferencespace = refspace; xrreferencespace = xrreferencespace.getoffsetreferencespace( new xrrigidtransform(startposition, {x:0, y:0, z:1.0, w: 1.0})); xrsession.requestanimationframe(drawframe); }); in this code, we obtain a local reference space, then use getoffsetreferencespace() to create a new space whose origin is adjusted to a position given by startpositi...
...And 3 more matches
Implementing a Microsoft Active Accessibility (MSAA) Server - Accessibility
if that pointer is non-null, then there is an accessible object for it.
...other assistive technologies use a whitelist, and must list your window classes somewhere in their implementation, and then turn on msaa support when a window of that class receives focus.
...the easiest way to do this is to objid_client object cache its parent's window handle and then implement its get_accparent() method to return the results of accessibleobjectfromwindow(mparenthwnd objid_window, iid_iaccessible, &ptr); not all msaa objects implemented by 3rd party vendors problem: as described above, screen readers tend to look first for window classes they know, such as button, listbox, combobox, msctls_statusbar32, msctls_trackbar32, #32770 (dialog class), systreeview32,...
...And 3 more matches
Backwards Compatibility of Flexbox - CSS: Cascading Style Sheets
if you want to include very old browsers with flexbox support then you can include the vendor prefixes in your css in addition to the unprefixed version.
...the specification defines what happens if you use other layout methods on an element which then becomes a flex item.
...flex containers in the following live example, i have floated two blocks and then set display: flex on the container.
...And 3 more matches
Line-based placement with CSS Grid - CSS: Cascading Style Sheets
if you are working in a right-to-left language then line 1 will be the far right of the grid.
... when we specify our grid area using the grid-area property we first define both start lines block-start and inline-start, then both end lines block-end and inline-end.
...3; grid-column-end: -4; grid-row-start: -1; grid-row-end: -3; } .box3 { grid-column-start: -2; grid-column-end: -3; grid-row-start: -1; grid-row-end: -2; } .box4 { grid-column-start: -2; grid-column-end: -4; grid-row-start: -3; grid-row-end: -4; } stretching an item across the grid being able to address the start and end lines of the grid is useful as you can then stretch an item right across the grid with: .item { grid-column: 1 / -1; } gutters or alleys the css grid specification includes the ability to add gutters between column and row tracks with the grid-column-gap and grid-row-gap properties.
...And 3 more matches
Relationship of grid layout to other layout methods - CSS: Cascading Style Sheets
a common question then is how to make those items line up.
...when you use css grid layout you create a layout and then you place items into it, or you allow the auto-placement rules to place the items into the grid cells according to that strict grid.
...then it is offset in that area using the top and left properties.
...And 3 more matches
Getting Started - Developer guides
then, mozilla, safari, and other browsers followed, implementing an xmlhttprequest object that supported the methods and properties of microsoft's original activex object.
...our javascript will request an html document, test.html, which contains the text "i'm a test." then we'll alert() the contents of the response.
...ntents() { if (httprequest.readystate === xmlhttprequest.done) { if (httprequest.status === 200) { alert(httprequest.responsetext); } else { alert('there was a problem with the request.'); } } } })(); </script> in this example: the user clicks the "make a request" button; the event handler calls the makerequest() function; the request is made and then (onreadystatechange) the execution is passed to alertcontents(); alertcontents() checks if the response was received and ok, then alert()s the contents of the test.html file.
...And 3 more matches
Writing forward-compatible websites - Developer guides
javascript prefix all global variable access in onfoo attributes with “window.” when an event handler content attribute (onclick, onmouseover, and so forth) is used on html element, all name lookup in the attribute first happens on the element itself, then on the element's form if the element is a form control, then on the document, and then on the window (where the global variables you have defined are).
... for example, if you have this markup: <div onclick="alert(ownerdocument)">click me</div> then clicking on the text alerts the ownerdocument of the div.
...if that happens, then suddenly your function stops being called.
...And 3 more matches
<input type="date"> - HTML: Hypertext Markup Language
WebHTMLElementinputdate
it then reads that value back in string and number formats.
...if the value of the max attribute isn't a possible date string in the format yyyy-mm-dd, then the element has no maximum date value.
...if the value of the min attribute isn't a possible date string in the format yyyy-mm-dd, then the element has no minimum date value.
...And 3 more matches
<input type="image"> - HTML: Hypertext Markup Language
WebHTMLElementinputimage
permitted values are: get a url is constructed by starting with the url given by the formaction or action attribute, appending a question mark ("?") character, then appending the form's data, encoded as described by formenctype or the form's enctype attribute.
... this url is then sent to the server using an http get request.
...if the image input has a name attribute, then keep in mind that the specified name is prefixed on every attribute, so if the name is position, then the returned coordinates would be formatted in the url as ?position.x=52&position.y=55.
...And 3 more matches
<video>: The Video Embed element - HTML: Hypertext Markup Language
WebHTMLElementvideo
in other words, it sends the origin: http header without a cookie, x.509 certificate, or performing http basic authentication.
...in other words, it sends the origin: http header with a cookie, a certificate, or performing http basic authentication.
...if this attribute isn't specified, nothing is displayed until the first frame is available, then the first frame is shown as the poster frame.
...And 3 more matches
Authorization - HTTP
the http authorization request header contains the credentials to authenticate a user agent with a server, usually, but not necessarily, after the server has responded with a 401 unauthorized status and the www-authenticate header.
... header type request header forbidden header name no syntax authorization: <type> <credentials> directives <type> authentication type.
...other types: iana registry of authentication schemes authentification for aws servers (aws4-hmac-sha256) <credentials> if the "basic" authentication scheme is used, the credentials are constructed like this: the username and the password are combined with a colon (aladdin:opensesame).
...And 3 more matches
JavaScript modules - JavaScript
these examples demonstrate a simple set of modules that create a <canvas> element on a webpage, and then draw (and report information about) different shapes on the canvas.
...} which we then export: export { square }; over in main.js, we import it like this: import { square } from './modules/square.js'; and then use the class to draw our square: let square1 = new square(mycanvas.ctx, mycanvas.listid, 50, 50, 100, 'blue'); square1.draw(); square1.reportarea(); square1.reportperimeter(); aggregating modules there will be times where you'll want to aggregate modules together.
... import('./modules/mymodule.js') .then((module) => { // do something with the module.
...And 3 more matches
Array.prototype.reduce() - JavaScript
if initialvalue is provided in the call to reduce(), then accumulator will be equal to initialvalue, and currentvalue will be equal to the first value in the array.
... if no initialvalue is provided, then accumulator will be equal to the first value in the array, and currentvalue will be equal to the second.
...if kpresent is true, then // i.
...And 3 more matches
Promise.all() - JavaScript
this returned promise is then resolved/rejected asynchronously (as soon as the stack is empty) when all the promises in the given iterable have resolved, or if any of the promises reject.
... if an empty iterable is passed, then this method returns (synchronously) an already resolved promise.
... var p1 = promise.resolve(3); var p2 = 1337; var p3 = new promise((resolve, reject) => { settimeout(() => { resolve("foo"); }, 100); }); promise.all([p1, p2, p3]).then(values => { console.log(values); // [3, 1337, "foo"] }); if the iterable contains non-promise values, they will be ignored, but still counted in the returned promise array value (if the promise is fulfilled): // this will be counted as if the iterable passed is empty, so it gets fulfilled var p = promise.all([1,2,3]); // this will be counted as if the iterable passed contains only the resolve...
...And 3 more matches
Promise.any() - JavaScript
if no promises in the iterable fulfil (if all of the given promises are rejected), then the returned promise is rejected with an aggregateerror, a new subclass of error that groups together individual errors.
...this returned promise is then resolved/rejected asynchronously (as soon as the stack is empty) when any of the promises in the given iterable resolve, or if all the promises have rejected.
... if an empty iterable is passed, then this method returns (synchronously) an already resolved promise.
...And 3 more matches
Add to Home screen - Progressive web apps (PWAs)
part of this is the simple gesture of accessing an app by tapping its icon on your home screen, and then having it appear neatly in its own window.
... note that the type member in each icon's object specifies the icon's mimetype, so the browser can quickly read what type the icon is, and then ignore it and move to a different icon if it doesn't support it.
...we then cache all the site's assets using the cache api, and serve them from the cache instead of the network using the code in the sw.js file.
...And 3 more matches
dominant-baseline - SVG: Scalable Vector Graphics
if there is no baseline table in the nominal font, or if the baseline table lacks an entry for the desired baseline, then the browser may use heuristics to determine the position of the desired baseline.
...ext> <text dominant-baseline="middle" x="30" y="50">middle</text> <text dominant-baseline="hanging" x="30" y="80">hanging</text> </svg> usage notes value auto | text-bottom | alphabetic | ideographic | middle | central | mathematical | hanging | text-top default value auto animatable yes auto if this property occurs on a <text> element, then the computed value depends on the value of the writing-mode attribute.
... if the writing-mode is horizontal, then the value of the dominant-baseline component is alphabetic.
...And 3 more matches
href - SVG: Scalable Vector Graphics
WebSVGAttributehref
if the url points to multiple target elements, if the given target element is not capable of being a target of the given animation element, or if the given target element is not part of the current document, then the animation element will not affect any target element.
... if the href attribute or the deprecated xlink:href attribute is not provided, then the target element will be the immediate parent element of the current animation element.
... note that if the target element is not part of the current svg document fragment, then whether the target element will be removed or not is defined by the host language.
...And 3 more matches
Paths - SVG: Scalable Vector Graphics
WebSVGTutorialPaths
for instance, since our box is 80×80, the <path> element could have been written as: <path d="m 10 10 h 80 v 80 h -80 z" fill="transparent" stroke="black"/> the path will move to point (10,10) and then move horizontally 80 points to the right, then 80 points down, then 80 points to the left, and then back to the start.
...the bézier function then creates a smooth curve that transfers from the slope established at the beginning of the line, to the slope at the other end.
...the thing to note here is that the curve starts in the direction of the first control point, and then bends so that it arrives along the direction of the second control point.
...And 3 more matches
Interacting with page scripts - Archive of obsolete content
don't use it unless you trust the page, and even then be careful.
...you can then assign that to a property of the target window, and the page script can access it.
...it can then clone objects or export functions as members of that new object.
...And 2 more matches
context-menu - Archive of obsolete content
usage instead of manually adding items when particular contexts occur and then removing them when those contexts go away, you bind items to contexts, and the adding and removing is automatically handled for you.
...when the context menu is first shown and all of the declarative contexts for your item are current) and then remains active until you destroy your context menu item or the page is unloaded.
... if you did not use selectorcontext to decide whether to show the menu item, then this is the actual node clicked.
...And 2 more matches
platform/xpcom - Archive of obsolete content
usage the xpcom module makes it simpler to perform three main tasks: implement xpcom object interfaces implement and register xpcom factories implement and register xpcom services if all you need to do is use xpcom objects that someone else has implemented, then you don't need to use this module.
...if you don't specify a class id, then the factory will generate one.
... create and register the factory var factory = factory({ component: helloworld }); var id = factory.id; // retrieve the factory by class id var wrapper = components.classesbyid[id].createinstance(ci.nsisupports); var helloworld = wrapper.wrappedjsobject; console.log(helloworld.hello()); replacing factories if the factory you create has the same contract id as an existing registered factory, then your factory will replace the existing one.
...And 2 more matches
console - Archive of obsolete content
if you have started firefox for your add-on from the command line with jpm run or jpm test then these messages appear in the command shell you used.
... if the add-on has been installed in firefox, then the messages appear in the browser console.
... if you're developing your add-on using the extension auto-installer, then the add-on is installed in firefox, meaning that messages will appear in the browser console.
...And 2 more matches
Localization - Archive of obsolete content
to reference localized strings from html, add a data-l10n-id attribute to the html tag where you want the localized string to appear, and assign the identifier to it: <html> <body> <h1 data-l10n-id="hello_id"></h1> </body> </html> then you can use this html file to build your interface, for example inside a panel: var button = require("sdk/ui/button/action").actionbutton({ id: "localized-hello", label: "localized hello", icon: "./icon-16.png", onclick: function() { hello.show(); } }); var hello = require("sdk/panel").panel({ height: 75, width: 150, contenturl: require("sdk/self").data.url("my-panel.html") ...
...then it retrieves and returns the localization appropriate for the count you supplied.
... using identifiers if the localization system can't find an entry for a particular identifier using the current locale, then it just returns the identifier itself.
...And 2 more matches
Adding Events and Commands - Archive of obsolete content
the most commonly used event is the onload event, which is used in overlays and other windows to detect when the window has loaded and then run initialization code: // rest of overlay code goes here.
...for a button, it represents the action of the user clicking on it, or focusing it with the keyboard and then pressing the enter key.
...for example: <button label="&xulschoolhello.defaultgreeting.label;" oncommand="xulschoolchrome.browseroverlay.changegreeting(event);" /> then on the javascript code you would have something like this: changegreeting : function(aevent) { // more stuff aevent.target.setattribute("label", somenewgreeting); } the target in this example is the button element, so clicking on it will change its text.
...And 2 more matches
Signing an extension - Archive of obsolete content
in the options window, open the advanced panel, then select the encryption tab.
...then cert8.db, key3.db and secmod.db will be generated.
...id" \ -p $mypassword \ -x -z ~/desktop/myextension/dest/myextension-1.0.xpi \ ~/desktop/myextension/source unset mypassword then a signed xpi file will be generated.
...And 2 more matches
MMgc - Archive of obsolete content
the gc typically is constructed early in your program's initialization, and then passed to operations like operator new for allocating gc objects.
...(the second switch will slow your application down a lot more than the first switch, so you could try the first, then the second.) when a missing write barrier is detected, mmgc will assert and drop you into the debugger, and will print out a message telling you which object contained the missing write barrier, the address of the member variable that needs it, and what object didn't get marked due to the missing write barrier.
...the problem then becomes: how to account for the fact that the mutator is changing the state of the heap between marking increments how much time to spend marking in each increment mark consistency a correct collector never deletes a live object (duh).
...And 2 more matches
Making a Mozilla installation modifiable - Archive of obsolete content
the files are then collected into a series of jar archives, which are just zip files that contain a specially formatted "manifest" file which describes the contents of the archive so mozilla knows what to do with them.
...although mozilla stores the ui files in jar archives, it can also access them in their original, unarchived form, which is useful for the extensions developer because it makes it unnecessary to extract the files from the archive before changing the code and then re-add them to the archive afterwards.
... instead, you only have to extract them once and can then make as many modifications as you like.
...And 2 more matches
In-Depth - Archive of obsolete content
then open the dom inspector (tools->web development->dom inspector).
... click on the inspect icon and then click on the back button in the browser window.
...organizing images to organize all of your icons you can store them all in one image and then tell mozilla which portions to use.
...And 2 more matches
Layout System Overview - Archive of obsolete content
one of the goals of the layout system's design is to create parts of the presentation as they become available, rather than waiting for the entire document to be read, parsed, and then presented.
...if a content element is modified, layout must determine if the change influences the formatting of that or other elements' presentations, and must then reformat, or re-reflow, the impacted elements.
...</p> there is one block that corresponds to the <p> element, and then a number of lines of text that correspond to the text.
...And 2 more matches
generateCRMFRequest() - Archive of obsolete content
crmfobject = crypto.generatecrmfrequest("requesteddn", "regtoken", "authenticator", "escrowauthoritycert", "crmf generation done code", keysize1, "keyparams1", "keygenalg1", ..., keysizen, "keyparamsn", "keygenalgn"); this method will generate a sequence of crmf requests that has n requests.
... "regtoken" a value used to authenticate the user to the ra/ca.
... "authenticator" a value that the user can authenticate with in the future when their private key is not available.
...And 2 more matches
Twitter - Archive of obsolete content
example: jetpack.lib.twitter.statuses.update({ data: { status: "o frabjous day!" }, username: "basic_auth_username", password: "basic_auth_password", success: function () console.log("hey!") }); user authentication you can supply a username and password to methods that require authentication using the second, more advanced call style described above.
...when you call a method that requires authentication -- such as jetpack.lib.twitter.statuses.update() -- without providing a username or password, firefox will prompt the user for them if she is not already authenticated with twitter.
... both methods use http basic authentication.
...And 2 more matches
Binding Attachment and Detachment - Archive of obsolete content
if a binding is attached and it already specifies an inherited binding using the extends attribute, then the base binding at the end of the inheritance chain is the one that will inherit from the most derived binding that is already attached.
...therefore the <destructor> block of the derived binding will execute, and then the base binding's block will execute.
...if a resolution of style on the bound element determines that a new bindingt should be attached, then the following binding chain is detached: s1->s2 ->s3 and the new binding is attached.
...And 2 more matches
Binding Implementations - Archive of obsolete content
if both the attribute form and the element form are used to specify a getter or setter, then the element form is ignored.
...if a property is readonly and a setter is defined, then the setter is ignored.
...if either of these attributes is specified on the property element, then any defined getters and setters are ignored.
...And 2 more matches
XPJS Components Proposal - Archive of obsolete content
when a xpjs component module is first installed - or at autoregistration time - the xpjsmanager will load the .js file into a fresh js environment, let its top level script run to do whatever initialization it wants to do, and then it will call the module's nsregisterself function (passing the filespec of the .js file).
...the xpjsmanager will receive this call from the js code, store the mapping of clsid to .js filespec in the registry for its own use later, and then call the real component manager to do the registration.
...the component manager (and anyone else with a reference to that factory) can then call the factory's createinstance method at will.
...And 2 more matches
Index - Archive of obsolete content
ArchiveMozillaXULIndex
it explains the concept of dom documents, demonstrates a few simple examples of using dom calls to perform basic manipulations on a document, and then demonstrates working with anonymous xbl content using mozilla-specific methods.
...for instance, if the value of ?name is 'jake', then the attribute value will be 'my name is jake'.
...this will return a table of result records which are then used to generate output.
...And 2 more matches
appendNotification - Archive of obsolete content
if "" then an icon appropriate for the priority level is used.
... if the return value from this function is not true, then the notification is closed.
...nts.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 testnotificationbutton2callback(thenotification, buttoninfo, eventtarget) { window.alert("button 2 pressed"); //do not prevent notification from closing: }; function testnotificationcallback(reason) { ...
...And 2 more matches
SeaMonkey - making custom toolbar (SM ver. 1.x) - Archive of obsolete content
if you know how to program in javascript, then you can write your own code that does other things.
... go to the directory where you installed seamonkey, then go to the chrome directory there.
...(if you leave both sections in the file, then your button's appearance will match the classic theme.) save the file.
...And 2 more matches
Using the Editor from XUL - Archive of obsolete content
the <iframe> contents are then editable.
...it does some getting of window.arguments (which is a way callers can pass parameters to new windows -- we use this to get the url to be loaded), then it calls editorstartup(), where the real work happens.
...we get the url to load from the args element, then kick off the load: var url = document.getelementbyid("args").getattribute("value"); editorshell.loadurl(url); loading the document in the <iframe> of course happens asynchronously, so we need to know when we have a document that we can start editing.
...And 2 more matches
Writing Skinnable XUL and CSS - Archive of obsolete content
if you wish for your package to blend in with the other packages, then the skin for your package should inherit information from the global skin in order to reduce the amount of duplication across packages and in order to make the ui as a whole easier to skin.
...if your skin file wishes to inherit the global skin, then it should import the global skin explicitly.
...if it imported the global skin, then when it was overlayed into navigator, it would potentially clash (if the user's current chosen navigator skin were not inheriting from global).
...And 2 more matches
XUL accessibility guidelines - Archive of obsolete content
this behavior is then repeated for the next form field.
...screen readers will then read aloud the label when entering a form field.
...if the user were to tab to the "exceptions..." button they would hear "cookies {pause} exceptions {pause} button." the next tab would read "cookies {pause} keep until {pause} they expire {pause} one of three {pause} combobox." if the screen reader only read the label, then the user would have to guess what the "exceptions" button or the "keep until" combobox was referring to.
...And 2 more matches
Developing cross-browser and cross-platform pages - Archive of obsolete content
it requires from the web author to have knowledge of the capabilities of all current browsers that may visit the page and then to code appropriately for these.
...once "detected", the web author then uses different functions (aka code branching) or points the user to different pages (aka site branching) or web content.
... so if "browser sniffing" is unreliable and difficult, then how do you code safely for different browsers and different browser versions?
...And 2 more matches
Browser Detection and Cross Browser Support - Archive of obsolete content
if (document.all) { // internet explorer 4+ document.write('<link rel="stylesheet" type="text/css" src="style-ie.css">'); } else if (document.layers) { // navigator 4 document.write('<link rel="stylesheet" type="text/css" src="style-nn.css">'); } note how the above example only provided stylesheets for internet explorer and navigator 4 and even then only if the visitor has javascript support turned on in their browser.
...if you have the need to only allow specific versions of browsers to use your secure site, then the user agent string and the related information from the navigator object can be very useful.
...if your pages make use of advanced javascript which manipulates or creates new content using the w3c dom core, then opera 5 and 6 should be considered downlevel as well due to their limited support for the w3c dom.
...And 2 more matches
Requests For Enhancement - Archive of obsolete content
ArchiveWebXFormsRFE
if you have an idea that might improve mozilla's xforms implementation then you should choose one of the following rfe categories and put your request there.
...an additional way to attract the xforms team's attention to an enhancement request you are promoting is to vote for the bug that is related with the feature request (if there is no bug yet then please feel free to file it).
... then you can give a vote by clicking on the 'vote' link on the bug page.
...And 2 more matches
XForms Range Element - Archive of obsolete content
single-node binding special incremental - supported, default value is false start - lower bound of possible values end - upper bound of possible values step - is used for incrementing/decrementing values start/end/step attributes if the value of the bound instance node is outside the range of values specified by the start and end attributes, then the range element receives a xforms-out-of-range event.
... if the bound value then becomes in range, the range element receives a xforms-in-range event.
...if this attribute is omitted, then it is assumed to be 0.
...And 2 more matches
Building up a basic demo with A-Frame - Game development
we'll then build up a demo and run it.
...edit the <a-entity> defining the torus to look like the following: <a-entity geometry=" primitive: torus; radius: 1; radiustubular: 0.1; segmentstubular: 12;" material=" color: #eaeff2; roughness: 0.1; metalness: 0.5;" rotation="10 0 0" position="-3 1 0"> </a-entity> in the new material attribute, we set up the color of the material, then its roughness (a rougher material will scatter reflected light in more directions than a smooth material) and metalness (how metallic the material is).
...add a new <script> element at the end of the <body> element, just after the <a-scene> element, then add the following javascript code inside it: var scene = document.queryselector('a-scene'); var cylinder = document.createelement('a-cylinder'); cylinder.setattribute('color', '#ff9500'); cylinder.setattribute('height', '2'); cylinder.setattribute('radius', '0.75'); cylinder.setattribute('position', '3 1 0'); scene.appendchild(cylinder); we're getting a reference to the scene handler first, then we create the cylinder element as an a-frame entity.
...And 2 more matches
Building up a basic demo with PlayCanvas editor - Game development
click diffuse, then select the colored box next to the color label — it will open a color wheel.
...click on the root folder in the hierarchy panel (to make sure that the new shape appears in the root, and not as a child of the box) then click on the big add entity (plus) button and select cylinder from the dropdown list — it will add a new cylinder shape to the scene.
... click diffuse, then click the color picker — give it an orange color (we used ff9500.) drag and drop the cylindermaterial icon onto the cylinder object on the sceene to apply that color.
...And 2 more matches
Audio for Web games - Game development
for more passive audio auto play, for example background music that starts as soon as a game loads, one trick is to detect any user initiated event and start playback then.
...jumping to, playing, and then pausing that silence will mean we can now use javascript to play that file at arbitrary points.
...if you space your individual sounds by at least 500ms then using the timeupdate event (which fires every 250ms) should be sufficient.
...And 2 more matches
Pseudo-classes and pseudo-elements - Learn web development
if we wanted to make the first paragraph in an article larger and bold, we could add a class to that paragraph and then add css to that class, as shown in the first example below: however, this could be annoying to maintain — what if a new paragraph got added to the top of the document?
... a more valid use of these pseudo-elements is to insert an icon, for example the little arrow added in the example below, which is a visual indicator that we wouldn't want read out by a screenreader: these pseudo-elements are also frequently used to insert an empty string, which can then be styled just like any element on the page.
...we then use css to style it just like any element.
...And 2 more matches
Introduction to CSS layout - Learn web development
starting with a well-structured html document is very important, as you can then work with the way things are laid out by default rather than fighting against it.
...to use flexbox, you apply display: flex to the parent element of the elements you want to lay out; all its direct children then become flex items.
...if there is more space then the items will become wider; if there is less space they will become narrower.
...And 2 more matches
Legacy layout methods - Learn web development
4, 6, or 12), and then fit your content columns inside these imaginary columns.
...for example, you could make the second row look like this: <div class="row"> <div class="col span8">13</div> <div class="col span4">14</div> </div> now you've got a grid system working, you can simply define the rows and the number of columns in each row, then fill each container with your required content.
... 60 / 960 = 0.0625 we then move the decimal point 2 places giving us a percentage of 6.25%.
...And 2 more matches
Positioning - Learn web development
this is very similar to static positioning, except that once the positioned element has taken its place in the normal layout flow, you can then modify its final position, including making it overlap other elements on the page.
... if no ancestor elements have their position property explicitly defined, then by default all ancestor elements will have a static position.
...we give the heading the same width as the content column and then give it a white background and some padding and margin, so the content won't be visible underneath it.
...And 2 more matches
Fundamental text and font styling - Learn web development
once it reaches the end, it goes down to the next line and continues, then the next line, until all the content has been placed in the box.
... note: if the above paragraph leaves you feeling confused, then no matter — go back and review our box model article, to brush up on the box model theory, before carrying on.
...for example, if you had an <article> element in your page, and set its font-size to 1.5 em (which would compute to 24 px final size), and then wanted the paragraphs inside the <article> elements to have a computed font size of 20 px, what em value would you use?
...And 2 more matches
Styling lists - Learn web development
e, paragraph for reference, paragraph for reference, paragraph for reference.</p> <ul> <li>hummus</li> <li>pita</li> <li>green salad</li> <li>halloumi</li> </ul> <h2>recipe (ordered) list</h2> <p>paragraph for reference, paragraph for reference, paragraph for reference, paragraph for reference, paragraph for reference, paragraph for reference.</p> <ol> <li>toast pita, leave to cool, then slice down the edge.</li> <li>fry the halloumi in a shallow, non-stick pan, until browned on both sides.</li> <li>wash and chop the salad.</li> <li>fill pita with salad, hummus, and fried halloumi.</li> </ol> <h2>ingredient description list</h2> <p>paragraph for reference, paragraph for reference, paragraph for reference, paragraph for reference, paragraph for reference, paragraph for ref...
... styled the unordered list like so (on top of what you've already seen above): ul { padding-left: 2rem; list-style-type: none; } ul li { padding-left: 2rem; background-image: url(star.svg); background-position: 0 0; background-size: 1.6rem 1.6rem; background-repeat: no-repeat; } here we've done the following: set the padding-left of the <ul> down from the default 40px to 20px, then set the same amount on the list items.
...the following example: <ol start="4"> <li>toast pita, leave to cool, then slice down the edge.</li> <li>fry the halloumi in a shallow, non-stick pan, until browned on both sides.</li> <li>wash and chop the salad.</li> <li>fill pita with salad, hummus, and fried halloumi.</li> </ol> gives you this output: reversed the reversed attribute will start the list counting down instead of up.
...And 2 more matches
What are browser developer tools? - Learn web development
chrome: open the developer tools and then select the sources tab.
... (opera works the same way.) edge and internet explorer 11: press f12 and then, ctrl + 3, or if the tools are already displayed, click on the debugger tab.
... safari: open the developer tools and then select the debugger tab.
...And 2 more matches
Client-side form validation - Learn web development
if it gets to the server and is then rejected, a noticeable delay is caused by a round trip to the server and then back to the client-side to tell the user to fix their data.
...il" name="mail"> <button>submit</button> </form> and add the following javascript to the page: const email = document.getelementbyid("mail"); email.addeventlistener("input", function (event) { if (email.validity.typemismatch) { email.setcustomvalidity("i am expecting an e-mail address!"); } else { email.setcustomvalidity(""); } }); here we store a reference to the email input, then add an event listener to it that runs the contained code each time the value inside the input is changed.
...sage emailerror.classname = 'error'; // reset the visual state of the message } else { // if there is still an error, show the correct error showerror(); } }); form.addeventlistener('submit', function (event) { // if the email field is valid, we let the form submit if(!email.validity.valid) { // if it isn't, we display an appropriate error message showerror(); // then we prevent the form from being sent by canceling the event event.preventdefault(); } }); function showerror() { if(email.validity.valuemissing) { // if the field is empty // display the following error message.
...And 2 more matches
Sending form data - Learn web development
the server then responds, generally handling the data and loading the url defined by the action attribute, causing a new page load (or a refresh of the existing page, if the action points to the same page).
... select "network" select "all" select "foo.com" in the "name" tab select "headers" you can then get the form data, as shown in the image below.
...to get it working again, we have found that you can load up the mamp app, then choose the menu options mamp > preferences > php, and set "standard version:" to "7.2.x" (x will differ depending on what version you have installed).
...And 2 more matches
Arrays - Learn web development
here we look at why this is useful, then explore how to create an array, retrieve, add, and remove items stored in an array, and more besides.
... if we didn't have arrays, we'd have to store every item in a separate variable, then call the code that does the printing and adding separately for each item.
... accessing and modifying array items you can then access individual items in the array using bracket notation, in the same way that you accessed the letters in a string.
...And 2 more matches
Handling text — strings in JavaScript - Learn web development
creating a string to start with, enter the following lines: let string = 'the revolution will not be televised.'; string; just like we did with numbers, we are declaring a variable, initializing it with a string value, and then returning the value.
...if the browser can't find it, then an error is raised (e.g.
...if your program is raising such errors, then go back and check all your strings to make sure you have no missing quote marks.
...And 2 more matches
What went wrong? Troubleshooting JavaScript - Learn web development
then you can go back and try to fix your example.
... at this point, let's consult the developer console to see if it reports any syntax errors, then try to fix them.
...ath.floor(math.random()) + 1; and the one that generates the random number before each subsequent game is around line 113: randomnumber = math.floor(math.random()) + 1; to check whether these lines are indeed the problem, let's turn to our friend console.log() again — insert the following line directly below each of the above two lines: console.log(randomnumber); save and refresh, then play a few games — you'll see that randomnumber is equal to 1 at each point where it is logged to the console.
...And 2 more matches
Inheritance in JavaScript - Learn web development
then enter it again, replacing teacher with person.
... those available on an object instance, which can either be an object created when a constructor is instantiated like we saw above (so for example var teacher1 = new teacher( name = 'chris' ); and then teacher1.name), or an object literal (let teacher1 = { name = 'chris' } and then teacher1.name).
... it is good then, that the super() operator also accepts arguments for the parent constructor.
...And 2 more matches
Object prototypes - Learn web development
in this example, we have defined a constructor function, like so: function person(first, last, age, gender, interests) { // property and method definitions this.name = { 'first': first, 'last' : last }; this.age = age; this.gender = gender; //...see link in summary above for full definition } we have then created an object instance like this: let person1 = new person('bob', 'smith', 32, 'male', ['music', 'skiing']); if you type "person1." into your javascript console, you should see the browser try to auto-complete this with the member names available on this object: in this list, you will see the members defined on person1's constructor — person() — name, age, gender, interests, bio, and...
...it doesn't, then the browser checks person1's prototype object's prototype object, and it has.
...now try the following: object.prototype you'll see a large number of methods defined on object's prototype property, which are then available on objects that inherit from object, as shown earlier.
...And 2 more matches
Ember app structure and componentization - Learn web development
previous overview: client-side javascript frameworks next in this article we'll get right on with planning out the structure of our todomvc ember app, adding in the html for it, and then breaking that html structure into components.
... objective: to learn how to structure an ember app, and then break that structure into components.
... planning out the layout of the todomvc app in the last article we set up a new ember project, then added and configured our css styles.
...And 2 more matches
Getting started with React - Learn web development
create-react-app uses this name to make a new directory, then creates the necessary files inside it.
... make sure you cd to the place you'd like your app to live on your hard drive, then run the following in your terminal: npx create-react-app moz-todo-react this creates a moz-todo-react directory, and does several things inside it: installs some npm packages essential to the functionality of the app.
... take a moment to change the <p> tag on line 6 so that it reads "hello, world!", then save your file.
...And 2 more matches
Command line crash course - Learn web development
since then, the terminal has remained a constant feature of all operating systems — from desktop machines, to servers tucked away in the cloud (it’s not really a cloud), to microcomputers like the raspberry pi zero, and even to mobile phones.
...this will open up the man page in the terminal’s default text file viewer (for example, less in my terminal), and you should then be able to scroll through the page using the arrow keys, or some similar mechanism.
...if you want to remove a directory that is not empty (and also remove everything it contains), then you can use the -r option (recursive), but this is dangerous.
...And 2 more matches
Adding a new event
define and implement an event class then, you need to define and implement an event class.
...then, copy the additional members which are defined in the class.
...then, the method can have a pointer of jscontext in its argument.
...And 2 more matches
Debugging on Windows
you can click "start" button to run firefox then, already attached in the debugger.
...you can then select the process from dialog opened from "attach to process".
...for each dll, click the "new" button which creates a new entry and then hit the "..." buttons which lets you browse to the dll.
...And 2 more matches
Simple Sunbird build
insert "mac os x install disc 2", then open xcodetools.mpkg.
...(if you get a message saying this application did not install properly then you should see a windows dialog giving you the option to re-install with the 'correct settings'.
... building sunbird and lightning if you've set up you build environment as above, then all you need to do is: echo 'ac_add_options --enable-calendar' >> .mozconfig or just add the ac_add_options --enable-calendar line to your .mozconfig with your favourite editor.
...And 2 more matches
The Firefox codebase: CSS Guidelines
it's generally better to set a class and then specify the styles in css.
... if the answer is no and the value isn't changed at runtime, then you likely don't need a css variable.
... in general, it's good to first think of how some css could be written cleanly without the css variable(s) and then think of how the css variable could improve that css.
...And 2 more matches
Limitations of chrome scripts
however, if an add-on passes a cpow into a platform api, and that platform api then attempts an unsafe operation on it, this will throw an exception.
... nsicontentpolicy without the shim in multiprocess firefox, if you register the nsicontentpolicy in the chrome process then it will never see any attempts to load web content, because they happen in the content process.
...the chrome process then checks the content against the policy supplied by the add-on, and forwards the response back to the child to be enforced.
...And 2 more matches
Process scripts
when you need to run code in the content process in order to access web content, then you should use frame scripts.
...for example, if you call the global frame message manager's loadframescript() function, then the script will be loaded separately into all open tabs.
... this can then cause a problem the frame scripts are interacting with a global service in the content process.
...And 2 more matches
Firefox UI considerations for web developers
if no high-resolution icon is found, a screenshot is taken of the site; this screenshot is then scaled and cropped to fit in the space allotted to the icon.
... the selected image is then presented within the top sites list.
...the screenshot is then drawn in the icon box, which scales and crops the image as needed to fit.
...And 2 more matches
Using the Browser API
MozillaGeckoChromeAPIBrowser APIUsing
to run the demo, the best approach is to clone the github repo locally (or just download it directly if you don't do github), open webide, open the repo as a packaged app, then run it either on a simulator or a real device if you have one.
...for example: function canmovebwd() { browser.getcangoback().then(function(result) { if (result) { back.disabled = false; console.log("it's possible to navigate the history backward."); } else { back.disabled = true; console.log("it's not possible to navigate the history backward."); } }); } implementing the url bar the url bar for our simple browser is a <form> containing a single text <input>.
...we then set the browser iframe's src attribute to equal the value of the url bar, which causes the new url to be loaded in the iframe.
...And 2 more matches
Extending a Protocol
then we will send that same string back to the child process.
... defining windowglobalparent's alloc/deallocpechoparent() open up dom/ipc/windowglobalparent.h and we are going to add two things: at the top, add #include "mozilla/dom/echoparent.h" and then, as part of the windowglobalparent class definition, add the following two public methods: already_addrefed<echoparent> allocpechoparent(); bool deallocpechoparent(pechoparent* aactor); natrually, we will have to do the alloc/dealloc dance for the children too.
... defining windowglobalchild's alloc/deallocpechochild() same as above, now open up dom/ipc/windowglobalchild.h and we are going to add two things: at the top, add #include "mozilla/dom/echochild.h" and then, as part of the windowglobalchild class definition, add the following two public methods: already_addrefed<echochild> allocpechochild(); bool deallocpechochild(pechochild* aactor); super tedious, we know...
...And 2 more matches
CustomizableUI.jsm
this is useful for add-ons that get disabled and then re-enabled (e.g., when they update).
...before customizableui was introduced, then you have to make sure that in case of running on newer browsers, xul overlay does not contain description of the button that you are creating with createwidget() method.
...if any of the ui is changed after calling reset(), then undoreset will be a no-op.
...And 2 more matches
DeferredTask.jsm
if the task is running and the timer is armed, then one last execution from start to finish will happen again, immediately after the current execution terminates; then the returned promise will be resolved.
... if the task is not running and the timer is armed, then the task is started immediately, and the returned promise resolves when the new execution terminates.
... if the timer is already armed when the "finalize" method is called, then the task is executed immediately.
...And 2 more matches
Deferred
note: calling this method with a pending promise as the avalue argument, and then calling it again with another value before the promise is resolved or rejected, will have no effect the second time, as the associated promise is already resolved to the pending promise value as its resolution.
...if this value is a promise, then the associated promise will be resolved to the passed promise, and follow the state as the provided promise (including any future transitions).
... * * @param {anything} value : this value is used to resolve the promise * if the value is a promise then the associated promise assumes the state * of promise passed as value.
...And 2 more matches
Using the viewport meta tag to control layout on mobile browsers
mobiles) render pages in a virtual window or viewport, which is usually wider than the screen, and then shrink the rendered result down so it can all be seen at once.
... users can then pan and zoom to see different areas of the page.
... for example, if a mobile screen has a width of 640px, pages might be rendered with a virtual viewport of 980px, and then it will be shrunk down to fit into the 640px space.
...And 2 more matches
Leak-hunting strategies and tips
strategy for finding leaks when trying to make a particular testcase not leak, i recommend focusing first on the largest object graphs (since these entrain many smaller objects), then on smaller reference-counted object graphs, and then on any remaining individual objects or small object graphs that don't entrain other objects.
...then go on to selecting a folder, then selecting a message, and then other activities one does while reading mail.
... once you've done this, and it doesn't leak much, then try the action under trace-malloc or lsan or valgrind to find the leaks of smaller graphs of objects.
...And 2 more matches
AsyncTestUtils extended framework
if you pass a number greater than 1, then you get a direct reply-chain that long.
... for example, if you pass 3, then 1 <- 2 <- 3 is what the reply chain looks like.
...(we will probably auto-correct that in the future.) if your set definition was {count: 3, age: {days: 7}, age_incr: {days: -1}}, then you would generate messages from 7, 6, and 5 days ago.
...And 2 more matches
NSS API Guidelines
if you're good with tagging your releases, and then checking out (or exporting!) from the tag for your build, this saves you from messing around with specific files revision numbers.
...knowing what to then free does takes discipline not to leak memory, but it simplifies things a lot.
...(frees are allowed.) the arena_destructor_list preprocessor definition, and the code it encloses, are an effort to make the following work together: arenas, letting you allocate stuff and then removing them all at once lazy creation of pure-memory objects from asn.1 blobs, for example use of nsspkixcertificate doesn't drag all the code in for all constituent objects, unless they're actually being used our agressive pointer-tracking facility all these are useful, but they don't combine well.
...And 2 more matches
Scripting Java
how then, do we access classes in java packages?
...make sure your .jar or .class file is on you classpath then you may import them into your javascript application.
...this works just as in java, with the use of the new operator: js> new java.util.date() thu jan 24 16:18:17 est 2002 if we store the new object in a javascript variable, we can then call methods on it: js> f = new java.io.file("test.txt") test.txt js> f.exists() true js> f.getname() test.txt static methods and fields can be accessed from the class object itself: js> java.lang.math.pi 3.141592653589793 js> java.lang.math.cos(0) 1 in javascript, unlike java, the method by itself is an object and can be evaluated as well as being called.
...And 2 more matches
Rhino serialization
they're intended mainly as examples of the use of serialization: $ java org.mozilla.javascript.tools.shell.main js> function f() { return 3; } js> serialize(f, "f.ser") js> quit() $ java org.mozilla.javascript.tools.shell.main js> f = deserialize("f.ser") function f() { return 3;} js> f() 3 js> here we see a simple case of a function being serialized to a file and then read into a new instance of rhino and called.
...we want to be able to serialize a javascript object and then deserialize it into a new scope and have all of the references from the deserialized object to prototypes and parent scopes resolved correctly to refer to objects in the new scope.
...(it might be possible to save the java bytecodes in an array and then load the class upon deserialization, but at best that would eat up a lot of memory for just this feature.) one way around this is to compile the functions using the jsc tool: $ cat f.js function f() { return 3; } $ java -classpath js.jarorg.mozilla.javascript.tools.jsc.main f.js $ cat test2.js loadclass("f"); serialize(f, "f.ser"); g = deserialize("f.ser"); print(g()); $ java -classpath 'js.jar;.
...And 2 more matches
JSPropertyOp
if a jspropertyop or jsstrictpropertyop does nothing and returns true, then property get, set, or add is unaffected.
... each of these callbacks may veto the ongoing property operation by optionally reporting an error or raising an exception and then returning false.
... the operation then fails, and the error is propagated to the caller.
...And 2 more matches
JS_SetProperty
if the lookup found no property with the given name, or if it found that obj inherits such a property from a non-native object, then a new own property is added to obj, as described below.
... otherwise, if obj has an own property with the given name, then the existing property's value is set as described below.
...if the hook succeeds and the property has a stored value, then the value left in v by the addproperty hook becomes the stored value of the property.
...And 2 more matches
TPS Tests
the python test runner will read a test file (in javascript format), setup one or more firefox profiles with the necessary extensions and preferences, then launch firefox and pass the test file to the extension.
...} note that in this example, the foobar@restmail.net account must be registered on stage, otherwise authentication will fail (and the whole test will fail as well.
...sync], [bookmarks.verify, bookmarks_initial], [bookmarks.modify, bookmarks_initial], [bookmarks.verify, bookmarks_after_first_modify], [sync] ]); phase('phase3', [ [sync], [bookmarks.verify, bookmarks_after_first_modify] ]); the effects of this test file will be: firefox is launched with profile1, the tps extension adds the two bookmarks specified in the bookmarks_initial array, then they are synced to the sync server.
...And 2 more matches
Thread Sanitizer
adjusting the build configuration create the build configuration file .mozconfig with the following content in your mozilla-central directory: mk_add_options moz_objdir=@topsrcdir@/objdir-ff-tsan mk_add_options moz_make_flags=-j12 # enable llvm specific code and build workarounds ac_add_options --enable-thread-sanitizer # if clang is already in your $path, then these can simply be: # export cc=clang # export cxx=clang++ export cc="/path/to/clang" export cxx="/path/to/clang++" # llvm-symbolizer displays much more complete backtraces when data races are detected.
... # if it's not already in your $path, then uncomment this next line: #export llvm_symbolizer="/path/to/llvm-symbolizer" # add tsan to our compiler flags export cflags="-fsanitize=thread -fpic -pie" export cxxflags="-fsanitize=thread -fpic -pie" # additionally, we need the tsan flag during linking.
...the build will then be created in a new subdirectory with that name.
...And 2 more matches
Handling Mozilla Security Bugs
the applicant's nomination for membership will then be considered for a period of a few days, during which members of the security bug group can speak out in favor of or against the applicant.
... in practice, if over time a particular person happens to be frequently added to the cc list for security-sensitive bugs, then they would be a good candidate to be invited to join the security bug group.
... (as described previously, once added to the security bug group, that person would then have automatic access to all bugs marked security-sensitive, without having to be explicitly added to the cc list for each one.) note that, although we intend to make it relatively simple for a new person to join the security bug group, and we are not limiting the size of the group to any arbitrary number, we do not want the group to expand without any limits whatsoever.
...And 2 more matches
Creating a Python XPCOM component
then you can import xpcom in any python module (mostly, in your component).
...for example: xpidl.exe -m typelib -w -v -i c:\source\mozilla\obj-i686-pc-mingw32\dist\idl foo.idl xpidl will then create nsipysimple.xpt, which should be placed correctly (e.g., in the 'components' directory).
... def __del__(self): if verbose: print "pysimple: __del__ method called - object is destructing" def write(self): print self.yourname def change(self, newname): self.yourname = newname then register your component; the procedure is the same for any component, but will not work if python components weren't enabled.
...And 2 more matches
How to build an XPCOM component in JavaScript
if you are looking for add-on sdk solution for xpcom javascript components then check out platform/xpcom module first.
... if an interface exists that meets your needs, then you do not need to write an idl, or compile a typelib, and may skip to the next section.
... if you don't find a suitable pre-existing interface, then you must define your own.
...And 2 more matches
An Overview of XPCOM
these pieces, known as components, are then assembled back together at runtime.
...once the class is encapsulated, the only interface the client will see is this: encapsulation of someinterface class someinterface { public: virtual void dosomethinguseful() = 0; }; the implementation can then derive from this class and implement the virtual method.
... clients of this code can then use a factory design pattern to create the object (see factories) and further encapsulate the implementation.
...And 2 more matches
Creating the Component Code
irc irc.mozilla.org /join #developers /msg firebot uuid this command makes the bot generate and return a uuid, which you can then copy into your component source code.
...then xpcom calls registerself, passing parameters that we'll examine here.
...xpcom then loads the component library associated with the cid if it isn't loaded already.
...And 2 more matches
nsIAsyncInputStream
the caller must then wait for the stream to have some data to read.
... if the stream implements nsiasyncinputstream, then the caller can use this interface to request an asynchronous notification when the stream becomes readable or closed (via the asyncwait() method).
...if the stream is already readable or closed when asyncwait is called, then the nsiinputstreamcallback.oninputstreamready() event will be dispatched immediately.
...And 2 more matches
nsIAsyncOutputStream
the caller must then wait for the stream to become writable.
... if the stream implements nsiasyncoutputstream, then the caller can use this interface to request an asynchronous notification when the stream becomes writable or closed (via the asyncwait() method).
...if the stream is already writable or closed when asyncwait is called, then the nsioutputstreamcallback.onoutputstreamready() event will be dispatched immediately.
...And 2 more matches
nsIDocShell
for instance, if the user tries to reload the page, then this is the url that will be reloaded.
... createloadinfo() creates a docshellloadinfo object that you can manipulate and then pass to loaduri().
...if isunload is true, then the document is being unloaded as well.
...And 2 more matches
nsIFaviconService
for a normal page with a favicon we've stored, this will be an annotation uri which will then cause the corresponding favicon data to be loaded from this service.
...for a normal page with a favicon we've stored, this will be an annotation uri which will then cause the corresponding favicon data to be loaded from this service.
...if it then fails again, it will be re-added to the failed cache.
...And 2 more matches
nsIZipWriter
if the operation is performed on the queue then the channel will be opened asynchronously, otherwise the channel must support being opened synchronously.
...if azipentry does not end with "/" then it will be added.
...if saveinzipas was equal to "add this file.txt" then in the zip file it will also be named "add this file.txt" further detail: this example gives futher detail on the importance of forward slashes var filetoaddtozip = fileutils.file('c:\\add this file.txt'); var saveinzipas = 'sub folder/blah.txt'; //do not use backward slash for example do not do: 'sub folder\\blah.txt'.
...And 2 more matches
Using the clipboard
const gclipboardhelper = components.classes["@mozilla.org/widget/clipboardhelper;1"] .getservice(components.interfaces.nsiclipboardhelper); gclipboardhelper.copystring("put me on the clipboard, please."); this example will first create a clipboard helper and then copy a short string to the clipboard.
...then, the function settransferdata is called which copies the data from the string into the transferable.
...we can cut to the clipboard instead of copying by doing a copy and then deleting the original data.
...And 2 more matches
Working with Multiple Versions of Interfaces
we build construct our xpcom component so that first tries to get the interface by it's new iid, then if that fails, attempts plan b.
... and then implement plan b.
... we first dredge out the old interface identifiers from our yea olde firefox 1.5 sdk: static const nsiid iar_iid_old = { 0x663ca4a8, 0xd219, 0x4000, { 0x92, 0x5d, 0xd8, 0xf6, 0x64, 0x06, 0xb6, 0x26 }}; static const nsiid iad_iid_old = {0x8781fc88, 0x355f, 0x4439, { 0x88, 0x1f, 0x65, 0x04, 0xa0, 0xa1, 0xce, 0xb6 }}; then follow the recipe.
...And 2 more matches
Plug-in Basics - Plugins
go to the help menu, and click help and then about plug-ins.
...if it knows how to deal with that mime type (i.e., by loading a plug-in that's been registered for it), then it does so.
...it analyzes the attributes to determine the object type, then determines whether the browser can handle the type.
...And 2 more matches
Debugger.Source - Firefox Developer Tools
if a single piece of source code contains both top-level code and function definitions, perhaps with nested functions, then the debugger.script instances for those all refer to the same debugger.source instance.
... sourcemapurl if the instance refers to javascript source, if this source was produced by a minimizer or translated from some other language, and we know the url of a source map document relating the source positions in this source to the corresponding source positions in the original source, then this property’s value is that url.
... displayurl if the script had a special //# sourceurl comment, as described in the source maps specification, then this property’s value holds the string that was given.
...And 2 more matches
Index - Firefox Developer Tools
we use debugger to set a breakpoint in a function, and then evaluate an expression whenever it is hit.
...it then provides a number of views of the heap that can show you which objects account for memory usage and exactly where in your code you are allocating memory.
...the tool then shows you an overview of the things the browser was doing to render your site over the profile, and a graph of the frame rate over the profile.
...And 2 more matches
Edit Shape Paths in CSS - Firefox Developer Tools
if the shape is clipped by the margin box then the margin box will make up part of this line.
...you can then copy these values back into your stylesheet to create the new, tweaked shape path.
... ellipse() if the value of shape-outside is ellipse() then you are using the ellipse basic shape.
...And 2 more matches
Examine and edit HTML - Firefox Developer Tools
as you type, an autocomplete popup shows any class or id attributes that match the current search term: press up and down to cycle through suggestions, tab to choose the current suggestion, then enter to select the first node with that attribute.
...then you will find strange gaps between elements, even if you haven’t set any margin or padding on them.
...the shadow root is signified by a node named #shadow-root — you can click its expansion arrow to see the full contents of the shadow dom, and then manipulate the contained nodes in a similar way to other part of the page's dom (although with a limited featureset — you can't, for example, drag and drop or delete shadow dom nodes).
...And 2 more matches
Paint Flashing Tool - Firefox Developer Tools
repaints and responsiveness when the browser renders a web page it parses the html and css, determines how to lay it out, and then paints it to actually display the content on the screen.
... whenever an event happens that might change a visible part of the web page then the browser must repaint some portion of the page.
...layers are painted independently and then composited, so a change in the appearance of one layer does not trigger a repaint in any other layers, and when only the relation of two layers changes (in an animation, for example) no repaints are required at all.
...And 2 more matches
The JavaScript input interpreter - Firefox Developer Tools
to enter multi-line expressions, press shift+enter after typing each line, then enter to run all the entered lines.
... if your input does not appear to be complete when you press enter, then the console treats this as shift+enter , enabling you to finish your input.
... for example, if you type: function foo() { and then enter, the console does not immediately execute the input, but behaves as if you had pressed shift+enter , so you can finish entering the function definition.
...And 2 more matches
about:debugging (before Firefox 68) - Firefox Developer Tools
select the web developer menu under the hamburger menu (), then select "service workers".
... before firefox 48 if you change files that are loaded on demand, like content scripts or popups, then changes you make are picked up automatically, and you'll see them the next time the content script is loaded or the popup is shown.
... if you change files that stay loaded the whole time, like background scripts, then you can pick up changes you've made by disabling and then re-enabling the add-on in the about:addons page.
...And 2 more matches
AudioContext.createMediaStreamSource() - Web APIs
the createmediastreamsource() method of the audiocontext interface is used to create a new mediastreamaudiosourcenode object, given a media stream (say, from a mediadevices.getusermedia instance), the audio from which can then be played and manipulated.
... 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.
... next, we feed this source audio into a low pass biquadfilternode (which effectively serves as a bass booster), then a audiodestinationnode.
...And 2 more matches
Cache.add() - Web APIs
WebAPICacheadd
the add() method is functionally equivalent to the following: fetch(url).then(function(response) { if (!response.ok) { throw new typeerror('bad response status'); } return cache.put(url, response); }) for more complex operations, you'll need to use cache.put() directly.
... syntax cache.add(request).then(function() { // request has been added to the cache }); parameters request the request you want to add to the cache.
... the response status is not in the 200 range (i.e., not a successful response.) this occurs if the request does not return successfully, but also if the request is a cross-origin no-cors request (in which case the reported status is always 0.) examples this code block waits for an installevent to fire, then calls waituntil() to handle the install process for the app.
...And 2 more matches
CacheStorage - Web APIs
examples this code snippet is from the mdn sw-test example (see sw-test running live.) this service worker script waits for an installevent to fire, then runs waituntil to handle the install process for the app.
... this consists of calling cachestorage.open to create a new cache, then using cache.addall to add a series of assets to it.
... if not, fetch the request from the network, then also open the cache created in the first block and add a clone of the request to it using cache.put (cache.put(event.request, response.clone()).) if this fails (e.g.
...And 2 more matches
Manipulating video using canvas - Web APIs
then addeventlistener() is called to begin watching the video element so that we obtain notification when the user presses the play button on the video.
... in response to the user beginning playback, this code fetches the width and height of the video, halving each (we will be halving the size of the video when we perform the chroma-keying effect), then calls the timercallback() method to start watching the video and computing the visual effect.
... the timer callback the timer callback is called initially when the video starts playing (when the "play" event occurs), then takes responsibility for establishing itself to be called periodically in order to launch the keying effect for each frame.
...And 2 more matches
Drawing shapes with canvas - Web APIs
the clearrect() function then erases a 60x60 pixel square from the center, and then strokerect() is called to create a rectangular outline 50x50 pixels within the cleared square.
... then you use drawing commands to draw into the path.
...we then use the moveto() method to move the starting point to the desired position.
...And 2 more matches
Transformations - Web APIs
we then draw the second and smaller blue rectangle and save the state.
... a rotate example in this example, we'll use the rotate() method to first rotate a rectangle from the canvas origin and then from the center of the rectangle itself with the help of translate().
...rectangle center // x = x + 0.5 * width // y = y + 0.5 * height ctx.rotate((math.pi / 180) * 25); // rotate ctx.translate(-200, -80); // translate back // draw grey rect ctx.fillstyle = '#4d4e53'; ctx.fillrect(150, 30, 100, 100); } to rotate the rectangle around its own center, we translate the canvas to the center of the rectangle, then rotate the canvas, then translate the canvas back to 0,0, and then draw the rectangle.
...And 2 more matches
DataTransferItem.webkitGetAsEntry() - Web APIs
ner = document.createelement("ul"); container.appendchild(directorycontainer); directoryreader.readentries(function(entries) { entries.foreach(function(entry) { scanfiles(entry, directorycontainer); }); }); } } scanfiles() begins by creating a new <li> element to represent the item being scanned, inserts the name of the item into it as its text content, and then appends it to the container.
...then a new <ul> is created and appended to the parent list; this will contain the directory's contents in the next level down in the list's hierarchy.
... then come the event handlers.
...And 2 more matches
Traversing an HTML table with JavaScript and DOM Interfaces - Web APIs
for each <td> element, we then created the text node with the table cell's text.
... once we have created the <table>, <tbody>, <tr>, and <td> elements, and then the text node, we then append each object to its parent in the opposite order: first, we attach each text node to its parent <td> element using cell.appendchild(celltext); next, we attach each <td> element to its parent <tr> element using row.appendchild(cell); next, we attach each <tr> element to the parent <tbody> element using tblbody.appendchild(row); next, we attach the <tbody> element to its parent <table> element using tbl.appendchild(tblbody); next, we attach the <table> element to its parent <body> element using body.appendchild(tbl); remember this technique.
...first, you create elements from the top down; then you attach the children to the parents from the bottom up.
...And 2 more matches
EffectTiming.fill - Web APIs
WebAPIEffectTimingfill
first we'll define the two objects that describe the keyframes and the timing configuration to use, then we'll actually see the code that triggers and runs the animation when the "animatebutton" button is clicked.
...that means that unless we specify otherwise using the fill property, the instant the animation is started the element will be rotated to the left 90°, and then it will animate smoothly from there.
...notice how before the animation starts running, the box is upright, then upon clicking the "animate!" button, the box is instantly rotated 90° to the left (to correspond to the first keyframe in the animation sequence).
...And 2 more matches
Element.innerHTML - Web APIs
WebAPIElementinnerHTML
this is then wrapped in a <pre> element.
... then the value of innerhtml is changed to this new string.
... if the element whose contents are being replaced is a <template> element, then the <template> element's content attribute is replaced with the new documentfragment created in step 1.
...And 2 more matches
EventTarget.addEventListener() - Web APIs
we then call addeventlistener() to set up a fake event handler, specifying those options, so that the options will be checked if the browser recognizes an object as the third parameter.
... then, we call removeeventlistener() to clean up after ourselves.
... then, when you want to create an actual event listener that uses the options in question, you can do something like this: someelement.addeventlistener("mouseup", handlemouseup, passivesupported ?
...And 2 more matches
FetchEvent.respondWith() - Web APIs
if the response.url value is the empty string, then the fetchevent.request.url is used as the final url.
... this means, for example, if a service worker intercepts a stylesheet or worker script, then the provided response.url will be used to resolve any relative @import or importscripts() subresource loads (bug 1222008).
... there are a few, though, where it does matter: if a fetch() is intercepted, then you can observe the final url on the result's response.url.
...And 2 more matches
Using files from web applications - Web APIs
using the file api, which was added to the dom in html5, it's now possible for web content to ask the user to select local files and then read the contents of those files.
...oppropagation(); e.preventdefault(); } function dragover(e) { e.stoppropagation(); e.preventdefault(); } the real magic happens in the drop() function: function drop(e) { e.stoppropagation(); e.preventdefault(); const dt = e.datatransfer; const files = dt.files; handlefiles(files); } here, we retrieve the datatransfer field from the event, pull the file list out of it, and then pass that to handlefiles().
...after creating the new filereader object, we set up its onload function and then call readasdataurl() to start the read operation in the background.
...And 2 more matches
FileSystemDirectoryReader.readEntries() - Web APIs
ner = document.createelement("ul"); container.appendchild(directorycontainer); directoryreader.readentries(function(entries) { entries.foreach(function(entry) { scanfiles(entry, directorycontainer); }); }); } } scanfiles() begins by creating a new <li> element to represent the item being scanned, inserts the name of the item into it as its text content, and then appends it to the container.
...then a new <ul> is created and appended to the parent list; this will contain the directory's contents in the next level down in the list's hierarchy.
... then come the event handlers.
...And 2 more matches
IDBIndex.openCursor() - Web APIs
if the key range is not specified or is null, then the range includes all the records.
... if at least one record matches the key range, then the result property of the event is set to the new idbcursorwithvalue object; the value of the cursor object is set to a structured clone of the referenced value.
... if no records match the key range then then the result property of the event is set to null.
...And 2 more matches
IDBIndex.openKeyCursor() - Web APIs
if the key range is not specified or is null, then the range includes all the keys.
... if at least one key matches the key range, then the result property of the event is set to the new idbcursor object; the key property of the cursor object is set to the found key and the primarykey property is set to the the corresponding primary key of the found record.
... if no keys match the key range, then then the result property of the event is set to null.
...And 2 more matches
MediaDevices.ondevicechange - Web APIs
example in this example, we create a function called updatedevicelist(), which is called once when mediadevices.getusermedia() successfully obtains a stream, and then is called any time the device list changes.
...; 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 references to the <ul> elements that are used to list the audio and video devices: let audiolist = document.getelementbyid("audiolist"); let videolist = document.getelementbyid("videolist"); getting and dr...
...this method is called any time we want to fetch the current list of media devices and then update the displayed lists of audo and video devices using that information.
...And 2 more matches
Using the MediaStream Recording API - Web APIs
it allows you to record snippets of audio and then play them back.
...first of all, we style the <label> how we want it, making sure that it has enough z-index to always sit above the other elements and therefore be focusable/clickable: label { font-family: 'notocoloremoji'; font-size: 3rem; position: absolute; top: 2px; right: 3px; z-index: 5; cursor: pointer; } then we hide the actual checkbox, because we don't want it cluttering up our ui: input[type=checkbox] { position: absolute; top: -100px; } next, we style the information screen (wrapped in an <aside> element) how we want it, give it fixed position so that it doesn't appear in the layout flow and affect the main ui, transform it to the position we want it to sit in by default, and give it a tra...
...we then use the mediarecorder api to record the stream, and output each recorded snippet into the source of a generated <audio> element so it can be played back.
...And 2 more matches
PaymentRequest.show() - Web APIs
usage notes the most common patterns for using show() involve either the async/await syntax or the use of show().then().catch() to handle the response and any possible rejection.
... then/catch syntax you can also use the older promise-based approach to work with payments, using the then() and catch() functions on the promise returned by show(): function processspayment() { const payrequest = new paymentrequest(methoddata, details, options); payrequest.onshippingaddresschange = ev => ev.updatewith(checkaddress(payrequest)); payrequest.onshippingoptionchange = ev => ev.upd...
...atewith(checkshipping(payrequest)); payrequest.show() .then(response => validateresponse(response)) .catch(err => handleerror(err)); } this is functionally equivalent to the processpayment() method using the await syntax.
...And 2 more matches
PublicKeyCredential.response - Web APIs
the response read-only property of the publickeycredential interface is an authenticatorresponse object which is sent from the authenticator to the user agent for the creation/fetching of credentials.
... an authenticatorresponse is either: an authenticatorattestationresponse (when the publickeycredential is created via credentialscontainer.create()) an authenticatorassertionresponse (when the publickeycredential is obtained via credentialscontainer.get()).
... syntax response = publickeycredential.response value an authenticatorresponse object containing the data a relying party's script will receive and which should be sent to the relying party's server in order to validate the demand for creation or fetching.
...And 2 more matches
PublicKeyCredentialCreationOptions.attestation - Web APIs
this is a string whose value indicates the preference regarding the attestation transport, between the authenticator, the client and the relying party.
... the attestation is a mean for the relying party to verify the origin of the authenticator with an attestation certificate authority.
... "indirect": the client may change the assertion from the authenticator (for instance, using an anonymization ca).
...And 2 more matches
PublicKeyCredentialCreationOptions.challenge - Web APIs
this is randomly generated then sent from the relying party's server.
... this value (among other client data) will be signed by the authenticator, using its private key, and must be sent back for verification to the server as part of authenticatorattestationresponse.attestationobject.
... note: when the credential is retrieved with a navigator.credentials.get() call, the signature of the challenge is contained in authenticatorassertionresponse.signature.
...And 2 more matches
PublicKeyCredentialRequestOptions.challenge - Web APIs
this is randomly generated then sent from the relying party's server.
... this value (among other client data) will be signed by the authenticator's private key and produce authenticatorassertionresponse.signature which should be sent back to the server as part of the response.
... note: when the credential is created with a navigator.credentials.create() call, the signature of the challenge is contained within authenticatorattestationresponse.attestationobject.
...And 2 more matches
PublicKeyCredentialRequestOptions.userVerification - Web APIs
this is a string which indicates how the user verification should be part of the authentication process.
... note: an analogous option exists for the creation operation (navigators.credentials.create()), see the userverification property of publickeycredentialcreationoptions.authenticatorselection.
... syntax userverification = publickeycredentialrequestoptions.userverification value a string qualifying how the user verification should be part of the authentication process.
...And 2 more matches
PublicKeyCredentialRequestOptions - Web APIs
the publickeycredentialrequestoptions dictionary of the web authentication api holds the options passed to navigator.credentials.get() in order to fetch a given publickeycredential.
...this value will be signed by the authenticator and the signature will be sent back as part of authenticatorassertionresponse.signature.
... publickeycredentialrequestoptions.userverification optional a string qualifying how the user verification should be part of the authentication process.
...And 2 more matches
PushManager.subscribe() - Web APIs
syntax ​pushmanager.subscribe(options).then(function(pushsubscription) { ...
... applicationserverkey: a base64-encoded domstring or arraybuffer containing an ecdsa p-256 public key that the push server will use to authenticate your application server.
... if specified, all messages from your application server must use the vapid authentication scheme, and include a jwt signed with the corresponding private key.
...And 2 more matches
RTCPeerConnection.setRemoteDescription() - Web APIs
only then does the agreed-upon configuration take effect.
...this lets you simplify code such as the following: mypeerconnection.setremotedescription(new rtcsessiondescription(description)) .then(function () { return createmystream(); }) to simply be: mypeerconnection.setremotedescription(description) .then(function () { return createmystream(); }) using async/await syntax, you can further simplify this to: await mypeerconnection.setremotedescription(description); createmystream(); since it's unnecessary, the rtcsessiondescription() constructor is deprecated.
... on the other hand, if we're in the middle of an ongoing negotiation and an offer is passed into setremotedescription(), the ice agent automatically begins an ice rollback in order to return the connection to a stable signaling state, then, once the rollback is completed, sets the remote description to the specified offer.
...And 2 more matches
RTCRemoteOutboundRtpStreamStats.localId - Web APIs
example in this example, we have a pair of functions: the first, networkteststart(), captures an initial report, and the second, networkteststop(), captures a second report, then uses the two reports to output some information about the network conditions...
... networkteststop() the networkteststop() function obtains a second report, endreport, then uses the two reports together to determine several...
...it takes as input the rtcpeerconnection being tested, calls getstats() to get a new rtcstatsreport with current statistics, then computes the results it's looking for, outputting those results as appropriate to the user by appending appropriate html to the contents of the <div> element whose class is stats-box.
...And 2 more matches
ServiceWorkerContainer.register() - Web APIs
syntax serviceworkercontainer.register(scripturl, options) .then(function(serviceworkerregistration) { ...
... 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...
... alternatively, if this code were included in a page at example.com/product/description.html, with the javascript file residing at example.com/product/sw.js, then the service worker would only apply to resources under example.com/product.
...And 2 more matches
SubtleCrypto.encrypt() - Web APIs
the web crypto api supports three different aes modes: ctr (counter mode) cbc (cipher block chaining) gcm (galois/counter mode) it's strongly recommended to use authenticated encryption, which includes checks that the ciphertext has not been modified by an attacker.
... authentication helps protect against chosen-ciphertext attacks, in which an attacker can ask the system to decrypt arbitrary messages, and use the result to deduce information about the secret key.
... while it's possible to add authentication to ctr and cbc modes, they do not provide it by default and when implementing it manually one can easily make minor, but serious mistakes.
...And 2 more matches
Lighting in WebGL - Web APIs
then we update the vertex shader to adjust the color of each vertex, taking into account the ambient lighting as well as the effect of the directional lighting given the angle at which it's striking the face.
... return { position: positionbuffer, normal: normalbuffer, texturecoord: texturecoordbuffer, indices: indexbuffer, }; this should look pretty familiar by now; we create a new buffer, bind it to be the buffer we're working with, then send along our array of vertex normals into the buffer by calling bufferdata().
... then we add the code to drawscene() to bind the normals array to a shader attribute so the shader code can get access to it: // tell webgl how to pull out the normals from // the normal buffer into the vertexnormal attribute.
...And 2 more matches
Lighting a WebXR setting - Web APIs
the reflected ray, then, departs along at that angle off the normal.
...this light reaches every surface in the scene at the same intensity from every direction, and is then reflected equally in every direction.
... for each polygon in the scene, the vertex shader program determines the vertices' colors, and then the fragment shader generates each pixel in the polygon by combining the appropriate texel from the assigned texture, any color tint or effect, and other visual data.
...And 2 more matches
Starting up and shutting down a WebXR session - Web APIs
ebxrpolyfill(); tempxr = navigator.xr; break; case "no": default: tempxr = navigator.xr; break; } return tempxr; } const xr = getxr("no"); // get the native xrsystem object const xr = getxr("yes"); // always returns an xrsystem from the polyfill const xr = getxr("if-needed"); // use the polyfill only if navigator.xr missing the returned xrsystem object can then be used according to the documentation provided here on mdn.
...fundamentally, that looks like this: xr.requestsession("immersive-vr").then((session) => { xrsession = session; /* continue to set up the session */ }); note the parameter passed into requestsession() in this code snippet: immersive-vr.
...you can then proceed to prepare the session for use and begin your animations.
...And 2 more matches
XRView.transform - Web APIs
WebAPIXRViewtransform
with the transform, you can then position the view as a camera within the 3d scene.
...you can then use the inverse of this matrix to transform the objects in your scene to adjust their placement and orientation to simulate the viewer's movement through space.
... then we iterate over each xrview found in the xrviewerpose's list of views.
...And 2 more matches
XRWebGLLayer.getNativeFramebufferScaleFactor() static method - Web APIs
if the scaling factor is 1.0, then the frame buffer pixels and the native display pixels are the same size.
... if the scaling factor is greater than zero, then the frame buffer is smaller than the diplay's native dimensions, resulting in the output being up-scaled for display to the screen after rendering into the frame buffer.
... while rendering a frame for this scene, we get the viewport for the view and apply it to webgl, then render the scene.
...And 2 more matches
ARIA: listbox role - Accessibility
if that's an option element, then that would be the id of the most recently interacted with option, regardless of whether that option has an aria-selected value of true or not.
... if the id does not refer to a dom descendant of the listbox, then that id must be included among the ids in the aria-owns attrubute.
... if there's a visible label, then aria-labelledby should be used instead to refer to that label.
...And 2 more matches
Architecture - Accessibility
if it has text siblings, then it gets exposed as the unicode char for an embedded object, which is '\xfffc' within the parent nshypertextaccessible.
... how does an at deal with text (a) to get the embedded object for an embedded object char: linkindex = iahypertext::getlinkindex(offset) iahyperlink*object = iahypertext::getlink(linkindex) iaccessible* accessible = qi/qs(object) (b) to get the offset in the parent text for a given embedded object: qi/qa to iahyperlink if not successful, then it is not embedded in text, so it's position in parent should be determined just by ia2::indexinparent, which will return its child offset within the parent.
...in firefox, the results of getendindex will always be the startindex + 1, because links are always just represented by a single embedded object character (c) to get the next char fom a given offset in an accessible text: if current char is 0 (end of string), then we are on a hard line break: get next node (typical depth first search), and set the current offset = 0 iatext::ch = getcharacteratoffset(++offset); if ch == embedded object char (0xfffc) then get object for that offset (see a above), then set the current offset to -1, and go to step 2 if ch == 0 then we must determine whether we're on a hard line break: if the current accessible...
...And 2 more matches
Cognitive accessibility - Accessibility
n-language standards; focusing attention on important content; minimizing distractions, such as unnecessary content or advertisements; providing consistent web page layout and navigation; incorporating familiar elements, such as underlined links that are blue when not visited and purple when visited; dividing processes into logical, essential steps with progress indicators; making website authentication as easy as possible without compromising security; and making forms easy to complete, such as with clear error messages and simple error recovery.
...for example, being able to extend the expiration time on an application requiring an authentication code sent to a mobile device via text message helps with the following scenarios: people with attention or anxiety disorders.
... ensure that people can continue an activity without loss of data after re-authenticating an expired session, for example, saving the state of a questionnaire.
...And 2 more matches
Accessibility documentation index - Accessibility
found 105 pages: # page tags and summary 1 accessibility accessibility, landing accessibility (often abbreviated to a11y—as in "a" then 11 characters then "y") in web development means enabling as many people as possible to use web sites, even when those people's abilities are limited in some way.
...when this role is added to an element, the browser will send out an accessible alert event to assistive technology products which can then notify the user about it.
...if the user is expected to close the alert, then the alertdialog role should be used instead.
...And 2 more matches
Keyboard - Accessibility
focusable elements should have interactive semantics if an element can be focused using the keyboard, then it should be interactive; that is, the user should be able to do something to it and produce a change of some kind (for example, activating a link or changing an option).
...a positive value puts the element ahead of those in the default ordering; elements with positive values are focused in the order of their tabindex values (1, then 2, then 3, etc.).
... see also tabindex global html attribute understanding focus order don't use tabindex greater than 0 clickable elements must be focusable and should have interactive semantics if an element can be clicked with a pointing device, such as a mouse, then it should also be focusable using the keyboard, and the user should be able to do something by interacting with it.
...And 2 more matches
CSS Box Alignment - CSS: Cascading Style Sheets
if you initially learned flexbox then you may consider these properties to be part of the flexbox specification, and some of the properties are indeed listed in level 1 of flexbox.
... fallback alignment if you set an alignment that cannot be fulfilled, then the fallback alignment will come into play and deal with the available space.
...if you were using arabic, a right to left language, then the same value of start would result in the items moving to the right, as sentences in arabic start on the right-hand side of the page.
...And 2 more matches
Block and inline layout in normal flow - CSS: Cascading Style Sheets
in a vertical writing mode then would lay out horizontally.
... if we set margins on the paragraph element to 0 then the borders will touch.
...it then has an inner display type which changes the way its children behave.
...And 2 more matches
CSS grids, logical values, and writing modes - CSS: Cascading Style Sheets
if you want to dig into writing modes further, however, then i would recommend that you read jen simmons excellent article on css writing modes.
...it then moves onto the next line, creating a new row track, and fills in more items: * {box-sizing: border-box;} .wrapper { border: 2px solid #f76707; border-radius: 5px; background-color: #fff4e6; } .wrapper > div { border: 2px solid #ffa94d; border-radius: 5px; background-color: #ffd8a8; padding: 1em; color: #d9480f; } .wrapper { display: grid; grid-template-...
...items will, by default, place themselves along the inline axis then move onto a new row.
...And 2 more matches
Subgrid - CSS: Cascading Style Sheets
introduction to subgrid when you add display: grid to a grid container, only the direct children become grid items and can then be placed on the grid that you have created.
...i then make this grid item into a grid, giving it column tracks that are a subgrid and defining rows as normal.
...i can then place .subitem on this grid.
...And 2 more matches
<easing-function> - CSS: Cascading Style Sheets
this causes the animation to go farther than the final state, and then return.
... keywords for common cubic-bezier easing functions ease the animation starts slowly, accelerates sharply, and then slows gradually towards the end.
... ease-in the animation starts slowly, and then progressively speeds up until the end, at which point it stops abruptly.
...And 2 more matches
font-size - CSS: Cascading Style Sheets
WebCSSfont-size
if you haven't set the font size anywhere on the page, then it is the browser default, which is often 16px.
...if you set a font-size of 20px on the body element, then 1em = 20px and 2em = 40px.
...if the font-size you want is 12px, then you should specify 0.75em (because 12/16 = 0.75).
...And 2 more matches
<input type="checkbox"> - HTML: Hypertext Markup Language
WebHTMLElementinputcheckbox
if it is, then the value of the checkbox's value attribute is reported as the input's value.
... essentially, then, the indeterminate attribute adds a third possible state to the checkbox: "i don't know." in this state, the browser may draw the checkbox in grey or with a different mark inside the checkbox.
...if they are completely unrelated, then you can just deal with them all separately, as shown above.
...And 2 more matches
<select>: The HTML Select element - HTML: Hypertext Markup Language
WebHTMLElementselect
if this attribute is not specified, the control inherits its setting from the containing element, for example <fieldset>; if there is no containing element with the disabled attribute set, then the control is enabled.
...if it is not specified, then only one option can be selected at a time.
... usage notes selecting multiple options on a desktop computer, there are a number of ways to select multiple options in a <select> element with a multiple attribute: mouse users can hold the ctrl, command, or shift keys (depending on what makes sense for your operating system) and then click multiple options to select/deselect them.
...And 2 more matches
Browser detection using the user agent - HTTP
graceful degradation this is a top-down approach in which you build the best possible site using all the features you want, then tweak it to make it work on older browsers.
...then, default back to checking the user agent screen only if (!("maxtouchpoints" in navigator)) { /*code here*/}.
...if more people visit the webpage to see the cats, then it might be a good idea to put all the cats higher in the source code than the dogs so that more people can find what they are looking for faster on smaller screens where the content collapses down to one column.
...And 2 more matches
Cross-Origin Resource Sharing (CORS) - HTTP
WebHTTPCORS
additionally, for http request methods that can cause side-effects on server data (in particular, http methods other than get, or post with certain mime types), the specification mandates that browsers "preflight" the request, soliciting supported methods from the server with the http options request method, and then, upon "approval" from the server, sending the actual request.
... servers can also inform clients whether "credentials" (such as cookies and http authentication) should be sent with requests.
... until browsers catch up with the spec, you may be able to work around this limitation by doing one or both of the following: change the server-side behavior to avoid the preflight and/or to avoid the redirect change the request such that it is a simple request that doesn’t cause a preflight if that's not possible, then another way is to: make a simple request (using response.url for the fetch api, or xmlhttprequest.responseurl) to determine what url the real preflighted request would end up at.
...And 2 more matches
HTTP caching - HTTP
WebHTTPCaching
this can be useful if pages with http authentication, or response status codes that aren't normally cacheable, should now be cached.
...if a "cache-control: max-age=n" header is specified, then the freshness lifetime is equal to n.
...if an expires header exists, then its value minus the value of the date header determines the freshness lifetime.
...And 2 more matches
Proxy-Authorization - HTTP
the http proxy-authorization request header contains the credentials to authenticate a user agent to a proxy server, usually after the server has responded with a 407 proxy authentication required status and the proxy-authenticate header.
... header type request header forbidden header name no syntax proxy-authorization: <type> <credentials> directives <type> authentication type.
...see also the iana registry of authentication schemes.
...And 2 more matches
Numbers and dates - JavaScript
these methods use integers to represent these values as follows: seconds and minutes: 0 to 59 hours: 0 to 23 day: 0 (sunday) to 6 (saturday) date: 1 to 31 (day of the month) months: 0 (january) to 11 (december) year: years since 1900 for example, suppose you define the following date: var xmas95 = new date('december 25, 1995'); then xmas95.getmonth() returns 11, and xmas95.getfullyear() returns 1995.
...it then creates a date object named endyear and sets the year to the current year.
... then, using the number of milliseconds per day, it computes the number of days between today and endyear, using gettime and rounding to a whole number of days.
...And 2 more matches
Array.prototype.indexOf() - JavaScript
if the provided index is 0, then the whole array will be searched.
... } else // all else for (; i !== len; ++i) if (that[i] === member) return i return -1 // if the value was not found, then return -1 } })(object, math.max, math.min) however, if you are more interested in all the little technical bits defined by the ecma standard, and are less concerned about performance or conciseness, then you may find this more descriptive polyfill to be more useful.
...if n >= 0, then let k be n.
...And 2 more matches
Object.create() - JavaScript
then again, the actual iteration order is not guaranteed no matter what the order members are added.
... adding the missing object-method directly from the standard-object does not work: ocn = object.create( null ); // create "null" object (same as before) ocn.tostring = object.tostring; // since new object lacks method then try assigning it directly from standard-object > ocn.tostring // shows "tostring() { [native code] }" -- missing method seems to be there now > ocn.tostring == object.tostring // shows "true" -- method seems to be same as the standard object-method > ocn.tostring() // error: function.prototype.tostring requires that 'this' be a function adding the missing object-method directly to new objec...
... (which is really the cause of all these problems) and one cannot be directly added: ocn = object.create( null ); // create "null" object (same as before) ocn.prototype.tostring = object.tostring; // error: cannot set property 'tostring' of undefined ocn.prototype = {}; // try to create a prototype ocn.prototype.tostring = object.tostring; // since new object lacks method then try assigning it from standard-object > ocn.tostring() // error: ocn.tostring is not a function adding the missing object-method by using the standard-object as new object's prototype does not work either: ocn = object.create( null ); // create "null" object (same as before) object.setprototypeof(ocn, object); // set new object's prototype to the standard-object > ocn.tostring() /...
...And 2 more matches
Promise.prototype.finally() - JavaScript
this helps to avoid duplicating code in both the promise's then() and catch() handlers.
... the finally() method is very similar to calling .then(onfinally, onfinally) however there are a couple of differences: when creating a function inline, you can pass it once, instead of being forced to either declare it twice, or create a variable for it a finally callback will not receive any argument, since there's no reliable means of determining if the promise was fulfilled or rejected.
...so for example: unlike promise.resolve(2).then(() => {}, () => {}) (which will be resolved with undefined), promise.resolve(2).finally(() => {}) will be resolved with 2.
...And 2 more matches
WebAssembly.instantiate() - JavaScript
we then call an exported webassembly function that is exported by the instance.
... var importobject = { imports: { imported_func: function(arg) { console.log(arg); } } }; fetch('simple.wasm').then(response => response.arraybuffer() ).then(bytes => webassembly.instantiate(bytes, importobject) ).then(result => result.instance.exports.exported_func() ); note: you can also find this example at index.html on github (view it live also).
... second overload example the following example (see our index-compile.html demo on github, and view it live also) compiles the loaded simple.wasm byte code using the webassembly.compilestreaming() method and then sends it to a worker using postmessage().
...And 2 more matches
Progressive web app structure - Progressive web apps (PWAs)
mixing ssr with csr can lead to the best results — you can render a website on the server, cache its contents, and then update the rendering on the client-side as and when needed.
... app shell the app shell concept is concerned with loading a minimal user interface as soon as possible and then caching it so it is available offline for subsequent visits before then loading all the contents of the app.
...tent').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(); } }); }); the last block creates notifications that display a randomly-selected item from the games list: function randomnotification() { var randomitem = math.floor(math.random()*games.length); var notiftitle = games[randomitem].name; var notifbody = 'created by '+games[randomitem].a...
...And 2 more matches
Caching compiled WebAssembly modules - WebAssembly
any subsequent call to instantiatecachedurl() will then clear out the entire cache, allowing you to avoid using out-of-date modules.
...we start by trying to open a database, then see if we already have a compiled module with the key url stored in the given db: return opendatabase().then(db => { return lookupindatabase(db).then(module => { if we do, we instantiate it with the given import object: console.log(`found ${url} in wasm cache`); return webassembly.instantiate(module, importobject); }, if not, we compile it from scratch and then store the...
... compiled module in the database with a key of url, for next time we want to use it: errmsg => { console.log(errmsg); return webassembly.instantiatestreaming(fetch(url)).then(results => { storeindatabase(db, results.module); return results.instance; }); }) }, note: it is for this kind of usage that webassembly.instantiate() returns both a module and an instance: the module represents the compiled code and can be stored/retrieved in idb or shared between workers via postmessage(); the instance is stateful and contains the callable javascript functions, therefore it cannot be stored/shared.
...And 2 more matches
Exported WebAssembly functions - WebAssembly
an example let's look at an example to clear things up (you can find this on github as table-set.html; see it running live also, and check out the wasm text representation): var othertable = new webassembly.table({ element: "anyfunc", initial: 2 }); webassembly.instantiatestreaming(fetch('table.wasm')) .then(obj => { var tbl = obj.instance.exports.tbl; console.log(tbl.get(0)()); // 13 console.log(tbl.get(1)()); // 42 othertable.set(0,tbl.get(0)); othertable.set(1,tbl.get(1)); console.log(othertable.get(0)()); console.log(othertable.get(1)()); }); here we create a table (othertable) from javascript using the webassembly.table constructor, then we load table.wasm into our page using th...
... we then get the function exported from the module, retrieve the functions it references via tbl.get() and log the result of invoking each one to the console.
... to prove this, we then retrieve these references back from othertable and print their results to console too, which gives the same results.
...And 2 more matches
Communicating With Other Scripts - Archive of obsolete content
for example: if an add-on creates a single panel object and loads several content scripts into the panel at the same time, then they can interact with each other.
... if an add-on creates a single page-mod object and loads several content scripts into the page mod, then only content scripts associated with the same page can interact with each other: if two different matching pages are loaded, content scripts attached to page a cannot interact with those attached to page b.
...</html> finally, the content script "listen.js" uses window.addeventlistener() to listen for messages from the page script: // listen.js window.addeventlistener('message', function(event) { console.log(event.data); // message from page script console.log(event.origin); }, false); using postmessage() before firefox 31 if your add-on is running in a version of firefox before firefox 31, then your content script can't access the postmessage() or addeventlistener() apis using window, but must access them using document.defaultview instead.
... first, "main.js" will create a page-mod that will attach "content-script.js" to the target web page, and will then load the target web page: var tabs = require("sdk/tabs"); var mod = require("sdk/page-mod"); var self = require("sdk/self"); var pageurl = self.data.url("page.html") var pagemod = mod.pagemod({ include: pageurl, contentscriptfile: self.data.url("content-script.js"), contentscriptwhen: "ready" }) tabs.open(pageurl); the target web page "page.html" includes a button and a page script: ...
XUL Migration Guide - Archive of obsolete content
if your add-on needs a lot of help from third party packages, low-level apis, or xpcom, then the cost of migrating is high, and may not be worth it at this point.
... if your add-on only needs a little help from those techniques, and can accomplish most of what it needs using the supported apis, then it might still be worth migrating: we'll add more supported apis in future releases to meet important use cases.
...for example, if you have only imported the notifications module, then even if a malicious web page manages to inject code into your add-on, it can't use the sdk's file module to access the user's data.
... finally, if none of the above techniques work for you, you can use the require("chrome") statement to get direct access to the components object, which you can then use to load and access any xpcom object.
ui/sidebar - Archive of obsolete content
from firefox 33 onwards you can pass a browserwindow into these methods, and they will then operate on the specified window.
...if it is omitted, then the sidebar will be shown in the currently active window.
...if it is omitted, then the sidebar will be hidden for the currently active window.
... if you listen to attach, and in the listener take a reference to the worker object that's passed into it, so you can send it messages later on, then you should probably listen to detach, and in its handler, remove your reference to the worker.
Developing for Firefox Mobile - Archive of obsolete content
then: install the nightly build of the native version of firefox mobile on the device.
...then type: adb devices you should see some output like: list of devices attached 51800f220f01564 device (the long hex string will be different.) if you do, then adb has found your device and you can get started.
...then execute jpm-mobile run with some extra options: jpm-mobile run --adb /path/to/adb in the command shell, you should see something like: launching mobile application with intent name org.mozilla.fennec pushing the addon to your device starting: intent { act=android.activity.main cmp=org.mozilla.fennec/.app (has extras) } --------- beginning of /dev/log/main --------- beginning of /dev/log/system could not read chrome manifest 'file:///data/data/org.mozilla.fennec/chrome.manifest'.
...the easiest way is probably to copy the signed xpi somewhere on the device: adb push my-addon.xpi /mnt/sdcard/ then open firefox mobile and type this into the address bar: file:///mnt/sdcard/my-addon.xpi the browser should open the xpi and ask if you want to install it.
Examples and demos from articles - Archive of obsolete content
in such a condition is difficult and unnatural to keep track of all events started and then to stop them when appropriate through the cleartimeout() function.
...in different objects and then to create a constructor for such class of objects in order to standardize and simplify the instantiation of them.
...in such a condition is difficult and unnatural to keep track of all events started and then to stop them when appropriate through the cleartimeout() function.
...in different objects and then to create a constructor for such class of objects in order to standardize and simplify the instantiation of them.
Appendix C: Avoiding using eval in Add-ons - Archive of obsolete content
alternative: replace + function.apply() you may replace the original function with a new function, keeping a reference to the original function which you then call from the new one.
...if you want to disable your overrides again, then use a flag indicating that, or similar.
...because the object is frozen or sealed, then creating a proxy around the object might be a viable approach.
... document.getelementbyid("mymenu").docommand(); alternative: just hard-code what should happen if you know that the current version of the application will call { executesomething(); executesomethingelse();} then just do the same in your code.
Connecting to Remote Content - Archive of obsolete content
you can then use this object like any other javascript objects in your code.
... filter a complex xml file and generate a simpler xml document with only the data you need, so then you can use regular dom functions to read it.
...you can still use rdf as an intermediate format, though, and then use templates to generate xul and display the data.
...you can use it to view or even modify the data in a request, and then inspect the result.
Custom XUL Elements with XBL - Archive of obsolete content
so, if you have this: <xshelloperson name="pete" greeting="good morning" image="" />, then those attribute values are "inherited" to the content nodes that have this special attribute.
...these nodes are part of the xul dom just like any other, and having an id attribute is bound to cause problems, given that you could have more than instance of your element in the same document and then multiple inner items with the same id.
... in order to work around this problem, the anonid attribute is used instead: <xul:label anonid="xulshoolhello-name-label" xbl:inherits="value=name" /> and then, in order to get a reference to the node from the js code in your binding, we use the getanonymouselementbyattribute dom method: let namelabel = document.getanonymouselementbyattribute( this, "anonid", "xulshoolhello-name-label"); implementation the implementation section defines most of the scripting side of your element.
...you can leave the content alone by not including the content tag, and then just add the methods and properties you wish to override.
XPCOM Objects - Archive of obsolete content
well, those are applications that, simply put, take the underlying platform with perhaps a few changes and additions, and then write their own chrome layer.
...then you'll see a list of all members of this object, with some documentation about it.
...then we change it back, because after that we only need to get and set preferences, and those methods are in nsiprefbranch.
...childarray = childarrayobj.value; the general rule for out parameters is that you can pass an empty object, and then you can get the result by accessing the value attribute in this object after the method call.
Using Dependent Libraries In Extension Components - Archive of obsolete content
the basic strategy of the stub is to dynamically load the dependent libraries, then load the component library and continue registration.
...we want to load the dependent libraries // of the real component, then the component itself, and call nsgetmodule on // the component.
...we want to load the dependent libraries // of the real component, then the component itself, and call nsgetmodule on // the component.
... if you update your dependencies in your component, // but forget to remove a dependant library in the stubloader, then we don't want to // fail loading the component since the dependant library isn't required.
Localizing an extension - Archive of obsolete content
then we simply replace each text string in our xul files with the corresponding entity.
...then it fetches all the strings we need from the bundle, one by one, by calling the string bundle's getstring() method, passing the appropriate key for each string.
...then we replace any occurrences of the literal strings with the appropriate variables: samplepanel.tooltiptext = changestring + fieldarray[4] + " | " + openstring + fieldarray[5] + " | " + lowstring + fieldarray[6] + " | " + highstring + fieldarray[7] + " | " + volumestring + fieldarray[8]; localizing the description in install.rdf see localizing extension descriptions.
...for example, to add a spanish localization, you would add: locale stockwatcher2 es-es chrome/locale/es-es/ then just create a subdirectory chrome/locale/es-es and add the needed dtd files; in this case, options.dtd and stockwatcher2.dtd.
Images, Tables, and Mysterious Gaps - Archive of obsolete content
in cases where an author is writing a new document or trying to migrate a design to be as standards-based as possible, then "almost standards" mode is probably a better choice.
... one potential solution is to add a class to any image that needs to be block-level and then write the rule to match.
...should this property be adopted, then any browser supporting it could emulate traditional "shrinkwrap" behavior without risking other layout upset with the following rule: td {line-box-contain: font replaced;} /* proposed for css3 */ there are other possible fixes contained within the current css3 working drafts, such as line-height-policy.
...if you're using strict markup, or you need for other reasons to be in "standards" rendering, then remember these guidelines: any image alone in a table cell (e.g., single-pixel spacer images) should be made block-level.
Monitoring WiFi access points - Archive of obsolete content
the onchange() method (lines 13 through 27) begins by enabling universalxpconnect privileges, then clearing out the div (d) that will receive the updated list of access points.
... then the loop in lines 19-22 iterates over the list of access points received in the accesspoints array and adds them to the html in the div.
... then the c div is updated with the number of times the list has been refreshed.
...starting to monitor access points to start monitoring the access points, we instantiate the listener (on line 44), then get access to the wifi monitor interface on line 45.
Source Navigator - Archive of obsolete content
then click "ok".
... the snavigator then begins to scan your source directories.
...choose the project file that you've just created and then click "open...".
... source navigator then loads the database and then display the following symbols window: searching a method by typing in the method name viewing the definition/declaration by highlighting the method in the code ...
Autodial for Windows NT - Archive of obsolete content
if this service is running, and control panel | network connections | advanced | dialup preferences is set to enable autodial, then any application trying to access the internet will trigger the autodial feature whenever an internet address cannot be reached.
...essentially, if some address at domain.com is in the database, then any address at domain.com is considered to be in the database.
... also, if any address that starts with www is in the database, then any other address that begins with www is considered to be in the database.
...then enable autodial for a dialup connection: control panel | network connections | advanced | dialup preferences.
Creating a Microsummary - Archive of obsolete content
then just link to the microsummaries from within the pages themselves using a <link rel="microsummary"> element, f.e.: <head> <link rel="microsummary" href="index.php?view=microsummary"> </head> when firefox encounters a <link rel="microsummary"> element, it loads the url in the href attribute.
... install the extension (restarting firefox to complete installation) then go to the spread firefox home page, find the firefox download count (a large number at the bottom of the right-hand column), context click on the number, and select view xpath from the context menu.
...if we were the spread firefox webmasters, we might simply reference the generator within the page itself by adding a <link rel="microsummary"> tag to its <head> element: <head> <link rel="microsummary" href="path/to/our/generator.xml"> </head> since we're not that site's webmasters, however, we can specify the page to which the generator applies within the generator itself and then make the generator available for download and installation.
...to do so, we need to put it up on the web and then create a javascript link on some web page that calls firefox's window.sidebar.addmicrosummarygenerator() method to download and install the generator.
Getting Started - Archive of obsolete content
if it doesn't appear as you expected, then go back into the installed-chrome.txt file and double check that you modified the lines correctly.
...change the blue part to whatever you want your theme called and then its version number.
... then scroll down to the next section.
...<a href="javascript:installtrigger.installchrome(installtrigger.skin, 'myskin.jar', 'my skin theme')">install my skin</a> if you have jar files on your hard drive and would like to install them, then download/use this form.
Introducing the Audio API extension - Archive of obsolete content
content scripts can specify the audio stream's characteristics, then write audio samples.
... users must create an audio object and then use the mozsetup() function to specify the number of channels and the frequency (in hz).
...then the samples are written in the audio stream with the function mozwriteaudio().
... autolatency = false; } processing an audio stream since the mozaudioavailable event and the mozwriteaudio() method both use float32array values, it is possible to take the output of one audio stream and pass it directly (or process first and then pass) to a second.
Nanojit - Archive of obsolete content
then it wraps the lirbufwriter in zero or more other lirwriter objects, all of which implement the same interface as lirbufwriter.
... then a pointer to a function is used, which takes an int as input and returns the sum of that parameter with two.
... (typedef js_fastcall int32_t (*addtwofn)(int32_t); ) then, printf is hardcoded to call it with a parameter 5, and on linking with nanojit library, the following program will display 2+5=7 now, what i need to do is generate output for this: start two = int 2 twoplustwo = add two, two ret twoplustwo this adds two and two in the most hardcoded way possible.
...the interpreter is then equipped to handle the overflow.
How to Write and Land Nanojit Patches - Archive of obsolete content
then for each revision involved, mark its whiteboard as fixed-in-tracemonkey or fixed-in-tamarin.
...then find the corresponding bug(s) and commit the (hopefully already-reviewed!) tr/tm portion of the patch(es) on top of your current, un-pushed tip.
...then update the whiteboard for the each such bug p and add a comment url.
... scenario 4: if you break something if you land a patch that breaks nanojit-central, and then land a follow-up fix, it's a good idea to ensure the follow-up fix gets merged to tm and tr as soon as possible.
Tamarin build documentation - Archive of obsolete content
then build as follows: - replace the makefile in the main folder with the one attached to this page.
...nor does any other brand of make.) setup: if you normally work in a cygwin mounted place (eg /home/user/...) then you must cd around to the cygdrive path equivalent (eg /cygdrive/c/cygwin/home/user/).
...to enable this go to eclipse preferences >> c/c++ >> indexer, then select 'use active build configuration' in the 'build configuration for the indexer' section.
...additional things to try are clicking on the project name then refreshing it (file/refresh or right-click/refresh) and/or quitting and restarting eclipse.
Menus - Archive of obsolete content
<menu label="file" accesskey="f"/> this menu can then be opened by pressing the access key (typically in combination with the alt key).
... for example, if it is a menu element and has been activated via a mouseover, then the menu will open.
... if it has been activated via navigation with the up or down arrow on the keyboard, then pressing the return key or right arrow key will open the menu.
... if it were a menuitem, then pressing the return key would have launched the command associated with it.
Complete - Archive of obsolete content
if you want to see these techniques in action, then you can download and install the complete allcustom extension: allcustom.xpi (the link is external only because this wiki does not support xpi files.) the extension does not contain any useful functions.
...restart the application using the command line switch: -uilocale fr-fr (of course, if your application is already in french, specify en-us here to switch the extension to english.) notes: if you use a shortcut or launcher icon to start the application, then you can add the command line switch by editing the icon's properties.
...to work around the bug, close the application, delete the file xul.mfl in its profile, then restart it with the command line switch.
...testing a theme to test a theme in seamonkey, choose view – apply theme, then choose the theme.
Custom toolbar button - Archive of obsolete content
if you know how to program in javascript, then you can write your own code that does other things.
...go to the profile directory that you use for the application, then go to the extensions directory there.
...then it specifies an overlay for each toolbar.
... advanced troubleshooting if you have some technical knowledge, then you can use the application's javascript console to see error messages.
Advanced Rules - Archive of obsolete content
it then iterates over all that resource's child resources.
...you can then use the variable 'var' within the remainder of the conditions.
...we can then get related resources to the root resource by using the 'list' variable.
... the template builder then sees the member element.
XBL Example - Archive of obsolete content
this will call the onget script to get the value, increment or decrement the value by one, and then call the onset handler to set the value.
...it will need to make sure the page is not out of range and then modify the deck's selectedindex attribute and the text widget's label attribute.
... var thedeck=document.getanonymousnodes(this)[0].childnodes[0]; get the first element of the anonymous content array, which will be the vertical box, then get its first child, which will be the deck element.
...the label element can be retrieved by getting the first element of anonymous content (the vertical box), the second child of that label element (the horizontal box), and then the second element of that box.
XUL Questions and Answers - Archive of obsolete content
if user wants checkbox support for multicolumn lists, then they will have to implement one.
...the best you can do is a cascading menu along the lines of the move/copy menus, but then of course you lose the ability to easily select from the list.
...i want to create xul element in the javascript, assign datasources/ref/template attribute to it so that the content is generated from the rdf datasource create the element, set the datasources attribute then add the element to the document.
... this should then create the database.
Debugging a XULRunner Application - Archive of obsolete content
then run console redirector.exe /?
... troubleshooting x-jsd is not a registered protocol if the message "x-jsd is not a registered protocol" appears when trying to open *.js files in venkman, then add an empty file called .autoreg in the same directory as your xulrunner binary.
... if .autoreg already exists, then edit it to force the last modified time to be updated.
... xulrunner will then notice the new components file.
Adobe Flash - Archive of obsolete content
the flash plugin's description string uses a standard versioning nomenclature that can then be parsed for meaningful information.
...however, if you wish to use fscommands with the flash plugin to call javascript functions in an html page, then you must use the embed element, as discussed further in the section on fscommands.
... enter some text in the html form field below and then click outside the field, or hit the enter key, to send the text to the flash movie below: the example is missing.
... in example 2, a javascript function first obtained a handle to the html that spawned the plugin (the object element or the embed element) and then called a published method of the flash plugin on the reference to the html element.
TCP/IP Security - Archive of obsolete content
the lowest layer sends the accumulated data through the physical network; the data is then passed up through the layers to its destination.
... the integrity of data can be assured by generating a message authentication code (mac) value, which is a keyed cryptographic checksum of the data.
... peer authentication.
... ssl authentication is typically performed one-way, authenticating the server to the client, but it can be performed mutually.
Table Reflow Internals - Archive of obsolete content
when a target is the cell or below and the cell changes size, the row tells the table so it can decide if it needs to rebalance when a target is inside the cell's block, the cell requests max element, preferred sizes of its block in case they change after the table reflows the row group(s) containing the targets, if it rebalances, it then does a pass 2 reflow.
... special height reflow when there is a % height frame inside a cell without a computed height the frame will never get a chance to size based on the final cell height in paginated mode when there is a height on the table, the table doesn't allocate extra height to rows until after it does a pass 2 reflow and then it is too late this can be fixed by doing a special 3rd pass reflow special reflow example <table border=2 width=300> <tr> <td> this cell's width is constrained by the table and image widths.
...if the page is incomplete then the page sequence creates a continuation for the page and sets it as the page's next sibling (it is also the page's nextinflow).
...if there will be a pass 3 reflow then this should (bug) happen at that time instead.
Old Proxy API - Archive of obsolete content
if one of the fundamental traps isn't implemented and the proxy is used in a way that expects the fundamental trap to be defined, then an error is thrown.
... if a derived trap is implemented, then that trap's code is called whenever the corresponding behavior happens on the proxy.
...if a trap isn't implemented, then if it's a derived trap, the default implementation is used.
... however, if a fundamental trap is unimplemented, then a call to this trap will throw a typeerror.
Styling the Amazing Netscape Fish Cam Page - Archive of obsolete content
so i decided to break up the content so that there is a self-contained bit of markup for each fish, and then get down to styling.
...i then set up a thicker double border on the left, a one-pixel border the rest of the way around, and set the background to match the rest of the design.
... getting the image back on top of the heading turned out to be a matter of relatively positioning the floated image, and then giving it a z-index value.
...therefore, i just added a half-em margins on card paragraphs, and then changed the left margin to be 160px, which makes sure the text in the paragraphs won't wrap under the floated images.
Reference - Archive of obsolete content
if it's not in a standard, and that sun doc is corrent, then it should probably go in the window object methods.
...if downloading the stuff is your priority you are free to field ideas/concept to the devmo mailing list for discussion, and then actually code it (or find someone to do so).
...then carefully update all links to the javascript 1.5 pages to link to the javascript 1.6 pages -- unless the links are specifically about javascript 1.5 ?
... then do it all over again when javascript 1.7, javascript 2.0, javascript xxxxii.1, etc.
Mozilla XForms User Interface - Archive of obsolete content
if you see xhtml/xul then it means the control is available when xforms is hosted in either xhtml or xul.
... similarly, if you see xhtml only or xul only, then it means the control is available only in that host language.
... image - if the instance node contains an image, then an output element can be used in combination with the mediatype element to display the image.
...for example, if a repeat is bound to a nodeset that contains 5 nodes and the repeat contains an output element that echoes the current node, then the user will see 5 outputs in the form.
RDF in Mozilla FAQ - Archive of obsolete content
statements about the same rdf resource can then be intermingled: for example, the "last visit date" of a particular website comes from the "browser global history" datasource, and the "shortcut keyword" that you can type to reach that website comes from the "browser bookmarks" datasource.
...if the uri argument refers to an rdf/xml file's url, then the rdf service will create an rdf/xml datasource and asynchronously parse it.
...(these are bizarrely arranged because the eventual intent is to introduce templates using the extended form -- which in many ways is conceptually simpler, even if more verbose -- and then treat the "simple" form as a shorthand for the extended form.) what can i build with a xul template?
...</window> assuming that we've aquired a datasource somehow (e.g., like this), the following sample code illustrates how to add that datasource to the template, and then force the template to rebuild itself based on the newly added datasource's contents.
Game promotion - Game development
honesty is key and you should be authentic, because nobody likes boring press releases or pushy advertisements.
...if you're honest with your approach and your game is good, then you've got more of a chance of success.
... promo codes if you're selling the game, then create the ability to distribute promo codes allowing people to access your game for free (or at least a demo or time-limited version), and send them all over the place — to press, youtubers, as competition prizes, etc.
...then when you need any help they will be there for you.
Explaining basic 3D theory - Game development
it's like taking a photo of the given scenery you have prepared — you have to place the objects first, configure the camera, and then take the shot.
...then there's view transformation which takes care of positioning and setting the orientation of the camera in the 3d space.
... projection transformation (also called perspective transformation) then defines the camera settings.
... output merging during the output manipulation stage all the fragments of the primitives from the 3d space are transformed into a 2d grid of pixels that are then printed out on the screen display.
Building up a basic demo with the PlayCanvas engine - Game development
playcanvas application to begin developing our game we have to create the playcanvas application first (using the given <canvas> element), and then start the update loop.
... then it adds a camera component to it with the light gray clearcolor — the color will be visible as the background.
...then all we need to do is set the box's material to the newly created boxmaterial.
...then the material is created, given a gray color, and assigned to the cone entity.
XInclude - MDN Web Docs Glossary: Definitions of Web-related terms
s.length; i++) { var xinclude = xincludes[i]; var href = xinclude.getattribute('href'); var parse = xinclude.getattribute('parse'); var xpointer = xinclude.getattribute('xpointer'); var encoding = xinclude.getattribute('encoding'); // e.g., utf-8 // "text/xml or application/xml or matches text/*+xml or application/*+xml" before encoding (then utf-8) var accept = xinclude.getattribute('accept'); // header "accept: "+x var acceptlanguage = xinclude.getattribute('accept-language'); // "accept-language: "+x var xifallback = xinclude.getelementsbytagnamens('http://www.w3.org/2001/xinclude', 'fallback')[0]; // only one such child is allowed if (href === '' || href === null) { // points to same...
...obably just need bom test since other encodings must be specified var patternxml = /\.(svg|xml|xul|rdf|xhtml)$/; if ((contenttype && contenttype.match(/[text|application]\/(.*)\+?xml/)) || (href.indexof('file://') === 0 && href.match(patternxml))) { /* grab the response as text (see below for that routine) and then find encoding within*/ var encname = '([a-za-z][a-za-z0-9._-]*)'; var pattern = new regexp('^<\\?xml\\s+.*encoding\\s*=\\s*([\'"])'+encname+'\\1.*\\?>'); // check document if not?
... responsenodes = a; } else { // otherwise, the response must be a single well-formed document response responsenodes = [response.documentelement]; // put in array so can be treated the same way as the above } // prepend any node(s) (as xml) then remove xinclude for (j=0; j < responsenodes.length ; j++) { xincludeparent.insertbefore(responsenodes[j], xinclude); } xincludeparent.removechild(xinclude); } else if (responsetype === 'responsetext') { i...
...ludeparent.replacechild(textnode, xinclude); } // replace xinclude in doc with response now (as plain text or xml) } } } catch (e) { // use xi:fallback if xinclude retrieval above failed var xifallbackchildren = xifallback.childnodes; // prepend any node(s) then remove xinclude for (j=0; j < xifallbackchildren.length ; j++) { xincludeparent.insertbefore(xifallbackchildren[j], xinclude); } xincludeparent.removechild(xinclude); } } } return docu; } ...
Accessible multimedia - Learn web development
it works out the number of minutes and seconds from the given currenttime value (which is in seconds), adds a leading 0 if either the minute or second value is less than 10, and then creates the display readout and adds it to the time label.
... community/grass roots/self transcription — if you are part of an active community or team in your workplace, then you could ask them for help with doing the translations.
...if the audio you are presenting is something like a face to face meeting or live spoken performance, it would be acceptable to take notes during the performance, publish them in full along with the audio, then seek help in cleaning up the notes afterwards.
... transcript examples if you use an automated service, then you'll probably have to use the user interface that the tool provides.
WAI-ARIA basics - Learn web development
as a result, developers quite often rely on javascript libraries that generate such controls as a series of nested <div>s or table elements with classnames, which are then styled using css and controlled using javascript.
...as an example, aria-required="true" specifies that a form input needs to be filled in to be valid, whereas aria-labelledby="label" allows you to put an id on an element, then reference it as being the label for anything else on the page, including multiple elements, which is not possible using <label for="input">.
... if you go to voiceover's landmarks menu (accessed using voiceover key + u and then using the cursor keys to cycle through the menu choices), you'll see that most of the elements are nicely listed so they can be accessed quickly.
... if the disabled state of an input is likely to change, then it is also a good idea to indicate when it happens, and what the result is.
Sizing items in CSS - Learn web development
if you add a <div> to your html with no content, then give it a border as we did with the image, you will see a line on the page.
...when a size is given to an element (and the content of which then needs to fit into that size) we refer to it as an extrinsic size.
...the box will always be at least this height, but will then grow taller if there is more content than the box has space for at its minimum height.
...you should, however, not use this technique to load really large images and then scale them down in the browser.
The box model - Learn web development
if a box has an outer display type of inline, then: the box will not break onto a new line.
...any padding and border is then added to that width and height to get the total size taken up by the box.
... .box { box-sizing: border-box; } if you want all of your elements to use the alternative box model, and this is a common choice among developers, set the box-sizing property on the <html> element, then set all other elements to inherit that value, as seen in the snippet below.
...if you are using the alternative box model then the size of the border makes the content box smaller as it takes up some of that available width and height.
CSS values and units - Learn web development
if the allowed value includes <length-percentage> then you can use a length or a percentage.
...i have then set the boxes to have different opacity values — notice how the background shows through more when the alpha channel value is smaller.
...it is likely that for most projects you will decide on a color palette and then use those colors — and your chosen method of specifying color — throughout the whole project.
...you can then look up the specifics here on mdn.
Flexbox - Learn web development
if the parent hasn't got a fixed width in the cross axis direction, then all flex items will become as long as the longest flex items.
...so if you have four items with order values of 2, 1, 1, and 0 set on them respectively, their display order would be 4th, 2nd, 3rd, then 1st.
...we first use flex:1 100px; to effectively give it a minimum height of 100px, then we set its children (the <button> elements) to also be laid out like flex items.
...for example, if a browser is missing a css drop shadow, then the site will likely still be usable.
Test Your Skills: Fundamental layout comprehension - Learn web development
if you have worked through this module then you will have already covered the basics of what you need to know to do css layout today, and to work with older css as well.
... if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page.
... if you don't want to work locally then using a tool such as codepen or jsfiddle will work as well.
... the navigation bar should scroll with the content and then become stuck at the top of the viewport when it reaches it.
Grids - Learn web development
a grid will typically have columns, rows, and then gaps between each row and column — commonly referred to as gutters.
...we will look at the basic features of grid layout first and then explore how to create a simple grid system for your project.
... .container { display: grid; grid-template-columns: 200px 200px 200px; } add the 2nd declaration to your css rule, then reload the page, and you should see that the items have rearranged themselves one into each cell of the created grid.
...one</div> <div>two</div> <div>three</div> <div>four</div> <div>five</div> <div>six</div> <div>seven</div> </div> .container { display: grid; grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); grid-auto-rows: minmax(100px, auto); grid-gap: 20px; } this works because grid is creating as many 200 pixel columns as will fit into the container, then sharing whatever space is leftover between all of the columns — the maximum is 1fr which, as we already know, distributes space evenly between tracks.
Practical positioning examples - Learn web development
you might be thinking "why not just create the separate tabs as separate webpages, and just have the tabs clicking through to the separate pages to create the effect?" this code would be simpler, yes, but then each separate "page" view would actually be a newly-loaded webpage, which would make it harder to save information across views, and integrate this feature into a larger ui design.
...here we simply set a fixed height to make sure the panels fit snugly inside the info-box, position relative to set the <div> as the positioning context, so you can then place positioned child elements relative to it and not the <html> element, and finally we clear the float set in the css above so that it doesn't interfere with the remainder of the layout.
... then we use a for loop to cycle through all the tabs and run a function called settabhandler() on each one, which sets up the functionality that should occur when each one is clicked on.
...we then give it a large margin-left to move it over to the right, making space for the info-box to sit in, so it is not overlapping anything else.
Getting started with CSS - Learn web development
it contains an <em>emphasized</em> element.</p> <ul> <li>item one</li> <li>item two</li> <li>item <em>three</em></li> </ul> </body> </html> note: if you are reading this on a device or an environment where you can't easily create files, then don't worry — live code editors are provided below to allow you to write example code right here in the page.
...take a look at the page for list-style-type and you will find an interactive example at the top of the page to try some different values in, then all allowable values are detailed further down the page.
...try adding a class of special to it, then reload your page and see what happens.
...if you were to do this then you would no longer be able to apply the class to a <span> or another element by simply adding the class to it; you would have to add that element to the list of selectors: li.special, span.special { color: orange; font-weight: bold; } as you can imagine, some classes might be applied to many elements and you don't want to have to keep editing your css every time something new needs to take on that style.
How CSS is structured - Learn web development
here are three examples: <!-- inside a subdirectory called styles inside the current directory --> <link rel="stylesheet" href="styles/style.css"> <!-- inside a subdirectory called general, which is in a subdirectory called styles, inside the current directory --> <link rel="stylesheet" href="styles/general/style.css"> <!-- go up one directory level, then inside a subdirectory called styles --> <link rel="stylesheet" href="../styles/style.css"> internal stylesheet an internal stylesheet resides within an html document.
...ml> <html lang="en"> <head> <meta charset="utf-8"> <title>my css experiments</title> <link rel="stylesheet" href="styles.css"> </head> <body> <p>create your test html here</p> </body> </html> styles.css: /* create your test css here */ p { color: red; } when you find css that you want to experiment with, replace the html <body> contents with some html to style, and then add your test css code to your css file.
...add html, then add the two p { ...
...there are also other shorthand types, for example 2-value shorthands, which set padding/margin for top/bottom, then left/right */ padding: 10px 15px 15px 5px; is equivalent to these four lines of code: padding-top: 10px; padding-right: 15px; padding-bottom: 15px; padding-left: 5px; this one line: background: red url(bg-graphic.png) 10px 10px repeat-x fixed; is equivalent to these five lines: background-color: red; background-image: url(bg-graphic.png); background-position: 10px 10px; background-repeat: r...
What is CSS? - Learn web development
we then have a set of curly braces { }.
...each pair specifies a property of the element(s) we are selecting, then a value that we'd like to give the property.
...a website built in 2000, using the limited css available then, should still be usable in a browser today!
... browser support once css has been specified then it is only useful for us in developing web pages if one or more browsers have implemented it.
CSS FAQ - Learn web development
LearnCSSHowtoCSS FAQ
</div> if the same property is declared in both rules, the conflict is resolved first through specificity, then according to the order of the css declarations.
...if you define a rule and then you re-define the same rule, the last definition is used.
...inline style (in html style attributes) has the highest specificity and will override any selectors, followed by id selectors, then class selectors, and eventually element selectors.
... if you need to use prefixes in your work, you are advised to write your code in a way that uses the prefixed versions first, but then includes a non-prefixed standard version afterwards so it can automatically override the prefixed versions where supported.
How do I use GitHub Pages? - Learn web development
you can then collaborate on code projects, and the system is open-source by default, meaning that anyone in the world can find your github code, use it, learn from it, and improve on it.
...click plus (+) in the top right of the github homepage, then choose new repository.
...to do this, from the homepage of your repository choose settings, then scroll down until you get to the github pages section.
...then, you need to enter the following commands (pressing enter after each one) to push those changes to github: git add --all git commit -m 'another commit' git push you can replace another commit with a more suitable message to describe what change you just made.
How do you set up a local testing server? - Learn web development
click install, then click close when the installation has finished.
...you can then access your content at localhost:7800.
...to run this you'll need to install python/pip, then install flask using pip3 install flask.
... at this point you should be able to run the python flask examples using for example python3 python-example.py, then navigating to localhost:5000 in your browser.
The web and web standards - Learn web development
it'll take you a few months to really start to get into it, and then you'll need to keep learning so that your knowledge stays up-to-date with all the new tools and features that appear on the web platform, and keep practicing and refining your craft.
... there are another class of languages called back-end (or server-side) languages, meaning that they are run on the server before the result is then sent to the browser to be displayed.
... a typical use for a server-side language is to get some data out of a database and generate some html to contain the data, before then sending the html over to the browser to display it to the user.
...it also involves a lot of testing to see if anything fails in certain browsers, and then more work to fix those failures.
Video and Audio APIs - Learn web development
if it hasn't yet been set, we add the active class to the rwd button using classlist.add(), pause the video using htmlmediaelement.pause(), then set the intervalrwd variable to equal a setinterval() call.
... then we initialize two more variables — minutevalue and secondvalue.
... the length we should set the inner <div> to is worked out by first working out the width of the outer <div> (any element's clientwidth property will contain its length), and then multiplying it by the htmlmediaelement.currenttime divided by the total htmlmediaelement.duration of the media.
... note: you could also further improve the efficiency of the code by creating a separate function that runs these lines, then calling that anywhere it is needed, rather than repeating the lines multiple times in the code.
Storing the information you need — Variables - Learn web development
the first line pops a box up on the screen that asks the reader to enter their name, and then stores the value in a variable.
... you may not fully understand the syntax we are using (yet!), but you should be able to get the idea — if we didn't have variables available, we'd have to implement a giant code block that checked what the entered name was, and then display the appropriate message for any name.
... a safe convention to stick to is so-called "lower camel case", where you stick together multiple words, using lower case for the whole first word and then capitalize subsequent words.
...in this section we'll describe these in brief, then in future articles, you'll learn about them in more detail.
Adding features to our bouncing balls demo - Learn web development
note: if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page.
...you should then make the following changes: we want the evil circle to not be filled in, but rather just have an outer line (stroke).
...if it is one of the four represented by the specified keycodes, then the evil circle will move left/right/up/down.
... first of all, create a new evil circle object instance (specifying the necessary parameters), then call its setcontrols() method.
JavaScript object basics - Learn web development
try entering the following line below the javascript code that's already in your file, then saving and refreshing: const person = {}; now open your browser's javascript console, enter person into it, and press enter/return.
...next you write a dot, then the item you want to access — this can be the name of a simple property, an item of an array property, or a call to one of the object's methods, for example: person.age person.interests[1] person.bio() sub-namespaces it is even possible to make the value of an object member another object.
... setting object members so far we've only looked at retrieving (or getting) object members — you can also set (update) the value of object members by simply declaring the member you want to set (using dot or bracket notation), like this: person.age = 45; person['name']['last'] = 'cratchit'; try entering the above lines, and then getting the members again to see how they've changed, like so: person.age person['name']['last'] setting members doesn't just stop at updating the values of existing properties and methods; you can also create completely new members.
...we could get those values like this: let mydataname = nameinput.value; let mydatavalue = namevalue.value; we could then add this new member name and value to the person object like this: person[mydataname] = mydatavalue; to test this, try adding the following lines into your code, just below the closing curly brace of the person object: let mydataname = 'height'; let mydatavalue = '1.75m'; person[mydataname] = mydatavalue; now try saving and refreshing, and entering the following into your text input: person.
Multimedia: Images - Learn web development
should such an image only exist as a bitmap, then png would be the fallback format to chose.
...if you want to play it safe, then you would go for well compressed progressive jpegs.
... if all of this sounds a bit complicated or feels like too much work for your team then there is also online services that you can use as image cdns that will automate the serving of the correct image format on-the-fly, according to the type of device or browser requesting the image.
... and finally, should you want to include animated images into your page, then know that safari allows using video files within <img> and <picture> elements.
Componentizing our Svelte app - Learn web development
we'll componentize our app, then add more functionality to allow users to update existing components.
... code along with us git clone the github repo (if you haven't already done it) with: git clone https://github.com/opensas/mdn-svelte-tutorial.git then to get to the current app state, run cd mdn-svelte-tutorial/04-componentizing-our-app or directly download the folder's content: npx degit opensas/mdn-svelte-tutorial/04-componentizing-our-app remember to run npm install && npm run dev to start your app in development mode.
... inside this file we will declare a filter prop, and then copy the relevant markup over to it from todos.svelte.
...ock inside todos.svelte like so: <ul role="list" class="todo-list stack-large" aria-labelledby="list-heading"> {#each filtertodos(filter, todos) as todo (todo.id)} <li class="todo"> <todo {todo} /> </li> {:else} <li>nothing to do here!</li> {/each} </ul> the list of todos is displayed on the page, and the checkboxes should work (try checking/unchecking a couple, and then observing that the filters still work as expected), but our "x out of y items completed" status heading will no longer update accordingly.
Package management basics - Learn web development
to see local dependencies really shine, all you need to do is try to download and run an existing project — if it works and all the dependencies work right out of the box, then you have local dependencies to thank for the fact that the code is portable.
... type the following command, making sure you are inside the parcel-experiment directory: npm init you will now be asked some questions; npm will then create a default package.json file based on the answers: name: a name to identify the app.
...type in something really simple, like "a simple npm package to learn about using npm", then press return.
... initialise a new project npm init yarn init as shown above, this will prompt and walk you through a series of questions to describe your project (name, license, description and so on) then generate a package.json for you that contains meta information about your project and its dependencies.
Accessible Toolkit Checklist
ed via method calls layout engine - drawing underline under correct letter events - making keystrokes do the right thing msaa support, via iaccessible's get_acckeyboardshortcut support for ms windows settings when high contrast checkbox is set (in accessibility control panel, spi_gethighcontrast), or when user selects a "native" skin option in your software, then get all look and feel from current os skin.
... msaa support, including checkbox state and statechange event tab panels ctrl+[shift]+tab or ctrl+pgup/pgdn to switch tabs tabs can be focused, and then left/right arrow to switch first click on a tab switches to it, second click focuses it msaa support.
... multiple selection is possible with ctrl+arrow to move focus without selecting, then space to select item, shift+space to select to current point or control+space to toggle selection of current item shift+f10 or context menu key to bring up context menu for current item.
... msaa support, including accessible selection, selectable, multiselectable and extselectable states, and statechange events for checkbox children trees when a tree view is tabbed to, select the first item if nothing else is already selected up/down arrow key navigation left arrow to first collapse a branch, then move to parent right arrow to first expand a branch, then move to first child multiple selection is possible with ctrl+arrow to move focus without selecting, then space to select item, shift+space to select to current point or control+space to toggle selection of current item typing letter or several letters to navigate (similar to list support for this) shift+f10 or conte...
Android-specific test suites
running android-test to run android-test, first build firefox for android with your changes; then run ./mach android test this will run the tests and report the results to stdout, as well as produce an html report.
... running android-checkstyle to run android-checkstyle, first build firefox for android with your changes; then run ./mach android checkstyle this will run the tests and report the results to stdout, as well as produce an html report.
... running android-findbugs to run android-findbugs, first build firefox for android with your changes; then run ./mach android findbugs this will run the tests and report the results to stdout, as well as produce an html report.
... running android-lint to run android-lint, first build firefox for android with your changes; then run ./mach android lint this will lint the code and report the results to stdout, as well as produce an html report.
Creating reftest-based unit tests
reftest will then compare them and verify whether they produce the same bitmap.
... so, my point is, if you have an idea then create a test.
...one should be able to "snap a picture" of the glyph as it should be displayed and then the reference page would include that graphic in an <img> element.
...invalidation tests check both that the internal state of the document has been updated correctly, and that the browser then correctly invalidates and repaints the appropriate parts of the screen.
Multiple Firefox profiles
the one being run by this firefox instance will include the bold text "this is the profile in use" for example, if you find that text beneath the entry for "profile: suzie", then you are running in a profile named suzie.
...then follow the instructions below, applicable to your operating system.
...close all instances of firefox, or restart the computer, and then try again.
... renaming a profile in the profile manager, select the profile you want to rename, and then click "rename profile".
Gecko Keypress Event
charcode of dom keypress event if a keypress event is fired without any modifier keys (ctrl/alt(option)/meta(win/command)), then the properties of the event are the same as they were in gecko1.8.1.
... if the os-provided character cannot be entered without using the ctrl key, then, gecko does not replace the character.
... if the character provided by the keyboard layout cannot be entered without ctrl key, then, gecko does not replace the character (as on windows).
...there should be no chrome access keys with punctuation characters or other characters that would normally require depressing the shift key.) during accel key handling, if the event includes the shift modifier, but an alternative charcode is not a bicameral letter (i.e., it does not have upper and lower case forms), then the shift modifier state should be ignored if there is no exactly matching handler (requiring shift to be down).
IPDL Tutorial
then you can pass a mozilla::maybe object instead of a concrete value.
... the resolve callback for the first overload as well as the success callback for the mozpromise's then() method each have a single parameter.
...the rpc qualifiers mean that if the parent calls "callmecallyou()" on the child actor, then the child actor, while servicing this call, is allowed to call back into the parent actor's "callyou()" message.
... if an actor a sends messages m1 then m2 to actor b, b will be awoken to process m1 then m2.
Implementing Download Resuming
the server is not using http 1.1), then accessing this attribute will throw an ns_error_not_resumable exception.
...the front-end code can then notify the user of this, and offer to resume the download.
...then, you can check if it implements nsiresumablechannel.
... detecting when a file changed if the file changed (that is, the entity id does not match), then necko will notify the stream listener with an ns_error_entity_changed error code.
Interfacing with the Add-on Repository
importing the repository code module before you can use the add-on repository api, you need to import the code module: components.utils.import("resource://gre/modules/addonrepository.jsm"); having done this, you can then access the api through the resulting addonrepository object.
... for example: searchsucceeded: function(addons, addoncount, totalresults) { var num = math.floor(math.random() * addoncount); this.shownotification("would you like to try the " + addons[num].name + " addon?", "install", addons[num].install); }, this routine randomly selects one of the returned add-ons, then calls the previously mentioned shownotification() routine, passing in as parameters a prompt including the name of the returned add-on, a label for the button to show in the notification ("install"), and the addoninstall object that can be used with the add-on manager api to install the add-on.
...skey: "i", callback: function() { if (popupnotifications.install) { popupnotifications.install.install(); } else { popupnotifications.remove(box); } } }, null /* secondary action */ ); } the code here starts by stashing the passed-in addoninstall object for later use, then creates and displays the pop-up notification box with the text and button label passed into the method.
... the pop-up callback function that gets called when the user clicks the button looks to see if there's a non-null addoninstall object reference; if it's null, then the pop-up is displaying an error notification, so clicking the button simply dismisses the pop-up.
Following the Android Toasts Tutorial from a JNI Perspective
for example, if the class is blah.foo.bar then the signature of this will be this in slash notation with an l and ; around it.
...if there is a sub class such as blah.foo.bar.subclass then a dollar sign is used in the slash notation, so this would be lblah/foo/bar$subclass;.
...if it is not static, then it cannot be used on an instance of that class.
...we will add this to our sig object in slash notation: geckoappshell: 'lorg/mozilla/gecko/geckoappshell;' we then instantiate the geckoappshell class in jni and declare the getcontext method; dxr showed that this method accepted no arguments and returns a context, and we already had the sig for context in our sig object.
Task.jsm
if you specify a generator function or the iterator returned by a generator function, then task.spawn() is implicitly called, and the yield operator works on the returned promise.
...sk.spawn((function* () { return yield sendgreeting(this.message.replace(/name/, name)); }).bind(this); }) }; with async(), the method can be declared succinctly: let greeter = { message: "hello, name!", greet: task.async(function* (name) { return yield sendgreeting(this.message.replace(/name/, name)); }) }; while maintaining identical semantics: greeter.greet("mitchell").then((reply) => { ...
... for (let i = 0; i < 3; i++) { result += yield getpromiseresolvedontimeoutwithvalue(50, "!"); } return "resolution result for the task: " + result; }).then(function (result) { // result == "resolution result for the task: value!!!" // the result is undefined if no special task.result exception was thrown.
...task.spawn(function* () { let currentdir = yield os.file.getcurrentdirectory(); let path = os.path.join(currentdir, ".mozconfig"); try { let info = yield os.file.stat(path); console.log("the .mozconfig file is " + info.size + " bytes long."); } catch (ex if ex instanceof os.file.error && ex.becausenosuchfile) { console.log("you don't have .mozconfig in " + currentdir); } }).then(null, components.utils.reporterror); in this example, if the promise returned by os.file.stat is rejected, an exception is thrown inside the task.
WebRequest.jsm
this then enables the event listener to modify or cancel the request.
...if you don't pass filter, then the listener is invoked for every web request the browser makes that triggers that particular event.
... to specify match patterns, first import the "matchpattern.jsm" module, then construct a matchpattern.
...if you supply an array of strings, then a url matches if it matches any of the strings.
Localization content best practices
it might be tempting to 'save time' by presenting this as the url of this feed %s and then is invalid; cannot be reached and cannot be parsed.
...tos-text = by proceeding you accept the {{link}} tos-link = terms of services and then replace {{link}} at run-time with the second string.
...privacy-link = privacy terms and then replace {{link}} at run-time with the link.
...if your changes are relevant only for english — for example, to correct a typographical error or to make letter case consistent — then there is generally no need to update the entity name.
Localizing without a specialized tool
to start, make sure you are in /path/to/your/working/directory/l10n-mozilla-1.9.2/x-testing and then, type the command mkdir /browser/chrome/browser now, step back out to the broader directory that contains both your l10n base (l10n-mozilla-1.9.2) and the en-us source code (mozilla-1.9.2).
...to do this, you first need to create the directory structure and then copy the file into it.
... type the command pwd again, make sure you are in /path/to/your/working/directory/l10n-mozilla-1.9.2/x-testing and then type the command mkdir /browser/chrome/browser now, copy the file by typing cp mozilla-1.9.2/browser/locales/chrome/browser/aboutcerterror.dtd l10n-mozilla-1.9.2/x-testing/browser/chrome/browser/aboutcerterror.dtd you should now see the aboutcerterror.dtd file in that newly created directory.
... each time you see a directory or set of sub-directories, you will need to run the mkdir command inside your locale directory and then copy the .dtd or .properties files into that directory.
Creating localizable web applications
then, use css to give a cue to the user that if she follows the link, she will be served english content.
...if you really have to use multiple strings, then make sure you're using comments or event contexts to let localizers know which part they're translating (cf.
...in general though, we should consider implementing such decorations as css images (background-image or ::after's/::before's content) and then select them with "html[dir="rtl"] > ...".
...you should then display the right icon depending on the locale.
Fonts for Mozilla 2.0's MathML engine
in general, if the necessary glyphs are not available on the system then mozilla tries to stretch symbols using scale transforms, but that may result in a less pleasant rendering.
...the fonts may be installed by extracting the font files (which have the .otf extension) from the zip archive, then following instructions for microsoft windows, or copying the files to a ~/library/fonts folder on mac os x, or to a ~/.fonts/ directory (which may need to be created) on unix/linux systems.
... reset old preferences if users have previously changed the "font.mathfont-family" preference for a previous version of mozilla, then it is best to reset this to the default value.
...mathml font selection with css you can get these fonts from the mathml-fonts add-on ; the xpi is just a zip archive that you can fetch and extract for example with the following command: wget https://addons.mozilla.org/firefox/downloads/latest/367848/addon-367848-latest.xpi -o mathml-fonts.zip; \ unzip mathml-fonts.zip -d mathml-fonts then copy the mathml-fonts/resource/ directory somewhere on your web site and ensure that the woff files are served with the correct mime type.
Mozilla Development Strategies
it's easier to do it right once, when your mind is in the problem, than to do it once quickly and then have to come back and do it again the right way.
...you don't want to have one tree, update it every morning, and then be stuck waiting for blockers to clear.
... for c++, use #define, #ifdef, #else and #endif for xul / js, and you're doing something major, add your new files to the tree and then have it be a simple jar.mn patch to enable it.
...obviously, when doing it the "right" way means re-engineering large amounts of code, then incremental work is better; it's a fine line.
Memory reporting
if d has data members that point to other objects, then d::sizeofexcludingthis must override b::sizeofexcludingthis.
... however, if d does not have any of its own fields that point to other objects, then d::sizeofexcludingthis is not necessary.
... alternatively, if d does have fields that point to other objects but you don't want to measure them because they're insignificant, then d::sizeofexcludingthis is again not necessary.
...in graph-like structures (where an object might be pointed to by more than one other object) it gets more difficult, and might even require some way to mark objects that have been counted (and then a way to unmark them once the measurement is complete).
A brief guide to Mozilla preferences
load user pref files, first prefs.js, then user.js .
... if the application encounters any error during loading of a default pref file, the application will issue a warning that a configuration file has failed to load and then quit.
...when the user then runs nightly, the preference now has the same value as the default, so is not written by nightly.
... when the user then runs developeredition again, the preference value will be false as no user preference was written by nightly.
NSPR's Position On Abrupt Thread Termination
the process abstraction is then responsible for closing all open files and reclaiming all storage that may have been allocated during the process' lifetime.
...in the natural course of events, these resources will be allocated by a thread, used for some period of time, and then freed as the stack unwinds.
...if they cannot, because of some state corruption, then they must assume that the corruption, like the state, is shared, and their only resource is for the process to terminate.
... to make this solution work requires that a function that encounters an error be designed such that it first repairs its immediate state, and then reports that error to its caller.
An overview of NSS Internals
the programmer's task is to initialize nss with the required parameters (such as a database), and nss will then transparently manage the database files.
...then you attempt to verify the signature found in (a) using the public key found in (b).
...create a context handle while providing all the parameters required for the operation, then call an “update” function multiple times to pass subsets of the input to nss.
... for example, if you wanted to create your own pair of keys and request a new certificate from a ca, you could use certutil to create an empty database, then use certutil to operate on your database and create a certificate request (which involves creating the desired key pair) and export it to a file, submit the request file to the ca, receive the file from the ca, and import the certificate into your database.
FIPS Mode - an explanation
the device must have a way for users to authenticate to it (to "login" to it), to prove to it that they are authorized to use the cryptographic engines and keys it contains.
... it may not do any cryptographic operations that involve the use of cryptographic keys, nor allow any of the keys or certificates it holds to be seen or used, except when a user has successfully authenticated to it.
... if users authenticate to it with a password, it must ensure that their passwords are strong passwords.
... one device does all the operations that may be done without needing to authenticate, and the other device stores the user's certificates and private keys and performs operations that use those private keys.
JSS Provider Notes
then you can sign your own jss jar file.
... translatekey() simply gets the encoded form of the given key and then tries to import it by calling generatepublic() or generateprivate().
...in this case, the key should be wrapped (encrypted with another key), and then the encrypted key might be extractable from the token.
...if that fails, it calls getencoded() on the source key, and then tries to create a new key on the target token from the encoded bits.
Mozilla-JSS JCA Provider notes
then you can sign your own jss jar file.
... translatekey() simply gets the encoded form of the given key and then tries to import it by calling generatepublic() or generateprivate().
...in this case, the key should be wrapped (encrypted with another key), and then the encrypted key might be extractable from the token.
...if that fails, it calls getencoded() on the source key, and then tries to create a new key on the target token from the encoded bits.
Enc Dec MAC Using Key Wrap CertReq PKCS10 CSR
*/ if (port_geterror() == sec_error_token_not_logged_in) { rv = pk11_authenticate(slot, pr_true, pwdata); if (rv != secsuccess) { pr_fprintf(pr_stderr, "could not authenticate to token %s : %s\n", pk11_gettokenname(slot), port_errortostring(rv)); rv = secfailure; goto cleanup; } rv = pk11_importcert(slot, cert, ck_invalid_handle, ...
... pr_fprintf(pr_stderr, "could not add certificate to token or database : %s\n", port_errortostring(rv)); rv = secfailure; goto cleanup; } } rv = cert_changecerttrust(handle, cert, trust); if (rv != secsuccess) { if (port_geterror() == sec_error_token_not_logged_in) { rv = pk11_authenticate(slot, pr_true, pwdata); if (rv != secsuccess) { pr_fprintf(pr_stderr, "could not authenticate to token %s : %s\n", pk11_gettokenname(slot), port_errortostring(rv)); rv = secfailure; goto cleanup; } rv = cert_changecerttrust(handle, cert, trust); } if (rv !
... break; case 't': truststr = strdup(optstate->value); break; case 'v': sigverify = pr_true; break; default: usage(progname); break; } } pl_destroyoptstate(optstate); if (cmd == unknown || !dbdir) usage(progname); /* open db for read/write and authenticate to it */ pr_init(pr_user_thread, pr_priority_normal, 0); initialized = pr_true; rv = nss_initreadwrite(dbdir); if (rv != secsuccess) { pr_fprintf(pr_stderr, "nss_initreadwrite failed\n"); goto cleanup; } pk11_setpasswordfunc(getmodulepassword); slot = pk11_getinternalkeyslot(); if (pk11_needlogin(slot)) { rv = pk11_authentic...
...ate(slot, pr_true, &pwdata); if (rv != secsuccess) { pr_fprintf(pr_stderr, "could not authenticate to token %s.\n", pk11_gettokenname(slot)); goto cleanup; } } switch (cmd) { case generate_csr: validategeneratecsrcommand(progname, dbdir, subject, subjectstr, certreqfilename); /* generate a csr */ rv = createcertrequest(slot, &pwdata, subject, certreqfilename, ascii); if (rv != secsuccess) { pr_fprintf(pr_stderr, "create certificate request: failed\n"); goto cleanup; } break; case add_cert_to_db: validateaddcerttodbcommand(progname, dbdir, nicknamestr, t...
sample2
*/ if (port_geterror() == sec_error_token_not_logged_in) { rv = pk11_authenticate(slot, pr_true, pwdata); if (rv != secsuccess) { pr_fprintf(pr_stderr, "could not authenticate to token %s : %s\n", pk11_gettokenname(slot), port_errortostring(rv)); rv = secfailure; goto cleanup; } rv = pk11_importcert(slot, cert, ck_invalid_handle, name, pr_false); } if (rv != secsuccess) { pr_fprintf(pr_stderr, "could not add certificate to token or database : %s\n", port_errortostring(rv...
...)); rv = secfailure; goto cleanup; } } rv = cert_changecerttrust(handle, cert, trust); if (rv != secsuccess) { if (port_geterror() == sec_error_token_not_logged_in) { rv = pk11_authenticate(slot, pr_true, pwdata); if (rv != secsuccess) { pr_fprintf(pr_stderr, "could not authenticate to token %s : %s\n", pk11_gettokenname(slot), port_errortostring(rv)); rv = secfailure; goto cleanup; } rv = cert_changecerttrust(handle, cert, trust); } if (rv != secsuccess) { pr_fprintf(pr_stderr, "could not change trust on certificate : %s\n", port_errortostring(rv)); rv = secfailure; goto cleanup; } } if (emailcert) { cert_savesmimeprofile(cert, null, pwdata); } cleanup: if (cert) { cert_destroycertificate (cert); } if (trust) { port_free(trust); } if (certder.data) { port_free(certder.data); } return rv; } /*...
...up(optstate->value); break; case 'x': selfsign = pr_true; break; case 'm': serialnumberstr = strdup(optstate->value); serialnumber = atoi(serialnumberstr); break; case 't': truststr = strdup(optstate->value); break; case 'v': sigverify = pr_true; break; default: usage(progname); break; } } pl_destroyoptstate(optstate); if (cmd == unknown || !dbdir) usage(progname); /* open db for read/write and authenticate to it */ pr_init(pr_user_thread, pr_priority_normal, 0); initialized = pr_true; rv = nss_initreadwrite(dbdir); if (rv != secsuccess) { pr_fprintf(pr_stderr, "nss_initreadwrite failed\n"); goto cleanup; } pk11_setpasswordfunc(getmodulepassword); slot = pk11_getinternalkeyslot(); if (pk11_needlogin(slot)) { rv = pk11_authenticate(slot, pr_true, &pwdata); if (rv != secsuccess) { pr_fprintf(pr_...
...stderr, "could not authenticate to token %s.\n", pk11_gettokenname(slot)); goto cleanup; } } switch (cmd) { case generate_csr: validategeneratecsrcommand(progname, dbdir, subject, subjectstr, certreqfilename); /* generate a csr */ rv = createcertrequest(slot, &pwdata, subject, certreqfilename, ascii); if (rv != secsuccess) { pr_fprintf(pr_stderr, "create certificate request: failed\n"); goto cleanup; } break; case add_cert_to_db: validateaddcerttodbcommand(progname, dbdir, nicknamestr, truststr, certfilename, certreqfilename, issuernamestr, serialnumberstr, selfsign); /* add cert to database */ rv = addcertificatetodb(slot, &pwdata, certreqfilename, certfilename, issuernamestr, certhandle, nicknamestr, truststr, serialnumber, selfsign, ascii); if (rv != secsuccess) { pr_fprintf(pr_stderr, "add...
Python binding for NSS
class names always begin with a upper case letter and are then followed by a mix of lower and upper case letters, a upper case letter is used to separate words.
...the beast cve fix in nss causes only one octet to be sent in the first socket packet and then the remaining data is sent normally, this is known as 1/n-1 record splitting.
... the example and test ssl code sent short messages and then did a sock.recv(1024).
... the following classes were replaced signaturealgorithm replaced by new class algorithmid the following classes were added algorithmid pkcs12decodeitem pkcs12decoder the following class methods were added pk11slot.authenticate() pk11slot.get_disabled_reason() pk11slot.has_protected_authentication_path() pk11slot.has_root_certs() pk11slot.is_disabled() pk11slot.is_friendly() pk11slot.is_internal() pk11slot.is_logged_in() pk11slot.is_removable() pk11slot.logout() pk11slot.need_login() pk11slot.need_user_init() pk11slot.user_disable() pk11slot.user_ena...
Necko walkthrough
receive response get a callback to each of these: nsistreamlistener::onstartrequest (header info) nsistreamlistener::ondataavailable (data in single or multiple chunks) nsistreamlistener::onstoprequest (no more data from http) this all happens on the main thread, in a non-blocking fashion: make your request on the main thread, then carry on and get the async response later, also on the main thread.
...then in necko http code (still on the main thread for now): nshttpchannel::asyncopen nshttpchannel::beginconnect() creates nshttpconnectioninfo object for the channel checks if we're proxying or not fires off the dns prefetch request (dispatched to dns thread pool) some other things nshttpchannel::connect might to a speculativeconnect (pre open tcp socket) nshttpchannel::continueconnect some cache stuff nshttpchannel::setuptransaction creates new nshttptransaction, and inits it with mrequesthead (the request headers) and muploadstream (which was created from the request data in channel setup) gets an nsiasynci...
...hostname and port) from the transaction, and then gets or creates a connection entry from the connection table, an nsclasshashtable<nscstringhashkey, nsconnectionentry> called mct in nshttpconnectionmgr.
... if a connection entry already exists matching the required conn info, then that one will be used; otherwise a new one is created (makenewconnection - creates socket etc.).
GC Rooting Guide
then ~eventlogger will fire and trigger a gc, invalidating that unrooted stack/register pointer.
...the usual way is to define a void trace(jstracer* trc, const char* name) method on the class -- which is already enough be able to create a js::rooted<yourstruct> on the stack -- and then arrange for it to be called during tracing.
...static void trace(jstracer* trc, jsobject* obj) { myclass* mine = static_cast<myclass*>(obj->getprivate()); mine->trace(trc, "myclass private field"); } } class myclass { heap<jsstring*> str; public: void trace(jstracer* trc, const char* name) { js::traceedge(trc, &str, "my string"); } } if a pointer to your structure is stored in some other structure, then its trace() method should invoke yours: struct myowningstruct { myclass* mything; void trace(jstracer* trc, const char* name) { if (mything) mything->trace(trc, "my thing"); } } if the toplevel structure is not stored in a jsobject, then how it gets traced depends on why it should be alive.
...o use js::persistentrooted (usable on anything with a trace method with the appropriate signature): js::persistentrooted<myowningstruct> immortalstruct; but note that js::persistentrooted in a struct or class is a rather dangerous thing to use -- it will keep a gc thing alive, and most gc things end up keeping their global alive, so if your class/struct is reachable in any way from that global, then nothing will ever be cleaned up by the gc.
Invariants
then cx->compartment == obj->compartment().
... if !js_isrunning(cx) && cx->globalobject == null, then cx->compartment == cx->runtime->defaultcompartment.
... if it cannot be statically proven that a name always refers to a specific variable (meaning either a parameter or a variable introduced by var/let/function/const) in the program, then a name op must be emitted.
...the function can be called after control exits that enclosing scope) then upvar instructions cannot be used for that nameexpression.
JS_ConstructObject
the preferred alternative is to save a copy of the constructor function for the class, then to call it using js_new.
... create a new object of the specified class, with the specified prototype and parent, then invokes a constructor function to initialize the new object.
... description js_constructobject creates a new object of the specified class, with the specified prototype and parent, then invokes a constructor function to initialize the new object.
... roughly speaking, we use parent or cx to find a global object, and then find clasp's constructor in that global object.
JS_GetGCParameter
when the gc is in "high frequency" mode (see above) then, the heap will be allowed to grow between collections according to these four parameters.
... additionally if a zone expands beyond the threshold without this factor, then it will be collected non-incrementally jsgc_allocation_threshold_factor_avoid_interrupt / "allocationthresholdfactoravoidinterrupt" jsgc_min_empty_chunk_count / "minemptychunkcount" we try to keep at least this many unused chunks in the free chunk pool at all times, even after a shrinking gc.
... jsgc_pretenure_threshold / "pretenurethreshold" if this percentage of the nursery is tenured and the nursery is at least 4mb, then process object groups to look for pretenuring candidates.
... jsgc_pretenure_group_threshold / "pretenuregroupthreshold" if more than this number of objects in a given object group are tenured, then pretenruing will be enabled for new objects in this group.
JS_InitClass
so, for example, if this object is js_getglobalobject(cx), then javascript code will be able to see the new class as a global name.
...if constructor is null, then static_ps and static_fs must also be null.
...if you pass null as the constructor parameter, then a constructor is not built, and you cannot specify static properties and functions for the class.
...if you provide a constructor for the class, then you should also pass an object to parent_proto.
Setting up an update server
open them and find this line: #defines['disable_updater_authenticode_check'] = true.
...to move the installation, first call ./mach package, then you can either copy <obj dir>/dist/firefox to a new "install directory" elsewhere, or run the installer located in the <obj dir>/dist/install/sea.
...then run these commands, substituting <obj dir>, <mar output path>, <version> and <channel> appropriately: ./mach package touch "<obj dir>/dist/firefox/precomplete" mar="<obj dir>/dist/host/bin/mar.exe" moz_product_version=<version> mar_channel_id=<channel> ./tools/update-packaging/make_full_update.sh <mar output path> "<obj dir>/dist/firefox" for a local build, <channel> can be default, and <versi...
...then, create a file within called update.xml with these contents, replacing <mar name>, <hash> and <size> with the mar's filename, its sha512 hash, and its file size in bytes.
Using the Places keywords API
placesutils.keywords.insert({ keyword: "my_keyword", url: "http://www.example.com/" postdata: "post+data=1&test=2" }).then(() => { /* success */ }, e => { /* failure */ }); note that setting an already existing keyword to a different url, will silently update the existing keyword to the new url.
... placesutils.keywords.fetch("my_keyword").then(entry => { /* entry is either null, or a keyword entry */ }, e => { /* failure */}); fetching entries by url the fetch() method also accepts a keyword entry, where it's possible to specify keyword, url, or both.
... placesutils.keywords.fetch({ url: "http://www.example.com/" }, entry => { /* invoked for each found keyword entry */ }) .then(oneentry => { /* oneentry is either null, or one of the keyword entries */ }, e => { /* failure */}); removing a keyword the remove() method accepts a keyword string.
... placesutils.keywords.remove("my_keyword").then(() => { /* success */ }, e => { /* failure */ }); ...
XPCOM changes in Gecko 2.0
previously, whenever gecko detected that the application version had changed, or one or more extensions was added, removed, enabled, or disabled, it was necessary to throw away all existing component registrations, then restart the application (what we call the "extension manager restart") during its startup process.
...in theory, this is invisible to the user, but it's a costly process, since every component needs to be loaded and executed, then unloaded, then reloaded again during the restart.
...this gets enough of xpcom loaded and running that we can then load the extension manager and perform the necessary installing, uninstalling, and updating of any installed extensions.
... once that's done, the extensions can then be loaded by simply reading their manifests, loading their components, and continuing the startup process, all without having to restart the browser.
Building the WebLock UI
if the weblock component is being installed in mozilla or another gecko-based browser, then this third section shows you how to create the entry point in the browser for controlling the web locking.
...a boolean wlocked variable can do this: // initialize the wlocked variable as unlocked var wlocked = 0; then the functions that get called from the interface and call through to the lock and unlock methods of the weblock component must also adjust this variable accordingly: function wlock() { // check to see if locking is on or off weblock.lock(); wlocked = 1; } function wunlock() { // check to see if locking is on or off weblock.unlock(); wlocked = 0; } an important preliminary of these...
...the "shell" for the xul file, then, looks like this: <?xml version="1.0"?> <?xml-stylesheet href="chrome://global/skin/" type="text/css"?> <dialog id="weblock_ui" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul" title="web lock manager" persist="screenx screeny" screenx="24" screeny="24"> </dialog> note that this part of the xul file also contains a stylesheet declaration, ...
...once it's installed and registered, the weblock component itself is ready to go: xpcom finds it and adds it to the list of registered components, and then weblock observes the xpcom startup event and initializes itself.
Finishing the Component
(for weblock, all you need are the headers for nsicontentpolicy and the nsicontentpolicy.idl.) then, using the same steps you used to create the weblock.h, create a header from this idl file using the xpidl compiler.
...the weblock class will then support four interfaces: nsisupports, nsiobserver, nsicontentpolicy, and iweblock.
...if uris of this kind are blocked, then gecko will not be able to start up, so we'll restrict the content policy to the http and ftp protocols.
...if these two strings do not match, then the component returns return false and blocks the load.
IAccessibleTable
in this case iaccessible2.indexinparent() will return the child index which then can be used when calling rowindex() and columnindex().
...ats should first test for the presence of the "table-cell-index" attribute and if it is not present then iaccessible2.indexinparent() can be used as in the typical case where cells are direct children of the table.
...accessible if both row and column index are valid then the corresponding accessible object is returned that represents the requested cell regardless of whether the cell is currently visible (on the screen).
...[propget] hresult caption( [out] iunknown accessible ); parameters accessible if the table has a caption then a reference to it is returned, else a null pointer is returned.
IAccessibleTable2
[propget] hresult caption( [out] iunknown accessible ); parameters accessible if the table has a caption then a reference to it is returned, else a null pointer is returned.
...cell if both row and column index are valid then the corresponding accessible object is returned that represents the requested cell regardless of whether the cell is currently visible (on the screen).
...then the entire column of cells for the specified column is selected.
...then the entire row of cells for the specified row is selected.
IAccessibleText
if the text() is implemented as a tree of text() objects with embed characters in higher levels representing substrings of child text() objects and the caret is in one of the child text() objects, then the offset in the higher level text() object would be at the embed character representing child text() object that contains the caret.
...three" and a child text() object containing "two" and if the caret is in the descendant object just before the 'o' in "two", then: the caretoffset for the "one ?
...for example, if text() type is ::ia2_text_boundary_word, then the complete word that is closest to and located after offset is returned.
...for example, if text() type is ::ia2_text_boundary_word, then the complete word that is closest to and located before offset is returned.
nsIClassInfo
if the flags attribute has the singleton bit set, then the value of this attribute specifies a classid through which this class can be accessed as a service using nsiservicemanager.getservice().
...if the flags attribute has the singleton bit set, then the value of this attribute specifies a classid through which this class can be accessed as a service using nsiservicemanager.getservice().
...if the flags attribute has the singleton bit set, then the value of this attribute specifies a contractid through which this class may be accessed as a service using nsiservicemanager.getservicebycontractid().
... if this method is not supported by an implementation, then it should return 0 for count and null for array.
nsICryptoHash
acstring finish( in prbool aascii ); parameters aascii if true then the returned value is a base-64 encoded string.
... if false, then the returned value is binary data.
...you will need to create an instance of nsicryptohash, open an input stream from a file, and then update the hash with the file.
... the example below shows how to convert a string to bytes in the utf-8 encoding, and then compute the sha256 hash of it.
nsILoadGroup
if the default load request is null, then the group's load flags are not changed.
...if this is a foreground request then the groupobserver's onstartrequest will be called.
... if the request is the default load request or if the default load request is null, then the load group will inherit its load flags from the request.
...if this is a foreground request then the groupobserver's onstoprequest will be called.
nsIMsgMessageService
you always can use streammessage to get the eml string representation of the message and then write it using file i/o methods.
...if streaming over the network is required and this is true, then an exception is thrown.
... note if we're offline, then even if alocalonly is false, we won't stream over the network return the url that gets run, if any ismsginmemcache() determines whether a message is in the memory cache.
... boolean ismsginmemcache(in nsiuri aurl, in nsimsgfolder afolder, out nsicacheentrydescriptor acacheentry); parameters aurl the url of the message, possibly with an appropriate command in it afolder the folder this message is in acacheentry if a cache entry is found, then a pointer to it return true if the message is in mem cache; false if it is not.
nsIPromptService
upon return, if the user pressed ok, then this parameter contains a newly allocated string value.
...upon return, if the user pressed ok, then this parameter contains a newly allocated string value.
...upon return, if the user pressed ok, then this parameter contains a newly allocated string value.
...upon return, if the user pressed ok, then this parameter contains a newly allocated string value.
nsITransactionManager
a value of zero means the transaction manager will execute each transaction, then immediately release all references it has to the transaction without pushing it on the undo stack.
...dotransaction() calls a transaction's nsitransaction.dotransaction() method, then pushes it on the undo stack.
...redotransaction() pops the topmost transaction on the redo stack, calls it's nsitransaction.redotransaction() method, then pushes it on the undo stack.
... undotransaction() pops the topmost transaction on the undo stack, calls it's nsitransaction.undotransaction() method, then pushes it on the redo stack.
nsIWebNavigation
for http and ftp urls and possibly others, characters above u+007f will be converted to utf-8 and then url- escaped per the rules of rfc 2396.
...if this argument is null, then the referring uri will be inferred internally.
... postdata if the uri corresponds to a http request, then this stream is appended directly to the http request headers.
... headers if the uri corresponds to a http request, then any http headers contained in this stream are set on the http request.
nsIXPConnect
if this parameter is given then afilenameflags will not be calculated and will be assumed to be 0 unless another value is given.
... if this parameter is null then afilenameflags will be calculated and the value of that argument will be ignored.
...if you do not pass init_js_standard_classes, then acomobj must implement nsixpcscriptable so it can resolve the standard classes when asked by the js engine.
...if aallowwrapper, then the returned value will be wrapped in the proper type of security wrapper on top of the xpcwrappednative (if needed).
nsIXmlRpcClient
last changed in gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0) inherits from: nsisupports method overview void init(in string serverurl); void setauthentication(in string username, in string password); void clearauthentication(in string username, in string password); void setencoding(in string encoding); void setencoding(in unsigned long type, out nsiidref uuid, out nsqiresult result); void asynccall (in nsixmlrpcclientlistener listener, in nsisupports ctxt, in string methodname, in nsisupports arguments, in pruint32 count); attributes attribute type description serverurl readonly nsi...
...call this before using this object void getdata ( in string serverurl ) ; parameters serverurl url of server side object on which methods should be called setauthentication() set authentication info if needed.
... both parameters must be specified for authentication to be enabled void setauthentication ( in string username, in string password ) ; parameters username username to be used if asked to authenticate password password to be used if asked to authenticate clearauthentication() clear authentication info void setauthentication ( in string username, in string password ) ; parameters username password setencoding() set character encoding.
... the default charset if this function is not called is "utf-8" void setauthentication ( in string encoding ) ; parameters encoding encoding charset to be used asynccall() call remote method methodname asynchronously with given arguments.
Mail event system
if the object wants to know about all notifications on all folders, then it should register with the mail session.
...the mail session receives all notifications from all folders, and then forwards it on to any nsifolderlisteners that have registered themselves.
... notifypropertychanged then broadcasts this event to the mail session: mailsession->onintpropertychanged(this, ktotalmessagesatom, 4, 5); the mail session rebroadcasts this information to each of the global listeners that has been registered with it.
...then we could // verify that our listener fired by checking if listenerhasfired and // totalmessageslistenerhasfired are true // this is left as an exercise for the reader.
Standard OS Libraries
so i went to the msdn winapi index page and then went to the "cursors" category and came across getcursorpos.
... i then searched it on msdn and saw that it needed the user32.dll.
...if you would like to do stuff off of the main thread, in chromeworker's, then you should use xcb.
... core foundation to learn about all the mac os x apis and which library file you will need to call, go to the mac developer library website and find the function, then scroll down to "declared in" section, and find which framework contains the header file.
Drawing and Event Handling - Plugins
however, for the plug-in to draw at any other time, for example, to highlight on a mouse-down event or draw animation at idle time, it must save the current setting of the port, set up its drawing environment as appropriate, draw, and then restore the port to the previous settings.
...the plug-in can then show the drag highlight and handle drops when they occur within the instance rectangle.
...the plug-in can then subclass the window to receive any events it needs.
...the plug-in can then draw the part of the update region that corresponds to its opaque areas.
Debugging service workers - Firefox Developer Tools
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.
...from updating your service worker: if your service worker has previously been installed, but then a new version of the worker is available on refresh or page load, the new version is installed in the background, but not yet activated.
...when you fill up the cache with assets, but then want to alter the behavior slightly, you previously had to manually write code to empty the cache, and then fill it again.
... you can also click on one of the individual items stored in the cache, then right/ctrl click on it to get options for deleting just that item, or every item in the cache.
Debugger.Script - Firefox Developer Tools
if this debugger.script’s source property is non-null, then this is equal to source.url.
...if a source line numberline has no code, thenl has noline property.
... if there is code forline, then l[line] is an array of offsets of byte code instructions that are entry points to that line.
... if this script has no coverage, or if it is not instrumented, then this function will return null.
Tutorial: Set a breakpoint - Firefox Developer Tools
we use debugger to set a breakpoint in a function, and then evaluate an expression whenever it is hit.
... save the following text to an html file: <div onclick="report('the best div');">click me!</div> <div onclick="report('another great div');">or me!</div> <script> function report(what) { console.log('clicked: ' + what); } </script> visit the html file in your browser, and open the browser content toolbox by opening the firefox menu, choosing “web developer”, and then “browser content toolbox”.
...then it evaluates the expression what in the given stack frame, and logs its result.
...re-running the code in the scratchpad creates a fresh debugger instance, adds the same web page as its debuggee, and then sets a new breakpoint.
DevTools API - Firefox Developer Tools
return this.dosomethingasynchronous() .then(() => this); }, destroy: function() { // synchronous destruction.
... return this.destroysomethingasynchronosly() .then(() => console.log("destroyed")); }, handleclick: function(event) { console.log("clicked", event.originaltarget); }, }; eventemitter eventemitter is an interface many developer tool classes and objects implement and use to notify others about changes in their internal state.
... return value: a promise that is fulfilled with the first extra argument for the event when then event is emitted.
...gdevtools.once("netmonitor-init").then(toolbox => { // note that the second argument is not available here.
Examine and edit CSS - Firefox Developer Tools
if the element has a display: grid declaration, then it gets a grid icon next to it, like this: .
...that means that if you are using a css preprocessor that has support for source maps, and you've enabled source map support in the style editor settings, then the link will take you to the original source, not the generated css.
... overridden declarations if a css declaration is overridden by some other css rule with a greater weight, then the declaration is shown with a line through it.
...if you enter var( into a property value and then type a dash (-), any variables you have declared in your css will then appear in an autocomplete list, which shows a color swatch so you can see exactly what color each variable choice is storing (bug 1451211).
Style Editor - Firefox Developer Tools
the media sidebar works especially well with responsive design view for creating and debugging responsive layouts: from firefox 46 onwards, if an @media rule contains a screen size in a condition, then it is made clickable: clicking it then resizes the screen to that size using the responsive design view: creating and importing style sheets you can create a new style sheet by clicking the new button in the toolbar.
... then you can just start entering css into the new editor and watch as the new styles are applied in real time just like changes to the other sheets.
...so you'd need to edit the generated css, then manually work out how to reapply that to the original source.
... this means that if you use, for example, sass, then the style editor will show you, and allow you to edit, sass files, rather than the css that is generated from them: for this to work, you must: use a css preprocessor that understands the source map revision 3 proposal.
about:debugging - Firefox Developer Tools
your device should show a popup to authorize your computer to connect to it — accept this and then click the refresh devices button again.
... to start a debugging session, first open the page that you wish to debug and then click connect next to the device name to open a connection to it.
...the temporary extension is then displayed under the temporary extensions header.
... if you change files that are loaded on demand, like content scripts or popups, then changes you make are picked up automatically, and you'll see them the next time the content script is loaded or the popup is shown.
AbstractRange - Web APIs
the end point is set to be the middle of the first child of the span, and then the range is used to copy the contents of the range.
...d work: let r = document.createrange(); let startnode = document.queryselector("section h2").childnodes[0]; r.setstart(startnode, 11); let endnode = document.queryselector("#entry1 p em").childnodes[0]; r.setend(endnode, 2); let fragment = r.clonecontents(); here an interesting problem arises—we are capturing content from multiple nodes located at different levels of the dom hierarchy, and then only part of one of them.
... the contents of the text nodes are then determined by the offsets into those text nodes given when calling setstart() and setend().
... we then finish up by calling clonecontents() on the range to create a new documentfragment object which contains the portion of the document encompassed by the range.
AesGcmParams - Web APIs
this contains additional data that will not be encrypted but will be authenticated along with the encrypted data.
... if additionaldata is given here then the same data must be given in the corresponding call to decrypt(): if the data given to the decrypt() call does not match the original data, the decryption will throw an exception.
... this gives you a way to authenticate associated data without having to encrypt it.
...this determines the size in bits of the authentication tag generated in the encryption operation and used for authentication in the corresponding decryption.
Body.arrayBuffer() - Web APIs
WebAPIBodyarrayBuffer
syntax response.arraybuffer().then(function(buffer) { // do something with buffer }); parameters none.
...if you need to play ogg during downloading (stream it) - consider htmlaudioelement: new audio("music.ogg").play(); in getdata() we create a new request using the request() constructor, then use it to fetch an ogg music track.
...when the fetch is successful, we read an arraybuffer out of the response using arraybuffer(), decode the audio data using audiocontext.decodeaudiodata, set the decoded data as the audio buffer source's buffer (source.buffer), then connect the source up to the audiocontext.destination.
... once getdata() has finished running, we start the audio source playing with start(0), then disable the play button so it can't be clicked again when it is already playing (this would cause an error.) function getdata() { source = audioctx.createbuffersource(); var myrequest = new request('viper.ogg'); fetch(myrequest).then(function(response) { return response.arraybuffer(); }).then(function(buffer) { audioctx.decodeaudiodata(buffer, function(decodeddata) { source.buffer = decodeddata; source.connect(audioctx.destination); }); }); }; // wire up buttons to stop and play audio play.onclick = function() { getdata(); source.start(0); play.setattribute('disabled', 'disabled'); } reading files the response() constructor accepts files and blobs, so it m...
Body.blob() - Web APIs
WebAPIBodyblob
syntax response.blob().then(function(myblob) { // do something with myblob }); parameters none.
... example in our fetch request example (run fetch request live), we create a new request using the request() constructor, then use it to fetch a jpg.
... when the fetch is successful, we read a blob out of the response using blob(), put it into an object url using url.createobjecturl, and then set that url as the source of an <img> element to display the image.
... var myimage = document.queryselector('img'); var myrequest = new request('flowers.jpg'); fetch(myrequest) .then(response => response.blob()) .then(function(myblob) { var objecturl = url.createobjecturl(myblob); myimage.src = objecturl; }); specifications specification status comment fetchthe definition of 'blob()' in that specification.
Body.json() - Web APIs
WebAPIBodyjson
syntax response.json().then(data => { // do something with your data }); parameters none.
... example in our fetch json example (run fetch json live), we create a new request using the request() constructor, then use it to fetch a .json file.
... when the fetch is successful, we read and parse the data using json(), then read values out of the resulting objects as you'd expect and insert them into list items to display our product data.
... const mylist = document.queryselector('ul'); const myrequest = new request('products.json'); fetch(myrequest) .then(response => response.json()) .then(data => { for (const product of data.products) { let listitem = document.createelement('li'); listitem.appendchild( document.createelement('strong') ).textcontent = product.name; listitem.append( ` can be found in ${ product.location }.
Body.text() - Web APIs
WebAPIBodytext
syntax response.text().then(function (text) { // do something with the text response }); parameters none.
... when getdata() is run, we create a new request using the request() constructor, then use it to fetch a specific .txt file.
... when the fetch is successful, we read a usvstring (text) object out of the response using text(), then set the innerhtml of the <article> element equal to the text object.
...cle = document.queryselector('article'); let mylinks = document.queryselectorall('ul a'); for(let i = 0; i <= mylinks.length-1; i++) { mylinks[i].onclick = function(e) { e.preventdefault(); let linkdata = e.target.getattribute('data-page'); getdata(linkdata); } }; function getdata(pageid) { console.log(pageid); var myrequest = new request(pageid + '.txt'); fetch(myrequest).then(function(response) { return response.text().then(function(text) { myarticle.innerhtml = text; }); }); } specifications specification status comment fetchthe definition of 'text()' in that specification.
CSS Painting API - Web APIs
you can then apply these values to properties like background-image to set complex custom backgrounds on an element.
... examples to draw directly into an element's background using javascript in our css, we define a paint worklet using the registerpaint() function, tell the document to include the worklet using the paintworklet addmodule() method, then include the image we created using the css paint() function.
... i * 2; ctx.beginpath(); ctx.moveto( blockwidth + (start * 10) + 10, y); ctx.lineto( blockwidth + (start * 10) + 20, y); ctx.lineto( blockwidth + (start * 10) + 20 + blockheight, blockheight); ctx.lineto( blockwidth + (start * 10) + 10 + blockheight, blockheight); ctx.lineto( blockwidth + (start * 10) + 10, y); ctx.closepath(); ctx.fill(); ctx.stroke(); } } }); we then include the paintworklet: <ul> <li>item 1</li> <li>item 2</li> <li>item 3</li> <li>item 4</li> <li>item 5</li> <li>item 6</li> <li>item 7</li> <li>item 8</li> <li>item 9</li> <li>item 10</li> <li>item 11</li> <li>item 12</li> <li>item 13</li> <li>item 14</li> <li>item 15</li> <li>item 16</li> <li>item 17</li> <li>item 18</li...
...> <li>item 19</li> <li>item 20</li> </ul> css.paintworklet.addmodule('https://mdn.github.io/houdini-examples/csspaint/intro/worklets/hilite.js'); then we can use the <image> with the css paint() function: li { --boxcolor: hsla(55, 90%, 60%, 1.0); background-image: paint(hollowhighlights, stroke, 2px); } li:nth-of-type(3n) { --boxcolor: hsla(155, 90%, 60%, 1.0); background-image: paint(hollowhighlights, filled, 3px); } li:nth-of-type(3n+1) { --boxcolor: hsla(255, 90%, 60%, 1.0); background-image: paint(hollowhighlights, stroke, 1px); } we've included a custom property in the selector block defining a boxcolor.
Cache.addAll() - Web APIs
WebAPICacheaddAll
syntax cache.addall(requests[]).then(function() { // requests have been added to the cache }); parameters requests an array of string urls that you want to be fetched and added to the cache.
... the response status is not in the 200 range (i.e., not a successful response.) this occurs if the request does not return successfully, but also if the request is a cross-origin no-cors request (in which case the reported status is always 0.) examples this code block waits for an installevent to fire, then runs waituntil() to handle the install process for the app.
... this consists of calling cachestorage.open to create a new cache, then using addall() to add a series of assets to it.
... this.addeventlistener('install', function(event) { event.waituntil( caches.open('v1').then(function(cache) { return cache.addall([ '/sw-test/', '/sw-test/index.html', '/sw-test/style.css', '/sw-test/app.js', '/sw-test/image-list.js', '/sw-test/star-wars-logo.jpg', '/sw-test/gallery/', '/sw-test/gallery/bountyhunters.jpg', '/sw-test/gallery/mylittlevader.jpg', '/sw-test/gallery/snowtroopers.jpg' ]); }) ); }); specifications specification status comment service workersthe definition of 'cache: addall' in that specification.
Cache.put() - Web APIs
WebAPICacheput
often, you will just want to fetch() one or more requests, then add the result straight to your cache.
... fetch(url).then(function(response) { if (!response.ok) { throw new typeerror('bad response status'); } return cache.put(url, response); }) note: put() will overwrite any key/value pair previously stored in the cache that matches the request.
... syntax cache.put(request, response).then(function() { // request/response pair has been added to the cache }); parameters request the request object or url that you want to add to the cache.
... var response; var cachedresponse = caches.match(event.request).catch(function() { return fetch(event.request); }).then(function(r) { response = r; caches.open('v1').then(function(cache) { cache.put(event.request, response); }); return response.clone(); }).catch(function() { return caches.match('/sw-test/gallery/mylittlevader.jpg'); }); specifications specification status comment service workersthe definition of 'cache: put' in that specification.
CacheStorage.delete() - Web APIs
syntax caches.delete(cachename).then(function(boolean) { // your cache is now deleted }); parameters cachename the name of the cache you want to delete.
... examples in this code snippet we wait for an activate event, and then run a waituntil() block that clears up any old, unused caches before a new service worker is activated.
...we return the keys of the caches in the cachestorage object using cachestorage.keys, then check each key to see if it is in the array.
... this.addeventlistener('activate', function(event) { var cachestokeep = ['v2']; event.waituntil( caches.keys().then(function(keylist) { return promise.all(keylist.map(function(key) { if (cachestokeep.indexof(key) === -1) { return caches.delete(key); } })); }) ); }); specifications specification status comment service workersthe definition of 'cachestorage: delete' in that specification.
CacheStorage.keys() - Web APIs
WebAPICacheStoragekeys
syntax caches.keys().then(function(keylist) { //do something with your keylist }); parameters none.
... examples in this code snippet we wait for an activate event, and then run a waituntil() block that clears up any old, unused caches before a new service worker is activated.
...we return the keys of the caches in the cachestorage object using keys(), then check each key to see if it is in the whitelist.
... then.addeventlistener('activate', function(event) { var cachewhitelist = ['v2']; event.waituntil( caches.keys().then(function(keylist) { return promise.all(keylist.map(function(key) { if (cachewhitelist.indexof(key) === -1) { return caches.delete(key); } }); }) ); }); specifications specification status comment service workersthe definition of 'cachestorage: keys' in that specification.
CacheStorage.open() - Web APIs
WebAPICacheStorageopen
syntax caches.open(cachename).then(function(cache) { // do something with your cache }); parameters cachename the name of the cache you want to open.
...here we wait for an installevent to fire, then runs waituntil() to handle the install process for the app.
... this consists of calling cachestorage.open() to create a new cache, then using cache.addall() to add a series of assets to it.
... self.addeventlistener('install', function(event) { event.waituntil( caches.open('v1').then(function(cache) { return cache.addall([ '/sw-test/', '/sw-test/index.html', '/sw-test/style.css', '/sw-test/app.js', '/sw-test/image-list.js', '/sw-test/star-wars-logo.jpg', '/sw-test/gallery/bountyhunters.jpg', '/sw-test/gallery/mylittlevader.jpg', '/sw-test/gallery/snowtroopers.jpg' ]); }) ); specifications specification status comment service workersthe definition of 'cachestorage: open' in that specification.
Pixel manipulation with canvas - Web APIs
pixels then proceed from left to right, then downward, throughout the array.
...for this, we need the current position of the mouse with layerx and layery, then we look up the pixel data on that position in the pixel array that getimagedata() provides us.
... for example, to paint the entire image represented by myimagedata to the top left corner of the context, you can simply do the following: ctx.putimagedata(myimagedata, 0, 0); grayscaling and inverting colors in this example we iterate over all pixels to change their values, then we put the modified pixel array back to the canvas using putimagedata().
...then we copy that one over to another canvas and resize the image to the size we want it to.
Console.table() - Web APIs
WebAPIConsoletable
if data is an array, then its values will be the array indices.
... if data is an object, then its values will be the property names.
...n array of strings console.table(["apples", "oranges", "bananas"]); // an object whose properties are strings function person(firstname, lastname) { this.firstname = firstname; this.lastname = lastname; } var me = new person("john", "smith"); console.table(me); collections of compound types if the elements in the array, or properties in the object, are themselves arrays or objects, then their elements or properties are enumerated in the row, one per column: // an array of arrays var people = [["john", "smith"], ["jane", "doe"], ["emily", "jones"]] console.table(people); // an array of objects function person(firstname, lastname) { this.firstname = firstname; this.lastname = lastname; } var john = new person("john", "smith"); var jane = new person("jane", "doe"); var e...
...mily = new person("emily", "jones"); console.table([john, jane, emily]); note that if the array contains objects, then the columns are labeled with the property name.
DOMMatrixReadOnly.scale() - Web APIs
les this svg contains three squares, one red, one blue, and one green, each positioned at the document origin: <svg width="250" height="250" viewbox="0 0 25 25"> <rect width="25" height="25" fill="red" /> <rect id="transformed" width="25" height="25" fill="blue" /> <rect id="transformedorigin" width="25" height="25" fill="green" /> </svg> this javascript first creates an identity matrix, then uses the scale() method to create a new matrix with a single parameter.
... we test if the browser supports a six parameter scale() method by creating a new matrix using three parameters and observing it's is2d property — if this is false then the third parameter has been accepted by the browser as a scalez parameter, making this a 3d matrix.
... we then create a new matrix scaled about a given origin, using either three or six parameters depending on the browser support.
... these new matrices are then applied to the blue and green squares as a transform, changing their dimensions and position.
FileSystemDirectoryEntry.getDirectory() - Web APIs
true false path exists the existing file or directory is removed and replaced with a new one, then the successcallback is called with a filesystemfileentry or a filesystemdirectoryentry, as appropriate.
... true false path doesn't exist the file or directory is created, then a filesystemfileentry or a filesystemdirectoryentry is passed to the successcallback, as appropriate.
... true true path doesn't exist the file or directory is created, then a filesystemfileentry or a filesystemdirectoryentry is passed to the successcallback, as appropriate.
... example in this example, a function is presented whose job it is to locate within a user's app data directory a json file containing a user dictionary for a specified language, then load that dictionary.
FileSystemDirectoryEntry.getFile() - Web APIs
true false path exists the existing file or directory is removed and replaced with a new one, then the successcallback is called with a filesystemfileentry or a filesystemdirectoryentry, as appropriate.
... true false path doesn't exist the file or directory is created, then a filesystemfileentry or a filesystemdirectoryentry is passed to the successcallback, as appropriate.
... true true path doesn't exist the file or directory is created, then a filesystemfileentry or a filesystemdirectoryentry is passed to the successcallback, as appropriate.
... example in this example, a function is presented whose job it is to locate within a user's app data directory a json file containing a user dictionary for a specified language, then load that dictionary.
Using FormData Objects - Web APIs
creating a formdata object from scratch you can build a formdata object yourself, instantiating it then appending fields to it by calling its append() method, like this: var formdata = new formdata(); formdata.append("username", "groucho"); formdata.append("accountnum", 123456); // number 123456 is immediately converted to a string "123456" // html file input, chosen by user formdata.append("userfile", fileinputelement.files[0]); // javascript file-like object var content = '<a id="a"><b id="b"...
... this example builds a formdata instance containing values for fields named "username", "accountnum", "userfile" and "webmasterfile", then uses the xmlhttprequest method send() to send the form's data.
...ddress:</label> <input type="email" autocomplete="on" autofocus name="userid" placeholder="email" required size="32" maxlength="64" /><br /> <label>custom file label:</label> <input type="text" name="filelabel" size="12" maxlength="32" /><br /> <label>file to stash:</label> <input type="file" name="file" required /> <input type="submit" value="stash the file!" /> </form> <div></div> then you can send it using code like the following: var form = document.forms.nameditem("fileinfo"); form.addeventlistener('submit', function(ev) { var ooutput = document.queryselector("div"), odata = new formdata(form); odata.append("customfield", "this is some extra data"); var oreq = new xmlhttprequest(); oreq.open("post", "stash.php", true); oreq.onload = function(oevent) { ...
... typically this is used as shown in our simple formdata event demo — in the javascript we reference a form: const formelem = document.queryselector('form'); in our submit event handler we use preventdefault to stop the default form submission, then invoke a formdata constructor to trigger the formdata event: formelem.addeventlistener('submit', (e) => { // on form submission, prevent default e.preventdefault(); // construct a formdata object, which fires the formdata event new formdata(formelem); }); when the formdata event fires we can access the formdata object using formdataevent.formdata, then do what we like with it (below we...
Using the Gamepad API - Web APIs
the navigator.getgamepads() method returns an array of all devices currently visible to the webpage, as gamepad objects (the first value is always null, so null will be returned if there are no gamepads connected.) this can then be used to get the same information.
...note that disconnecting a device and then connecting a new device may reuse the previous index.
...instead of constantly storing the gamepad's latest state in a variable it only stores a snapshot, so to do the same thing in chrome you have to keep polling it and then only use the gamepad object in code when it is available.
...in each execution of the loop we check if one of four buttons is being pressed; if so, we update the values of the a and b movement variables appropriately, then update the left and top properties, changing their values to the current values of a and b respectively.
HTML Drag and Drop API - Web APIs
a typical drag operation begins when a user selects a draggable element, drags the element to a droppable element, and then releases the dragged element.
... function dragstart_handler(ev) { // create an image and then use it for the drag image.
... typically, an application uses the getdata() method to retrieve drag items and then process them accordingly.
... the following example shows a drop handler getting the source element's id from the drag data, and then using the id to move the source element to the drop element: <script> function dragstart_handler(ev) { // add the target element's id to the data transfer object ev.datatransfer.setdata("application/my-app", ev.target.id); ev.datatransfer.dropeffect = "move"; } function dragover_handler(ev) { ev.preventdefault(); ev.datatransfer.dropeffect = "move" } function drop_handler(ev) { ev.preventdefault(); // get the id of the target and add the moved element to the target's dom const data = ev.datatransfer.getdata("application/my-app"); ev.target.appendchild(documen...
IDBIndex.get() - Web APIs
WebAPIIDBIndexget
if a value is found, then a structured clone of it is created and set as the result of the request object: this returns the record the key is associated with.
... example in the following example we open a transaction and an object store, then get the index lname from a simple contacts database.
... we then open a basic cursor on the index using idbindex.opencursor — this works the same as opening a cursor directly on an objectstore using idbobjectstore.opencursor except that the returned records are sorted based on the index, not the primary key.
... myindex.get('bungle') is then used to retrieve the record with an lname of bungle, and the result of that request is logged to the console when its success callback returns.
Browser storage limits and eviction criteria - Web APIs
so if your hard drive is 500 gb, then the total storage for a browser is 250 gb.
...if you had a really low memory situation where the global limit was, say, 8 mb, then the group limit would also be 8 mb.
... lru policy when the available disk space is filled up, the quota manager will start clearing out data based on an lru policy — the least recently used origin will be deleted first, then the next one, until the browser is no longer over the limit.
...these are then sorted according to "last access time." the least recently used origins are then deleted until there's enough space to fulfill the request that triggered this origin eviction.
MediaStreamTrackAudioSourceNode - Web APIs
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.
... next, we feed this source audio into a low pass biquadfilternode (which effectively serves as a bass booster), then a audiodestinationnode.
...ent.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 it var audioctx = new audiocontext(); var source = audioctx.createmediastreamsource(stream); // create a biquadfilt...
... biquadfilter.gain.value = range.value; // connect the audiobuffersourcenode to the gainnode // and the gainnode to the destination, so we can play the // music and adjust the volume using the mouse cursor source.connect(biquadfilter); biquadfilter.connect(audioctx.destination); // get new mouse pointer coordinates when mouse is moved // then set new gain value range.oninput = function() { biquadfilter.gain.value = range.value; } }) .catch(function(err) { console.log('the following gum error occured: ' + err); }); } else { console.log('getusermedia not supported on your browser!'); } // dump script to pre element pre.innerhtml = myscript.innerhtml; note: as a consequence of calli...
MediaStream Recording API - Web APIs
you can then process the data further or write it to file as desired.
...you can then examine that list and identify the potential input sources, and even filter the list based on desired criteria.
... in this code snippet, enumeratedevices() is used to examine the available input devices, locate those which are audio input devices, and create <option> elements that are then added to a <select> element representing an input source picker.
... 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 devices they wish to use.
Using the Notifications API - Web APIs
in its simplest form, we just include the following: notification.requestpermission().then(function(result) { console.log(result); }); this uses the promise-based version of the method.
...ion.permission === 'default') { notificationbtn.style.display = 'block'; } else { notificationbtn.style.display = 'none'; } } // let's check if the browser supports notifications if (!('notification' in window)) { console.log("this browser does not support notifications."); } else { if(checknotificationpromise()) { notification.requestpermission() .then((permission) => { handlepermission(permission); }) } else { notification.requestpermission(function(permission) { handlepermission(permission); }); } } } looking at the second main block first, you'll see that we first check to see if notifications are supported.
... if they are, we then run a check to see whether the promise-based version of notification.requestpermission() is supported.
...we did this using the following: function checknotificationpromise() { try { notification.requestpermission().then(); } catch(e) { return false; } return true; } we basically try to see if the .then() method is available on requestpermission().
OfflineAudioContext.startRendering() - Web APIs
syntax event-based version: offlineaudioctx.startrendering(); offlineaudioctx.oncomplete = function(e) { // e.renderedbuffer contains the output buffer } promise-based version: offlineaudioctx.startrendering().then(function(buffer) { // buffer contains the output buffer }); parameters none.
...we use the audiocontext to load an audio track via xhr (audiocontext.decodeaudiodata), then the offlineaudiocontext to render the audio into an audiobuffersourcenode and play the track through.
...this is then played as part of a simple standard audio graph.
... request.open('get', 'viper.ogg', true); request.responsetype = 'arraybuffer'; request.onload = function() { var audiodata = request.response; audioctx.decodeaudiodata(audiodata, function(buffer) { mybuffer = buffer; source.buffer = mybuffer; source.connect(offlinectx.destination); source.start(); //source.loop = true; offlinectx.startrendering().then(function(renderedbuffer) { console.log('rendering completed successfully'); var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); var song = audioctx.createbuffersource(); song.buffer = renderedbuffer; song.connect(audioctx.destination); play.onclick = function() { song.start(); } }).catch(function(err) {...
Using the Permissions API - Web APIs
the geolocation.getcurrentposition() function is then run, which prompts the user for permission; it runs the revealposition() function if permission is granted (which shows the map), or the positiondenied() function if permission is denied (which makes the "enable geolocation" button appear).
... 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 == 'denied') { report(result.state); geobtn.style.display = 'inline'; } result.onchange = function() { report(result.state); } }); } function r...
... 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.
...if we choose to never share our location from the permission prompt (deny permission), then we can't get back to the permission prompt without using the browser menu options: firefox: tools > page info > permissions > access your location.
PublicKeyCredentialCreationOptions.excludeCredentials - Web APIs
transports optional an array of strings describing the possible transports between the client and the authenticator.
... the value of the strings may be: "usb": the authenticator can be contacted via a removable usb link "nfc": the authenticator may be used over nfc (near field communication) "ble": the authenticator may be used over ble (bluetooth low energy) "internal": the authenticator is specifically bound to the client device (cannot be removed).
... if the authenticator already contains one of such a public key credential, the client will throw a domexception or asks the user if they want to create a new credential.
..., 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 credentials level 1the definition of 'excludecred...
PublicKeyCredentialRequestOptions.allowCredentials - Web APIs
transports optional an array of strings describing the possible transports between the client and the authenticator.
... the value of the strings may be: "usb": the authenticator can be contacted via a removable usb link "nfc": the authenticator may be used over nfc (near field communication) "ble": the authenticator may be used over ble (bluetooth low energy) "internal": the authenticator is specifically bound to the client device (cannot be removed).
... if the authenticator does not contain any of these public key credentials, the client will throw a domexception "notallowederror".
...ls: [ { 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 definition of 'allowcredentials' in that specification...
RTCIceCredentialType - Web APIs
the webrtc api's rtcicecredentialtype enumerated string type defines the authentication method used to gain access to an ice server identified by an rtciceserver object.
... values oauth the rtciceserver requires the use of oauth 2.0 to authenticate in order to use the ice server described.
... password the rtciceserver requires a username and password to authenticate prior to using the described ice server.
... token authenticating with the ice server requires the use of an oauth 2.0 token as defined in rfc 7635.
ReadableStream.tee() - Web APIs
to cancel the stream you then need to cancel both resulting branches.
... examples in the following simple example, a previously-created stream is teed, then both resulting streams (contained in two members of a generated array) are passed to a function that reads the data out of the two streams and prints each stream's chunks sequentially to a different part of the ui.
... function teestream() { const teedoff = stream.tee(); fetchstream(teedoff[0], list2); fetchstream(teedoff[1], list3); } function fetchstream(stream, list) { const reader = stream.getreader(); let charsreceived = 0; // read() returns a promise that resolves // when a value has been received reader.read().then(function processtext({ done, value }) { // result objects contain two properties: // done - true if the stream has already given you all its data.
...current chunk = ' + chunk; list.appendchild(listitem); // read some more, and call this function again return reader.read().then(processtext); }); } specifications specification status comment streamsthe definition of 'tee()' in that specification.
Reporting API - Web APIs
you can then retrieve reports by making a request to those urls.
... methods are then available on the observer to start collecting reports (reportingobserver.observe()), retrieve the reports currently in the report queue (reportingobserver.takerecords()), and disconnect the observer so it can no longer collect records (reportingobserver.disconnect()).
... reporting api interfaces reportingobserver create reportingobserver instances using its constructor, which can then be used to collect and access reports.
... examples in our deprecation_report.html example, we create a simple reporting observer to observe usage of deprecated features on our web page: let options = { types: ['deprecation'], buffered: true } let observer = new reportingobserver(function(reports, observer) { reportbtn.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( cons...
Request() - Web APIs
WebAPIRequestRequest
example in our fetch request example (see fetch request live) we create a new request object using the constructor, then fetch it using a globalfetch.fetch call.
... since we are fetching an image, we run body.blob on the response to give it the proper mime type so it will be handled properly, then create an object url of it and display it in an <img> element.
... var myimage = document.queryselector('img'); var myrequest = new request('flowers.jpg'); fetch(myrequest).then(function(response) { return response.blob(); }).then(function(response) { var objecturl = url.createobjecturl(response); myimage.src = objecturl; }); in our fetch request with init example (see fetch request init live) we do the same thing except that we pass in an init object when we invoke fetch(): var myimage = document.queryselector('img'); var myheaders = new headers(); myheaders.append('content-type', 'image/jpeg'); var myinit = { method: 'get', headers: myheaders, mode: 'cors', cache: 'default' }; var myrequest = new request('flowers.jpg',myinit); fetch(myrequest).then(function(response) { ...
... }); note that you could also pass the init object into the fetch call to get the same effect, e.g.: fetch(myrequest,myinit).then(function(response) { ...
Using the Screen Capture API - Web APIs
example of a window allowing the user to select a display surface to capture you can then use the captured stream, capturestream, for anything that accepts a stream as input.
...then the cursor is removed from the stream.
...it stops the stream by getting its track list using mediastream.gettracks(), then calling each track's {domxref("mediastreamtrack.stop, "stop()")}} method.
...the settings currently in effect are obtained using getsettings() and the established constraints are gotten with getconstraints() html the html starts with a simple introductory paragraph, then gets into the meat of things.
USB.requestDevice() - Web APIs
WebAPIUSBrequestDevice
only the selected device is passed to then().
...for example, if only a usb device with product id 0xa800 is found, then only one device will be listed by the user agent.
... on the other hand if the user agent finds two of the first listed device and one of the second, then all three devices will be listed.
... 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.
Animating textures in WebGL - Web APIs
we then set up two events to make sure the video is playing and the time has been updated.
... then in main() in place of the call to loadtexture() in the previous example, we call inittexture() followed by setupvideo() .
... in the definition of render() if copyvideo is true, then we call updatetexture() each time just before we call the drawscene() function.
... const texture = inittexture(gl); const video = setupvideo('firefox.mp4'); var then = 0; // draw the scene repeatedly function render(now) { now *= 0.001; // convert to seconds const deltatime = now - then; then = now; if (copyvideo) { updatetexture(gl, texture, video); } drawscene(gl, programinfo, buffers, texture, deltatime); requestanimationframe(render); } requestanimationframe(render); that's all there is to it!
Using WebRTC data channels - Web APIs
in this guide, we'll examine how to add a data channel to a peer connection, which can then be used to securely exchange arbitrary data; that is, any kind of data we wish, in any format we choose.
... then negotiate the connection out-of-band, using a web server or other means.
... let datachannel = pc.createdatachannel("myapp channel", { negotiated: true }); datachannel.addeventlistener("open", (event) => { begintransmission(datachannel); }); requestremotechannel(datachannel.id); in this code snippet, the channel is created with negotiated set to true, then a function called requestremotechannel() is used to trigger negotiation, to create a remote channel with the same id as the local channel.
...he goes into a bit more detail there, but as browsers have been updated since then some of it may be out-of-date.
Controlling multiple parameters with ConstantSourceNode - Web APIs
then we get references to the control widgets, setting playbutton to reference the play button and volumecontrol to reference the slider control that the user will use to adjust the gain on the linked pair of oscillators.
... then we assign a handler for the play button's click event (see toggling the oscillators on and off for more on the toggleplay() method), and for the volume slider's input event (see controlling the linked oscillators to see the very short changevolume() method).
...we also create gainnode2 and gainnode3, setting their values to match gainnode1, then set the value of the volume slider to the same value, so it is synchronized with the gain level it controls.
... function stoposcillators() { oscnode1.stop(); oscnode2.stop(); oscnode3.stop(); playing = false; } each node is stopped by calling its constantsourcenode.stop() method, then playing is set to false.
Web Audio API - Web APIs
learning coding is like playing cards — you learn the rules, then you play, then you go back and learn the rules again, then you play again.
... if you are more familiar with the musical side of things, are familiar with music theory concepts, want to start building instruments, then you can go ahead and start building things with the advance tutorial and others as a guide (the above linked tutorial covers scheduling notes, creating bespoke oscillators and envelopes, as well as an lfo among other things.) if you aren't familiar with the programming basics, you might want to consult some beginner's javascript tutorials first and then come back here — see our beginner's java...
...once decoded into this form, the audio can then be put into an audiobuffersourcenode.
...keep playing and experimenting — you can expand on any of these techniques to create something much more elaborate.background audio processing using audioworkletthe process of creating an audio processor using javascript, establishing it as an audio worklet processor, and then using that processor within a web audio application is the topic of this article.basic concepts behind web audio apithis article explains some of the audio theory behind how the features of the web audio api work, to help you make informed decisions while designing how audio is routed through your app.controlling multiple parameters with constantsourcenodethis article demonstrates how to use a co...
window.postMessage() - Web APIs
broadly, one window may obtain a reference to another (e.g., via targetwindow = window.opener), and then dispatch a messageevent on it with targetwindow.postmessage().
... the receiving window is then free to handle this event as needed.
...methods for obtaining such a reference include: window.open (to spawn a new window and then reference it), window.opener (to reference the window that spawned this one), htmliframeelement.contentwindow (to reference an embedded <iframe> from its parent window), window.parent (to reference the parent window from within an embedded <iframe>), or window.frames + an index value (named or numeric).
...otherwise, a security hole in the site you trusted to send only trusted messages could then open a cross-site scripting hole in your site.
WritableStreamDefaultWriter.write() - Web APIs
the write() property of the writablestreamdefaultwriter interface writes a passed chunk of data to a writablestream and its underlying sink, then returns a promise that resolves to indicate the success or failure of the write operation.
...it then calls a function called sendmessage(), passing the newly created stream and a string.
... const list = document.queryselector('ul'); function sendmessage(message, writablestream) { // defaultwriter is of type writablestreamdefaultwriter const defaultwriter = writablestream.getwriter(); const encoder = new textencoder(); const encoded = encoder.encode(message, { stream: true }); encoded.foreach((chunk) => { defaultwriter.ready .then(() => { return defaultwriter.write(chunk); }) .then(() => { console.log("chunk written to sink."); }) .catch((err) => { console.log("chunk error:", err); }); }); // call ready again to ensure that all chunks are written // before closing the writer.
... defaultwriter.ready .then(() => { defaultwriter.close(); }) .then(() => { console.log("all chunks written"); }) .catch((err) => { console.log("stream error:", err); }); } const decoder = new textdecoder("utf-8"); const queuingstrategy = new countqueuingstrategy({ highwatermark: 1 }); let result = ""; const writablestream = new writablestream({ // implement the sink write(chunk) { return new promise((resolve, reject) => { var buffer = new arraybuffer(2); var view = new uint16array(buffer); view[0] = chunk; var decoded = decoder.decode(view, { stream: true }); var listitem = document.createelement('li'); listitem.textcontent = "chunk decoded: " + decoded; list.appendchild(listitem); result += de...
WritableStreamDefaultWriter - Web APIs
writablestreamdefaultwriter.write() writes a passed chunk of data to a writablestream and its underlying sink, then returns a promise that resolves to indicate the success or failure of the write operation.
...it then calls a function called sendmessage(), passing the newly created stream and a string.
... const list = document.queryselector('ul'); function sendmessage(message, writablestream) { // defaultwriter is of type writablestreamdefaultwriter const defaultwriter = writablestream.getwriter(); const encoder = new textencoder(); const encoded = encoder.encode(message, { stream: true }); encoded.foreach((chunk) => { defaultwriter.ready .then(() => { return defaultwriter.write(chunk); }) .then(() => { console.log("chunk written to sink."); }) .catch((err) => { console.log("chunk error:", err); }); }); // call ready again to ensure that all chunks are written // before closing the writer.
... defaultwriter.ready .then(() => { defaultwriter.close(); }) .then(() => { console.log("all chunks written"); }) .catch((err) => { console.log("stream error:", err); }); } const decoder = new textdecoder("utf-8"); const queuingstrategy = new countqueuingstrategy({ highwatermark: 1 }); let result = ""; const writablestream = new writablestream({ // implement the sink write(chunk) { return new promise((resolve, reject) => { var buffer = new arraybuffer(2); var view = new uint16array(buffer); view[0] = chunk; var decoded = decoder.decode(view, { stream: true }); var listitem = document.createelement('li'); listitem.textcontent = "chunk decoded: " + decoded; list.appendchild(list...
XRSystem: requestSession() - Web APIs
navigator.xr.requestsession("immersive-vr") .then((xrsession) => { xrsession.addeventlistener('end', onxrsessionended); // do necessary session setup here.
... 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.requestsession('immersive-vr') .then((session) => { xrsession = session; // onsessionstarted() not shown for reasons of brevity and clarity.
... xrsession.end().then(() => xrsession = null); } } specifications specification status comment webxr device apithe definition of 'requestsession()' in that specification.
XRView - Web APIs
WebAPIXRView
currently, the specification (and therefore all current implementations of webxr) is designed around rendering every xrview into a single xrwebgllayer, which is then presented on the xr device with half used for the left eye and half for the right eye.
... model view matrix the model view matrix is a matrix which defines the position of an object relative to the space in which it's located: if objectmatrix is a transform applied to the object to provide its basic position and rotation, then the model view matrix can be computed by multiplying the object's matrix by the inverse of the view transform matrix, like this: mat4.multiply(modelviewmatrix, view.transform.inverse.matrix, objectmatrix); normal matrix the model view's normal matrix is used when lighting the scene, in order to transform each surface's normal vectors to ensure that the light is reflected in the correct directi...
...it's computed by inverting then transposing the model view matrix: mat4.invert(normalmatrix, modelviewmatrix); mat4.transpose(normalmatrix, normalmatrix); teleporting an object to programmatically move and/or rotate (often referred to as teleporting) an object, you need to create a new reference space for that object which applies a transform that encapsulates the desired changes.
...the xrpose returned will then be used to actuall render the scene for the current frame.
Operable - Accessibility
see ui controls and building keyboard accessibility back in 2.1.4 character key shortcuts (a) added in 2.1 if a single character key shortcut exists, then at least one of the following is true: single character key shortcuts can be turned off, remapped or are only active when the relevant user interface component is in focus.
... 2.2.5 re-authenticating (aaa) if an authentication session expires during usage of a web app, the user can re-authenticate and continue their usage without losing any data.
... if a proper structure of headings and semantic containers is provided to navigate with (for example <section>, <aside>, etc.), then an added "skip link" is not needed.
...if you need to place elements in an unusual layout, it is better to make sure the source order is sensible, then use css features like positioning to handle the layout.
@counter-style - CSS: Cascading Style Sheets
for example if you want the counters to start at 01 and go through 02, 03, 04 etc, then the pad descriptor is to be used.
...if the specified fallback also fails to represent the value, then the fallback style's fallback is used, if one is specified.
... if there are either no fallback systems described or if the chain of fallback systems are unable to represent a counter value, then it will ultimately fall back to the decimal style.
...for example, if the system specified is fixed, then each of the n symbols specified in the descriptor will be used to represent the first n counter symbols.
In Flow and Out of Flow - CSS: Cascading Style Sheets
floated items in this example i have a div, and then two paragraphs.
... i’ve added a background colour to the paragraphs, and then floated the div left.
... as a float it is first laid out according to where it would be in normal flow, then taken out of flow and moved to the left as far as possible.
... relative positioning and flow if you give an item relative positioning with position: relative it remains in flow, however you are then able to use the offset values to push it around.
Shapes From Images - CSS: Cascading Style Sheets
rather than drawing a path with a complex polygon in css, you can create the shape in a graphics program and then use the path created by the pixels less opaque than a threshold value.
...if the value of shape-image-threshold is 0.0 (which is the initial value) then the area must be fully transparent.
... if the value is 1.0 then it is fully opaque.
...if i set shape-image-threshold to 0.3 then i see the shape, if i set it to something smaller than 0.2 i do not get the shape.
Sticky footers - CSS: Cascading Style Sheets
if the content of the page extends past the viewport bottom, the footer then sits below the content as normal.
...you could also achieve this for a full page by setting a min-height of 100vh on the <body> and then using it as your grid container.
...we then create a single column grid layout with three rows, one row for each part of our layout.
...then we set our main content to flex-grow: 1 and the other two elements to flex-shrink: 0 — this prevents them from shrinking smaller when content fills the main area.
Viewport concepts - CSS: Cascading Style Sheets
if you scroll down, you are changing the contents of the visual viewport and bringing the bottom of the layout viewport into view, displaying the sticky footer, which will then stay stuck at the bottom.
...mobile browsers render pages in a virtual window or viewport, generally at 980px, which is usually wider than the screen, and then shrink the rendered result down so it can all be seen at once.
... users can then pan and zoom to see different areas of the page.
... for example, if a mobile screen has a width of 320px, a website might be rendered with a virtual viewport of 980px, and then it will be shrunk down to fit into the 320px space, which, depending on the design, is illegible for many if not everyone.
conic-gradient() - CSS: Cascading Style Sheets
a conic gradient is specified by indicating a rotation angle, the center of the gradient, and then specifying a list of color-stops.
...the gradient is then rotated by the from angle.
...the following changes from red to yellow at the 30% mark, and then transitions from yellow to blue over 35% of the gradient conic-gradient(red .8rad, yellow .6rad, blue 1.3rad); there are other effects you can create with conic gradients.
...by creating quadrants with an upper left and lower right white quadrant and lower left and upper right black quadrants, then repeating the gradient 16 times (four times across and four times down) you can make a checkerboard.
mask-size - CSS: Cascading Style Sheets
WebCSSmask-size
tiple values */ /* do not confuse this with mask-size: auto auto */ mask-size: auto, auto; mask-size: 50%, 25%, 25%; mask-size: 6px, auto, contain; /* global values */ mask-size: inherit; mask-size: initial; mask-size: unset; note: if the value of this property is not set in a mask shorthand property that is applied to the element after the mask-size css property, the value of this property is then reset to its initial value by the shorthand property.
... the rendered size of the mask image is then computed as follows: if both components of mask-size are specified and are not auto: the mask image renders at the specified size.
...if the image has no intrinsic proportion, then it is rendered at the size of the mask positioning area.
... if mask-size has one auto component and one non-auto component: if the image has an intrinsic proportion, then render it using the specified dimension and compute the other dimension from the specified dimension and the intrinsic proportion.
page-break-after - CSS: Cascading Style Sheets
recto if pages progress left-to-right, then this acts like right.
... if pages progress right-to-left, then this acts like left.
... verso if pages progress left-to-right, then this acts like left.
... if pages progress right-to-left, then this acts like right.
page-break-before - CSS: Cascading Style Sheets
recto if pages progress left-to-right, then this acts like right.
... if pages progress right-to-left, then this acts like left.
... verso if pages progress left-to-right, then this acts like left.
... if pages progress right-to-left, then this acts like right.
position - CSS: Cascading Style Sheets
WebCSSposition
relative the element is positioned according to the normal flow of the document, and then offset relative to itself based on the values of top, right, bottom, and left.
... sticky the element is positioned according to the normal flow of the document, and then offset relative to its nearest scrolling ancestor and containing block (nearest block-level ancestor), including table-related elements, based on the values of top, right, bottom, and left.
...tion: absolute; background: yellow; top: 30px; left: 30px; } result fixed positioning fixed positioning is similar to absolute positioning, with the exception that the element's containing block is the initial containing block established by the viewport, unless any ancestor has transform, perspective, or filter property set to something other than none (see css transforms spec), which then causes that ancestor to take the place of the elements containing block.
...rather than sliding offscreen with the rest of the content, the "b" heading will then remain fixed to the top of the viewport until all the "b" items have scrolled offscreen, at which point it will be covered up by the "c" heading, and so on.
WAI ARIA Live Regions/API Support - Developer guides
if it is not present, then something went wrong and mozilla was not able to provide this information.
...if the event name has ":system" appended to it, then it is /not/ from user input.
...if the screen reader automatically reads too much, then the web page will be too annoying to use.
... if the screen reader doesn't read anything, then the user may miss important information.
Cross-browser audio basics - Developer guides
if the <audio> element is not supported then <audio> and <source> will be ignored.
...here's an example of creating an <audio> element, setting the media to play, playing and pausing, and then playing from 5 seconds into the audio: var myaudio = document.createelement('audio'); if (myaudio.canplaytype('audio/mpeg')) { myaudio.setattribute('src','audiofile.mp3'); } if (myaudio.canplaytype('audio/ogg')) { myaudio.setattribute('src','audiofile.ogg'); } alert('play'); myaudio.play(); alert('stop'); myaudio.pause(); alert('play from 5 seconds in'); myaudio.currenttime = 5; myau...
... myaudio.pause(); note: there is no stop method — to implement a stop function, you'd have to pause the media then set the currenttime property value to 0.
... first of all, we apply a quick update to the progress bar css to display the hand pointer on hover: #progress { margin-left: 80px; border: 1px solid black; cursor: pointer; } then we add the code that detects the click and moves the 'playhead' to the correct position: var progress = document.getelementbyid('progress'); progress.addeventlistener('click', function(e) { // calculate the normalized position clicked var clickposition = (e.pagex - this.offsetleft) / this.offsetwidth; var clicktime = clickposition * myaudio.duration; // move the playhead to the corre...
Video player styling basics - Developer guides
simple :hover and :focus states are then set for each button that simply alters the opacity of the button: .controls button:hover, .controls button:focus { opacity:0.5; } to obtain appropriate button images, a set of free common control set icons was downloaded from the web.
... each image was then converted to a base64 encoded string (using an online base64 image encoder), since the images are quite small, the resultant encoded strings are quite short.
...'unmute' : 'mute'); } } this function is then called by the relevant event handlers: video.addeventlistener('play', function() { changebuttonstate('playpause'); }, false); video.addeventlistener('pause', function() { changebuttonstate('playpause'); }, false); stop.addeventlistener('click', function(e) { video.pause(); video.currenttime = 0; progress.value = 0; // update the play/pause button's 'data-state' which allows the...
...this means that a user could play/pause the video from these controls, which would then leave the custom control set's buttons out of sync.
Allowing cross-origin use of images and canvas - HTML: Hypertext Markup Language
the image is then configured to allow cross-origin downloading by setting its crossorigin attribute to "anonymous" (that is, allow non-authenticated downloading of the image cross-origin).
... the canvas's size is adjusted to match the received image, then the image is drawn into the canvas using drawimage().
... the canvas is then inserted into the document so the image is visible.
...the canvas method todataurl() is used to convert the image into a data:// url representing a png image, which is then saved into local storage using setitem().
<audio>: The Embed Audio element - HTML: Hypertext Markup Language
WebHTMLElementaudio
in other words, it sends the origin: http header without a cookie, x.509 certificate, or performing http basic authentication.
...in other words, it sends the origin: http header with a cookie, a certificate, or performing http basic authentication.
... waiting playback has stopped because of a temporary lack of data usage notes browsers don't all support the same file types and audio codecs; you can provide multiple sources inside nested <source> elements, and the browser will then use the first one it understands: <audio controls> <source src="myaudio.mp3" type="audio/mpeg"> <source src="myaudio.ogg" type="audio/ogg"> <p>your browser doesn't support html5 audio.
... to get a consistent look and feel across browsers, you'll need to create custom controls; these can be marked up and styled in whatever way you want, and then javascript can be used along with the htmlmediaelement api to wire up their functionality.
<img>: The Image Embed element - HTML: Hypertext Markup Language
WebHTMLElementimg
if the crossorigin attribute is not specified, then a non-cors request is sent (without the origin request header), and the browser marks the image as tainted and restricts access to its image data, preventing its usage in <canvas> elements.
... if the crossorigin attribute is specified, then a cors request is sent (with the origin request header); but if the server does not opt into allowing cross-origin access to the image data by the origin site (by not sending any access-control-allow-origin response header, or by not including the site's origin in any access-control-allow-origin response header it does send), then the browser marks the image as tainted and restricts access to its image data, preventing its usage in <canvas> elements.
...if the server does not opt into sharing credentials with the origin site (by sending back the access-control-allow-credentials: true response header), then the browser marks the image as tainted and restricts access to its image data.
...if the srcset attribute is absent, or contains no values with a width descriptor, then the sizes attribute has no effect.
<input type="file"> - HTML: Hypertext Markup Language
WebHTMLElementinputfile
by holding down shift or control, and then clicking).
...it is still possible (in most cases) for users to toggle an option in the file chooser that makes it possible to override this and select any file they wish, and then choose incorrect file types.
...then, insert the image into the list item too by creating a new <img> and setting its src to the thumbnail.
...update your selection.`; listitem.appendchild(para); } list.appendchild(listitem); } } } the custom validfiletype() function takes a file object as a parameter, then uses array.prototype.includes() to check if any value in the filetypes matches the file's type property.
<input type="month"> - HTML: Hypertext Markup Language
WebHTMLElementinputmonth
value a domstring representing the value of the month and year entered into the input, in the form yyyy-mm (four or more digit year, then a hyphen ("-"), followed by the two-digit month).
...if the value of the max attribute isn't a valid string in "yyyy-mm" format, then the element has no maximum value.
... we'll look at basic and more complex uses of <input type="month">, then offer advice on mitigating the browser support issue in the section handling browser support).
...in order to detect whether the browser supports <input type="month">, we create a new <input> element, try setting its type to month, then immediately check what its type is set to.
<input type="submit"> - HTML: Hypertext Markup Language
WebHTMLElementinputsubmit
permitted values are: get a url is constructed by starting with the url given by the formaction or action attribute, appending a question mark ("?") character, then appending the form's data, encoded as described by formenctype or the form's enctype attribute.
... this url is then sent to the server using an http get request.
...if you want to create a custom button and then customize the behavior using javascript, you need to use <input type="button">, or better still, a <button> element.
... a simple submit button we'll begin by creating a form with a simple submit button: <form> <div> <label for="example">let's submit some text</label> <input id="example" type="text" name="text"> </div> <div> <input type="submit" value="send"> </div> </form> this renders like so: try entering some text into the text field, and then submitting the form.
<input type="time"> - HTML: Hypertext Markup Language
WebHTMLElementinputtime
to accept as a valid input readonly a boolean attribute which, if present, indicates that the contents of the time input should not be user-editable step the stepping interval to use both for user interfaces purposes and during constraint validation unlike many data types, time values have a periodic domain, meaning that the values reach the highest possible value, then wrap back around to the beginning again.
... we'll look at basic and more complex uses of <input type="time">, then offer advice on mitigating the browser support issue later on (see handling browser support).
... then there's the problem of the user having no idea exactly what format the time is expected to be in.
...: 30px; } input:invalid+span:after { position: absolute; content: '✖'; padding-left: 5px; } input:valid+span:after { position: absolute; content: '✓'; padding-left: 5px; } the other part of the code that may be of interest is the feature detection code — to detect whether the browser supports <input type="time">, we create a new <input> element, try setting its type to time, then immediately check what its type is set to — non-supporting browsers will return text, because the time type falls back to type text.
<link>: The External Resource Link element - HTML: Hypertext Markup Language
WebHTMLElementlink
you can also provide a media type or query inside a media attribute; this resource will then only be loaded if the media condition is true.
...no cookie, x.509 certificate, or http basic authentication).
...a cookie, certificate, and/or http basic authentication is performed).
...k rel="apple-touch-icon-precomposed" sizes="72x72" href="favicon72.png"> <!-- non-retina iphone, ipod touch, and android 2.1+ devices: --> <link rel="apple-touch-icon-precomposed" href="favicon57.png"> <!-- basic favicon --> <link rel="icon" href="favicon32.png"> conditionally loading resources with media queries you can provide a media type or query inside a media attribute; this resource will then only be loaded if the media condition is true.
<nextid>: The NeXT ID element (Obsolete) - HTML: Hypertext Markup Language
WebHTMLElementnextid
the user then saves and closes the document.
... next would then add, within the header of the html document, a special tag, <nextid n="z8">, to inform where to continue its naming convention.
...</p> </body> </html> they then forward a copy of this document to someone with a next editor, and they delete sections z7 and z19, add ten more, z20 through z29, and then delete paragraphs z24 and z29.
... so then the nextid value is z30 when it's returned modified: <html> <head> <title> ...
Preloading content with rel="preload" - HTML: Hypertext Markup Language
you could perhaps preload and display a simple svg diagram if the user is on a narrow screen where bandwidth and cpu is potentially more limited, or preload a complex chunk of javascript then use it to render an interactive 3d model if the user's resources are more plentiful.
...for example, here we create a htmllinkelement instance, then attach it to the dom: var preloadlink = document.createelement("link"); preloadlink.href = "myscript.js"; preloadlink.rel = "preload"; preloadlink.as = "script"; document.head.appendchild(preloadlink); this means that the browser will preload the myscript.js file, but not actually use it yet.
... to use it, you could do this: var preloadedscript = document.createelement("script"); preloadedscript.src = "myscript.js"; document.body.appendchild(preloadedscript); this is useful when you want to preload a script, but then defer execution until exactly when you need it.
... <link rel="subresource"> was supported in chrome a while ago, and was intended to tackle the same issue as preload, but it had a problem: there was no way to work out a priority for the items (as didn't exist back then), so they all got fetched with fairly low priority.
401 Unauthorized - HTTP
WebHTTPStatus401
the http 401 unauthorized client error status response code indicates that the request has not been applied because it lacks valid authentication credentials for the target resource.
... this status is sent with a www-authenticate header that contains information on how to authorize correctly.
... this status is similar to 403, but in this case, authentication is possible.
... status 401 unauthorized example response http/1.1 401 unauthorized date: wed, 21 oct 2015 07:28:00 gmt www-authenticate: basic realm="access to staging site" specifications specification title rfc 7235, section 3.1: 401 unauthorized http/1.1: authentication ...
HTTP response status codes - HTTP
WebHTTPStatus
401 unauthorized although the http standard specifies "unauthorized", semantically this response means "unauthenticated".
... that is, the client must authenticate itself to get the requested response.
... 407 proxy authentication required this is similar to 401 but authentication is needed to be done by a proxy.
... 511 network authentication required the 511 status code indicates that the client needs to authenticate to gain network access.
Closures - JavaScript
you define some behavior, and then attach it to an event that is triggered by the user (such as a click or a keypress).
...one way of doing this is to specify the font-size of the body element (in pixels), and then set the size of the other elements on the page (such as headers) using the relative em unit: body { font-family: helvetica, arial, sans-serif; font-size: 12px; } h1 { font-size: 1.5em; } h2 { font-size: 1.2em; } such interactive text size buttons can change the font-size property of the body element, and the adjustments are picked up by other elements on the page thanks to the relative units.
... notice that i defined an anonymous function that creates a counter, and then i call it immediately and assign the result to the counter variable.
... you could store this function in a separate variable makecounter, and then use it to create several counters.
Control flow and error handling - JavaScript
a switch statement looks like this: switch (expression) { case label_1: statements_1 [break;] case label_2: statements_2 [break;] … default: statements_def [break;] } javascript evaluates the above switch statement as follows: the program first looks for a case clause with a label matching the value of expression and then transfers control to that clause, executing the associated statements.
... (by convention, the default clause is written as the last clause, but it does not need to be so.) break statements the optional break statement associated with each case clause ensures that the program breaks out of switch once the matched statement is executed, and then continues execution at the statement following switch.
...you can then reference the object's properties in the catch block.
... the following example opens a file and then executes statements that use the file.
Expressions and operators - JavaScript
if x is 3, then ++x sets x to 4 and returns 4, whereas x++ returns 3 and, only then, sets x to 4.
... if x is 3, then --x sets x to 2 and returns 2, whereas x-- returns 3 and, only then, sets x to 2.
... if x is 3, then -x returns -3.
...for example, you can override multiplication and division first, then addition and subtraction to evaluate addition first.
Functions - JavaScript
for example, here is a function that computes factorials recursively: function factorial(n) { if ((n === 0) || (n === 1)) return 1; else return (n * factorial(n - 1)); } you could then compute the factorials of 1 through 5 as follows: var a, b, c, d, e; a = factorial(1); // a gets the value 1 b = factorial(2); // b gets the value 2 c = factorial(3); // c gets the value 6 d = factorial(4); // d gets the value 24 e = factorial(5); // e gets the value 120 there are other ways to call functions.
... if an enclosed function defines a variable with the same name as a variable in the outer scope, then there is no way to refer to the variable in the outer scope again.
...you can use arguments.length to determine the number of arguments actually passed to the function, and then access each argument using the arguments object.
...the function then multiplies these by the first argument .
Loops and iteration - JavaScript
you can think of a loop as a computerized version of the game where you tell someone to take x steps in one direction, then y steps in another.
... <form name="selectform"> <p> <label for="musictypes">choose some music types, then click the button below:</label> <select id="musictypes" name="musictypes" multiple="multiple"> <option selected="selected">r&b</option> <option>jazz</option> <option>blues</option> <option>new age</option> <option>classical</option> <option>opera</option> </select> </p> <p><input id="btn" type="button" value="how many are selected?" /></p> </form> ...
...for example, you can use a label to identify a loop, and then use the break or continue statements to indicate whether a program should interrupt the loop or continue its execution.
...it then iterates over all the object's properties and returns a string that lists the property names and their values.
Classes - JavaScript
you first need to declare your class and then access it, otherwise code like the following will throw a referenceerror: const p = new rectangle(); // referenceerror class rectangle {} class expressions a class expression is another way to define a class.
... const dy = a.y - b.y; return math.hypot(dx, dy); } } const p1 = new point(5, 5); const p2 = new point(10, 10); p1.distance; //undefined p2.distance; //undefined console.log(point.distance(p1, p2)); // 7.0710678118654755 binding this with prototype and static methods when a static or prototype method is called without a value for this, such as by assigning a variable to the method and then calling it, the this value will be undefined inside the method.
... class animal { speak() { return this; } static eat() { return this; } } let obj = new animal(); obj.speak(); // the animal object let speak = obj.speak; speak(); // undefined animal.eat() // class animal let eat = animal.eat; eat(); // undefined if we rewrite the above using traditional function-based syntax in non–strict mode, then this method calls is automatically bound to the initial this value, which by default is the global object.
... a function with a superclass as input and a subclass extending that superclass as output can be used to implement mix-ins in ecmascript: let calculatormixin = base => class extends base { calc() { } }; let randomizermixin = base => class extends base { randomize() { } }; a class that uses these mix-ins can then be written like this: class foo { } class bar extends calculatormixin(randomizermixin(foo)) { } specifications specification ecmascript (ecma-262)the definition of 'class definitions' in that specification.
JSON.stringify() - JavaScript
it is then called for each property on the object or array being stringified.
...if you return undefined or a function then null is used instead.
... json.stringify({ a: 2 }, null, ' '); // '{ // "a": 2 // }' using a tab character mimics standard pretty-print appearance: json.stringify({ uno: 1, dos: 2 }, null, '\t'); // returns the string: // '{ // "uno": 1, // "dos": 2 // }' tojson() behavior if an object being stringified has a property named tojson whose value is a function, then the tojson() method customizes json stringification behavior: instead of the object being serialized, the value returned by the tojson() method when called will be serialized.
...me': 'screenb', 'width': 650, 'height': 350 }); session.screens.push({ 'name': 'screenc', 'width': 750, 'height': 120 }); session.screens.push({ 'name': 'screend', 'width': 250, 'height': 60 }); session.screens.push({ 'name': 'screene', 'width': 390, 'height': 120 }); session.screens.push({ 'name': 'screenf', 'width': 1240, 'height': 650 }); // converting the json string with json.stringify() // then saving with localstorage in the name of session localstorage.setitem('session', json.stringify(session)); // example of how to transform the string generated through // json.stringify() and saved in localstorage in json object again var restoredsession = json.parse(localstorage.getitem('session')); // now restoredsession variable contains the object that was saved // in localstorage console.log...
Math.clz32() - JavaScript
if x is not a number, then it will be converted to a number first, then converted to a 32-bit unsigned integer.
... if the converted 32-bit unsigned integer is 0, then return 32, because all bits are 0.
...the ctrz function below fills in all the high bits with the lowest filled bit, then negates the bits to erase all higher set bits so that clz can then be used.
...now, inversing the bits reveals the lowest zeros return 32 - clon(~integer) |0; */ } make these helper functions into asm.js module; then, you have a true performance masterpiece.
Object.isFrozen() - JavaScript
object.preventextensions(oneprop); object.isfrozen(oneprop); // === false // ...but then deleting that property makes the object // vacuously frozen.
...var nonwritable = { e: 'plep' }; object.preventextensions(nonwritable); object.defineproperty(nonwritable, 'e', { writable: false }); // make non-writable object.isfrozen(nonwritable); // === false // changing that property to non-configurable // then makes the object frozen.
...var nonconfigurable = { release: 'the kraken!' }; object.preventextensions(nonconfigurable); object.defineproperty(nonconfigurable, 'release', { configurable: false }); object.isfrozen(nonconfigurable); // === false // changing that property to non-writable // then makes the object frozen.
...object.issealed(frozen); // === true non-object coercion in es5, if the argument to this method is not an object (a primitive), then it will cause a typeerror.
Promise.race() - JavaScript
if the iterable contains one or more non-promise value and/or an already settled promise, then promise.race will resolve to the first of these values found in the iterable.
... var foreverpendingpromise = promise.race([]); console.log(foreverpendingpromise); settimeout(function(){ console.log('the stack is now empty'); console.log(foreverpendingpromise); }); // logs, in order: // promise { <state>: "pending" } // the stack is now empty // promise { <state>: "pending" } if the iterable contains one or more non-promise value and/or an already settled promise, then promise.race will resolve to the first of these values found in the array: var foreverpendingpromise = promise.race([]); var alreadyfulfilledprom = promise.resolve(100); var arr = [foreverpendingpromise, alreadyfulfilledprom, "non-promise value"]; var arr2 = [foreverpendingpromise, "non-promise value", promise.resolve(100)]; var p = promise.race(arr); var p2 = promise.race(arr2); console.log(p...
...ck is now empty // promise { <state>: "fulfilled", <value>: 100 } // promise { <state>: "fulfilled", <value>: "non-promise value" } using promise.race – examples with settimeout var p1 = new promise(function(resolve, reject) { settimeout(() => resolve('one'), 500); }); var p2 = new promise(function(resolve, reject) { settimeout(() => resolve('two'), 100); }); promise.race([p1, p2]) .then(function(value) { console.log(value); // "two" // both fulfill, but p2 is faster }); var p3 = new promise(function(resolve, reject) { settimeout(() => resolve('three'), 100); }); var p4 = new promise(function(resolve, reject) { settimeout(() => reject(new error('four')), 500); }); promise.race([p3, p4]) .then(function(value) { console.log(value); // "three" // p3 is faster, so i...
...t fulfills }, function(reason) { // not called }); var p5 = new promise(function(resolve, reject) { settimeout(() => resolve('five'), 500); }); var p6 = new promise(function(resolve, reject) { settimeout(() => reject(new error('six')), 100); }); promise.race([p5, p6]) .then(function(value) { // not called }, function(error) { console.log(error.message); // "six" // p6 is faster, so it rejects }); specifications specification ecmascript (ecma-262)the definition of 'promise.race' in that specification.
WebAssembly.Module.exports() - JavaScript
examples using exports the following example (see our index-compile.html demo on github, and view it live also) compiles the loaded simple.wasm byte code using the webassembly.compilestreaming() method and then sends it to a worker using postmessage().
... var worker = new worker("wasm_worker.js"); webassembly.compilestreaming(fetch('simple.wasm')) .then(mod => worker.postmessage(mod) ); in the worker (see wasm_worker.js) we define an import object for the module to use, then set up an event handler to receive the module from the main thread.
... when the module is received, we create an instance from it using the webassembly.instantiate() method, invoke an exported function from inside it, then show how we can return information on the available exports on a module using webassembly.module.exports.
... var importobject = { imports: { imported_func: function(arg) { console.log(arg); } } }; onmessage = function(e) { console.log('module received from main thread'); var mod = e.data; webassembly.instantiate(mod, importobject).then(function(instance) { instance.exports.exported_func(); }); var exports = webassembly.module.exports(mod); console.log(exports[0]); }; the exports[0] output looks like this: { name: "exported_func", kind: "function" } specifications specification webassembly javascript interfacethe definition of 'exports()' in that specification.
Operator precedence - JavaScript
then the a is also set to 5, the return value of b = 5, aka right operand of the assignment.
...for example, in the expression a && (b + c), if a is falsy, then the sub-expression (b + c) will not even get evaluated, even if it is in parentheses.
... a || (b * c); // evaluate `a` first, then produce `a` if `a` is "truthy" a && (b < c); // evaluate `a` first, then produce `a` if `a` is "falsy" a ??
... (b || c); // evaluate `a` first, then produce `a` if `a` is not `null` and not `undefined` a?.b.c; // evaluate `a` first, then produce `undefined` if `a` is `null` or `undefined` examples 3 > 2 && 2 > 1 // returns true 3 > 2 > 1 // returns false because 3 > 2 is true, then true is converted to 1 // in inequality operators, therefore true > 1 becomes 1 > 1, which // is false.
import - JavaScript
the import statement may then be used to import such defaults.
... import('/modules/my-module.js') .then((module) => { // do something with the module.
...function getusefulcontents(url, callback) { getjson(url, data => callback(json.parse(data))); } the main program: main.js import { getusefulcontents } from '/modules/file.js'; getusefulcontents('http://www.example.com', data => { dosomethinguseful(data); }); dynamic import this example shows how to load functionality on to a page based on a user action, in this case a button click, and then call a function within that module.
... const main = document.queryselector("main"); for (const link of document.queryselectorall("nav > a")) { link.addeventlistener("click", e => { e.preventdefault(); import('/modules/my-module.js') .then(module => { module.loadpageinto(main); }) .catch(err => { main.textcontent = err.message; }); }); } specifications specification ecmascript (ecma-262)the definition of 'imports' in that specification.
Digital video concepts - Web media technologies
each type of cone, then, captures the relative reponse peaks at various wavelengths, and the brain uses this data to figure out the intensity and hue of the color of the light arriving at that part of the retina.
...the eight pixels represented by this block, then, have four chroma samples shared among them.
...the resulting image, then, is comprised solely of the luminance data—a greyscale image.
... the jpeg file type's compression works by first converting the image to the y'uv color system, then compressing that data.
The "codecs" parameter in common media types - Web media technologies
general syntax a basic mime media type is expressed by stating the type of media (audio, video, etc), then a slash character (/), then the container format used to contain the media: audio/mpeg an audio file using the mpeg file type, such as an mp3.
... to do so, append a semicolon (;) followed by codecs= and then the string describing the format of the contents of the file.
... in this format, the codecs parameter's value begins with a four-character code identifying the codec being used in the container, which is then followed by a series of period (.) separated two-digit values.
... cccc.pp.ll.dd.cc[.cp[.tc[.mc[.ff]]]] the first five components are required; everything from cp (color primaries) onward is optional; you can stop including components at any point from then onward.
Mapping the width and height attributes of media container elements to their aspect-ratio - Web media technologies
this change means that the aspect ratio of the image is calculated by the browser early on and can then be used to correct the size needed to display the image before it has loaded, if css has been applied that causes problems with its display size.
...folks from mozilla then expanded on this thinking, working on a proposal in the css box sizing level 4 draft to define an aspect-ratio property and propose the idea of using the width and height attributes to compute layout.
... mozilla then brought the idea up in the wicg community group and discussed it further until representatives from chrome were onboard with the idea.
... when the width/height of an <img> element — as set using html attributes — is overidden using css using something like this: img { max-width: 100%; height: auto } the aspect ratio is then used to calculate the height and therefore the correct size is applied to the <img> element, meaning that the aforementioned jank will not occur when the image loads.
Navigation and resource timings - Web Performance
to view and capture our app's timing we enter: let time = window.performance.timing we can then use the results to measure how well our app is performing.
...a connection is considered as opened when all secure connection handshake, or socks authentication, is terminated.
...the browser then parses the content received, builds the dom, cssom, accessibility, and render trees, eventually rendering the page.
...if there are deferred scripts needing to be parsed, it will do so, then fire the domcontentloaded, after which the readiness is set to complete.
Progressive loading - Progressive web apps (PWAs)
it is faster to load all that information as one file rather than many small ones, but if the user doesn't need everything at the very beginning, we could load only what's crucial and then manage other resources when needed.
...when you include <img> elements in your html, then every referenced image will be fetched and downloaded during initial website access.
...if you're past that point, then you can start thinking about optimizing the image loading using javascript.
...then we loop through each image and load it: imagestoload.foreach((img) => { loadimages(img); }); blur in css to make the whole process more visually appealing, the placeholder is blurred in css.
gradientUnits - SVG: Scalable Vector Graphics
alue objectboundingbox animatable yes userspaceonuse this value indicates that the attributes represent values in the coordinate system that results from taking the current user coordinate system in place at the time when the gradient element is referenced (i.e., the user coordinate system for the element referencing the gradient element via a fill or stroke property) and then applying the transform specified by attribute gradienttransform.
... objectboundingbox this value indicates that the user coordinate system for the attributes is established using the bounding box of the element to which the gradient is applied and then applying the transform specified by attribute gradienttransform.
... default value objectboundingbox animatable yes userspaceonuse cx, cy, r, fx, fy, and fr represent values in the coordinate system that results from taking the current user coordinate system in place at the time when the gradient element is referenced (i.e., the user coordinate system for the element referencing the gradient element via a fill or stroke property) and then applying the transform specified by attribute gradienttransform.
... objectboundingbox for <radialgradient>: the user coordinate system for attributes cx, cy, r, fx, fy, and fr is established using the bounding box of the element to which the gradient is applied (see object bounding box units) and then applying the transform specified by attribute gradienttransform.
in - SVG: Scalable Vector Graphics
WebSVGAttributein
if no value is provided and this is the first filter primitive, then this filter primitive will use sourcegraphic as its input.
... if no value is provided and this is a subsequent filter primitive, then this filter primitive will use the result from the previous filter primitive as its input.
... if the value for result appears multiple times within a given <filter> element, then a reference to that result will use the closest preceding filter primitive with the given value for attribute result.
...if supplied, then graphics that result from processing this filter primitive can be referenced by an in attribute on a subsequent filter primitive within the same filter element.
unicode - SVG: Scalable Vector Graphics
WebSVGAttributeunicode
if a character is provided, then this glyph corresponds to the given unicode character.
... if multiple characters are provided, then this glyph corresponds to the given sequence of unicode characters.
...for example, if unicode="ffl", then the given glyph will be used to render the sequence of characters "f", "f", and "l".
...if the attribute is not provided for a given <glyph>, then the only way to use this glyph is via an <altglyph> reference.
SVG documentation index - SVG: Scalable Vector Graphics
WebSVGIndex
this value is then used to calibrate the browser's distance calculations with those of the author, by scaling all distance computations using the ratio pathlength/(computed value of path length).
...if supplied, then graphics that result from processing this filter primitive can be referenced by an in attribute on a subsequent filter primitive within the same <filter> element.
...this is achieved by other filters storing their output via the result attribute and then accessing it in a <femergenode> child.
... 369 <switch> element, needsexample, svg, svg container the <switch> svg element evaluates any requiredfeatures, requiredextensions and systemlanguage attributes on its direct child elements in order, and then renders the first child where these attributes evaluate to true.
Secure contexts - Web security
a secure context is a window or worker for which certain minimum standards of authentication and confidentiality are met.
... a context is considered secure when it meets certain minimum standards of authentication and confidentiality defined in the secure contexts specification.
... however, it’s important to note that if a non-secure context causes a new window to be created (with or without specifying noopener), then the fact that the opener was insecure has no effect on whether the new window is considered secure.
... if (window.issecurecontext) { // page is a secure context so service workers are now available navigator.serviceworker.register("/offline-worker.js").then(function () { ...
Types of attacks - Web security
the victim then retrieves this malicious script from the server when the browser sends a request for data.
...in supporting browsers, this will have the effect of ensuring that the session cookie is not sent along with cross-site requests and so the request is effectively unauthenticated to the application server.
... session hijacking session hijacking consists of gaining access to and misusing a user's authenticated session.
... session fixation should primarily be mitigated by regenerating session cookie values when the user authenticates (even if a cookie already exists) and by tieing any csrf token to the user.
Web Components
custom elements: a set of javascript apis that allow you to define custom elements and their behaviour, which can then be used as desired in your user interface.
...these can then be reused multiple times as the basis of a custom element's structure.
... using templates and slots a guide showing how to define a reusable html structure using <template> and <slot> elements, and then use that structure inside your web components.
... reference custom elements customelementregistry contains functionality related to custom elements, most notably the customelementregistry.define() method used to register new custom elements so they can then be used in your document.
Introduction to using XPath in JavaScript - XPath
contextnode.documentelement : contextnode.ownerdocument.documentelement ); </pre> and then pass document.evaluate, the nsresolver variable as the namespaceresolver parameter.
... it could be any of the simple types (number_type, string_type, boolean_type), but, if the returned result type is a node-set then it will only be an unordered_node_iterator_type.
... in order to associate the 'mathml:' prefix with the namespace uri 'http://www.w3.org/1998/math/mathml' and 'xhtml:' with the uri 'http://www.w3.org/1999/xhtml' we provide a function: function nsresolver(prefix) { var ns = { 'xhtml' : 'http://www.w3.org/1999/xhtml', 'mathml': 'http://www.w3.org/1998/math/mathml' }; return ns[prefix] || null; } our call to document.evaluate would then looks like: document.evaluate( '//xhtml:td/mathml:math', document, nsresolver, xpathresult.any_type, null ); implementing a default namespace for xml documents as noted in the implementing a default namespace resolver previously, the default resolver does not handle the default namespace for xml documents.
...note that if the result is a node-set then unordered_node_iterator_type is always the resulting type.
Index - XSLT: Extensible Stylesheet Language Transformations
WebXSLTIndex
javascript can enable a web application to load xml data, process it via xslt into a presentable form and then add it into an existing document.
...for example, javascript and xslt could be used to sort xml data and then display it.
... 22 <xsl:attribute-set> element, reference, xslt, attribute-set the <xsl:attribute-set> element creates a named set of attributes, which can then be applied as whole to the output document, in a manner similar to named styles in css.
...to achieve the functionality of an if-then-else statement, however, use the <xsl:choose> element with one <xsl:when> and one <xsl:otherwise> children.
port - Archive of obsolete content
the main add-on code: // content-script.js self.port.on("mymessage", function handlemymessage(mymessagepayload) { // handle the message }); in the main add-on code, to listen for "mymessage" sent from a a content script: // main.js worker.port.on("mymessage", function handlemymessage(mymessagepayload) { // handle the message }); once() often you'll want to receive a message just once, then stop listening.
...when it receives this message, the script logs the first paragraph of the document and then calls removelistener() to stop listening.
...this means that if "main.js" sends the message twice in successive lines, and the listener stops listening as soon as it receives the first message, then the listener will still receive the second message.
Communicating using "port" - Archive of obsolete content
when it receives this message, the script logs the first paragraph of the document and then calls removelistener() to stop listening.
...this means that if "main.js" sends the message twice in successive lines, and the listener stops listening as soon as it receives the first message, then the listener will still receive the second message.
... port.once() often you'll want to receive a message just once, then stop listening.
Modules - Archive of obsolete content
to prevent scripts from interfering with each other, loadscript should evaluate each script to be loaded in the scope of their own global object, and then return the global object as its result.
...if the loading script has chrome privileges, then so will any methods called by the loading script, even if that method was installed by a malicious script.
...the resolved id is then further resolved using the paths array: const { loader, main } = require('toolkit/loader'); let loader = loader({ paths: ["./": "http://www.foo.com/"], resolve: function (id, requirer) { // your code here return id; } }); main(loader, "./main.js"); cuddlefish uses a custom resolve function to implement a form of access control: modules can only require modules for w...
Program ID - Archive of obsolete content
when you create an xpi with jpm xpi: if the package.json does not include an id field, then the id written into the install.rdf is the value of the name field prepended with "@".
... if the package.json does include an id field, and it contains "@", then this is written into the install.rdf as the add-on id.
... if the package.json does include an id field, and it does not contain "@", then jpm xpi raises an error and the xpi will not be built.
Testing the Add-on SDK - Archive of obsolete content
this suite builds the example code, then runs these example add-on's test code.
... this suite builds the entire addon-sdk repo as an add-on, like cfx xpi would, then runs the add-on like cfx test would.
... with travis if you merely make a pull request for the mozilla/addon-sdk then all of the jpm tests mentioned above will be run on travis-ci automatically and you will see the pass/fail results with a link to the log in the github pull request.
Working with Events - Archive of obsolete content
then in the constructor you can assign a listener function to this property as an alternative to calling the object's on() method.
...the listener loads https://developer.mozilla.org/: require("sdk/ui/button/action").actionbutton({ id: "visit-mozilla", label: "visit mozilla", icon: "./icon-16.png", onclick: function() { require("sdk/tabs").open("https://developer.mozilla.org/"); } }); this is exactly equivalent to constructing the button and then calling the button's on() method: var button = require("sdk/ui/button/action").actionbutton({ id: "visit-mozilla", label: "visit mozilla", icon: "./icon-16.png" }); button.on("click", function() { require("sdk/tabs").open("https://developer.mozilla.org/"); }); removing event listeners event listeners can be removed by calling removelistener(type, listener), supplying the type of even...
... then we open two tabs.
panel - Archive of obsolete content
however, doing this will cause any content scripts to be unloaded and then reloaded, so it may be less efficient, and you'll lose any state associated with the scripts.
...anel.show(); var self = require("sdk/self"); var mypanel = require("sdk/panel").panel({ contenturl: "https://en.wikipedia.org/w/index.php?title=jetpack&useformat=mobile", contentstylefile: self.data.url("panel-style.css") }); mypanel.show(); private browsing if your add-on has not opted into private browsing, and it calls panel.show() when the currently active window is a private window, then the panel will not be shown.
... to the content window: // show the panel centered horizontally, with: // - the top edge 40px from the top // of the content window // - the bottom edge 100px from the bottom // of the content window require("sdk/panel").panel({ position: { top: 40, bottom: 100 } }).show(); if you set both top and bottom, but also set the panel's height explicitly using the height property, then the panel will ignore bottom, just as css does for its properties with the same name: // show the panel centered horizontally, with: // - the top edge 40px from the top // of the content window // - a height of 400px require("sdk/panel").panel({ position: { top: 40, bottom: 100, }, height: 400 }).show(); // this is equivalent to: require("panel").panel({ position { top...
windows - Archive of obsolete content
with this module, you can: enumerate the currently opened browser windows open new browser windows listen for common window events such as open and close private windows if your add-on has not opted into private browsing, then you won't see any private browser windows.
... here's an example converting from a high-level browserwindow to a chrome window, and then back the other way: var { modelfor } = require("sdk/model/core"); var { viewfor } = require("sdk/view/core"); var browserwindows = require("sdk/windows").browserwindows; function converttochromeandback(browserwindow) { // get the chrome window for this browserwindow var chromewindow = viewfor(browserwindow); // now we can use the chrome window api console.log(chromewindow.document.loca...
...in particular, if the user quits the browser then it's possible that your add-on will be unloaded before all windows are closed.
places/bookmarks - Archive of obsolete content
save() and search() are both asynchronous functions: they synchronously return a placesemitter object, which then asynchronously emits events as the operation progresses and completes.
... // we then pass `results` into the remove function to mark // all items to be removed, which returns the new modified `array` // of items, which is passed into save.
...multiple query objects are then or'd together.
remote/parent - Archive of obsolete content
> { process.port.emit("id", processid); }); // main.js const { processes, remoterequire } = require("sdk/remote/parent"); // load "remote.js" into every current and future process remoterequire("./remote.js", module); // for every current and future process processes.forevery(process => { // ask for the process id process.port.emit("fetchid"); // first argument is always the process, then the message payload process.port.once("id", (process, id) => { console.log("child process is remote:" + process.isremote); console.log("child process id:" + id); }); }); content frame manipulation this demonstrates telling every current frame to link to a specific anchor element: // remote.js const { frames } = require("sdk/remote/child"); // listeners receive the frame the event ...
...this is a shortcut for enumerating existing processes and then listening for attach events.
...this is a shortcut for enumerating existing frames and then listening for attach events.
Listening for Load and Unload - Archive of obsolete content
if your add-on exports a function called main(), then that function will be called whenever the add-on is loaded, and it will be passed an object containing a string describing the reason it was loaded as well as any arguments passed to it.
... if your add-on exports a function called onunload(), then that function will be called when the add-on is unloaded, and it will be passed a string describing the reason it was unloaded.
... exports.onunload = function (reason) {}; reason reason is one of the following strings describing the reason your add-on was unloaded: uninstall disable shutdown upgrade downgrade if your add-on is disabled, then uninstalled, your onunload listener will only be called once, with the disable reason.
Finding window handles - Archive of obsolete content
once you have a docshell, queryinterface it into nsibasewindow, call getmainwidget on result, and then call getnativedata(ns_native_window).
...ponents.interfaces.nsiinterfacerequestor) .getinterface(components.interfaces.nsiwebnavigation) .queryinterface(components.interfaces.nsidocshelltreeitem) .treeowner .queryinterface(components.interfaces.nsiinterfacerequestor) .getinterface(components.interfaces.nsibasewindow); then in c++ part, a function take nsibasewindow as param hwnd getparentwindowhwnd(nsibasewindow *window) { nativewindow hwnd; nsresult rv = window->getparentnativewindow(&hwnd); if (ns_failed(rv)) return null; return (hwnd)hwnd; } that's it; use with caution!
... 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.
JavaScript Daemons Management - Archive of obsolete content
in such a condition it is difficult and unnatural to keep track of all events started and then to stop them when appropriate through the cleartimeout() function.
...in different objects (daemons) and then to create a constructor for such a class of objects (daemon) in order to standardize and simplify the instantiation of them.
... init optional the function which will be synchronously invoked once during the creation of the daemon and then assigned to the onstop property.
Chapter 3: Introduction to XUL—How to build a more intuitive UI - Archive of obsolete content
when one has been checked, then the checked="true" attribute is set.
...as shown in listing 20, you first declare the number of columns, and then define the content of each row.
...you can also code it so that the rows come first, declaring the number of rows and then defining content by column.
Getting Started with Firefox Extensions - Archive of obsolete content
install hello world click the above link and then click "allow" in the pop-up bubble.
... if you open the menu and then the menu item below, you'll see a nice alert message (for some definitions of 'nice').
...issue the following command to unzip the file on linux or mac os x: unzip xulschoolhello1.xpi -d xulschoolhello1 on windows, you can change the file extension from xpi to zip, or open the file directly, then unzip it, using a zip tool.
Handling Preferences - Archive of obsolete content
you don't need to know them by heart; if doing task x requires some preference, then it's better to look for an explanation on how to do x rather than diving into the preferences list and see if you can find the preference you need.
... then, create the observer method: observe : function(asubject, atopic, adata) { if ("nspref:changed" == atopic) { let newvalue = asubject.getintpref(adata); // do something.
... the standard way of opening a preferences window is to open the add-ons manager, select the add-on, and then click on the preferences button.
JavaScript Object Management - Archive of obsolete content
if your add-on is called sergeant pepper, for instance, then sgtpepper would be a good namespace name.
...just like with the chrome, we define the package name and then a path.
...the definition of the class acts as a constructor as well, and then you can define all other members using the prototype attribute.
Observer Notifications - Archive of obsolete content
for example, you might want to notify that a task is completed, and then several different actions must be performed.
... an observer is an object that is responsible to observe (wait for) notifications and then to carry out subsequent actions.
... observerservice.removeobserver(testobserver, "xulschoolhello-test-topic"); after you have registered some observers to listen to a notification topic, you can then use the notifyobservers method to send a notification to all of them.
The Box Model - Archive of obsolete content
if one of the buttons has a very long label that restricts its minimum size, then it could be the label determining its size, while the other button would flex taking the rest of the room.
...in order to have wrapping descriptions, you need to set the text as a child node instead of using the value attribute: <description>&xulschoolhello.description.label;</description> even then, the text will extend as much as it can in a single line, so you need to add some css limits in order to make it wrap inside a xul dialog or window.
... xulschoolhello.linkedtext.label = go to <html:a onclick="%s">our site</html:a> for more information to include html in a xul document, you need to add the namespace for it in the document root: <overlay id="xulschoolhello-browser-overlay" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul" xmlns:html="http://www.w3.org/1999/xhtml"> then you can have an html:p (paragraph) element where you insert the result of parsing the property string.
The Essentials of an Extension - Archive of obsolete content
we then call the window.alert function with the message, just like we would do in an html document.
... then you use getformattedstring instead of getstring in order to get the localized string.
... note: packaging an extension is really just creating a zip archive of the contents of the main folder, then changing the filename extension to .xpi.
Setting up an extension development environment - Archive of obsolete content
make a symbolic link (also referred to as a shortcut) to the firefox binary (firefox.exe on windows), then move the link to your desktop, or your preferred location.
...on the "advanced" page, select the "general" tab then click the "config editor" button.
...(how to find your profile directory) alternatively, rather than using a guid, create a unique id using the format "name@yourdomain" (for example chromebug@mydomain.com) - then the proxy filename will be same as that id, with no curly brackets {}.
Signing an XPI - Archive of obsolete content
c:\> set path=c:\apps\nss-3.11.4\bin\;c:\apps\nss-3.11.4\lib\;c:\apps\nspr-4.6\lib\;%path% an easier way is to copy everything from your new directories c:\apps\nss-3.11.4\ and c:\apps\nspr-4.6\ including sub directories to the same directory - fx c:\apps\codesigning\ - and then run every command from that.
...tree "signed/" signed successfully re-package xpi change to the signed/ folder, create a new zip with the meta-inf/zigbert.rsa file listed first, then add the remaining files.
...they will then issue a signed certificate.
Supporting search suggestions in search plugins - Archive of obsolete content
(this means that a suggestion-supporting engine plugin will have two <url> elements, the other one being the main text/html search url.) for example, the yahoo search plugin has this <url> entry: <url type="application/x-suggestions+json" template="http://ff.search.yahoo.com/gossip?output=fxjson&command={searchterms}"/> if the user types "fir" into the search bar, then pauses, firefox inserts "fir" in place of {searchterms} and queries that url: <url type="application/x-suggestions+json" template="http://ff.search.yahoo.com/gossip?output=fxjson&command=fir"/> the results are used to construct the suggestion list box.
... when the browser wants to fetch possible matches for a search term, it then sends an http get request to the url specified by the <url> element.
... your server should then decide upon the suggestions to offer using whatever means it sees fit, and return a json array of results: query string the first element in the array is the original query string.
Creating a dynamic status bar extension - Archive of obsolete content
we then fetch the result returned by the web server into the variable output from the xmlhttprequest.responsetext property.
... the text we receive back from the server looks something like this: "goog",414.20,"5/1/2006","1:36pm",-3.74,417.85,419.44,412.19,4760215 we then parse the text.
...we then set the tooltip for the status bar panel by assigning an appropriate string to the samplepanel.tooltiptext property.
Inner-browsing extending the browser navigation paradigm - Archive of obsolete content
for example, imagine a web form where users have to choose their city, by first selecting country then state.
... for example, imagine a web form where users have to choose their city, by first selecting country then state.
...the code locates element with id mydata then copies the content of mydata (mydata.innerhtml) into the tickerdiv element (div element that is the container of elements into the ticker).
Notes on HTML Reflow - Archive of obsolete content
a frame that decides it needs a dirty reflow sets the ns_frame_is_dirty state bit on itself, and then calls the reflowdirtychild method on its parent frame.
...the parent frame can then either decide to schedule a reflowdirty incremental reflow targeted at itself, or to delegate that responsibility to its parent.
... if it decides to delegate, then it sets the ns_frame_is_dirty state bit on itself and recursively calls reflowdirtychild.
Creating a Firefox sidebar extension - Archive of obsolete content
then the registration files are made and finally the sidebar is packed into an installable xpi file.
...one must then set the key attribute of the menuitem to "".
...on unix systems: ~/src/emptysidebar$ cd chrome ~/src/emptysidebar/chrome$ zip -r emptysidebar.jar content/ locale/ on windows systems, use a zip tool to create emptysidebar.zip and then rename to emptysidebar.jar.
Making it into a static overlay - Archive of obsolete content
we'll first make the file into a static overlay, then we'll make it into a dynamic overlay.
...then there is a statusbar element containing a statusbarpanel element.
...to use this overlay instead of our changes to navigator.xul we need to remove our changes, then add a reference to the overlay to the top of navigator.xul: ...
Getting Started - Archive of obsolete content
install.rdf make a copy of install.rdf and place it in the my_theme directory, then open it up in your text editor.
...<a href='javascript:installtrigger.installchrome(installtrigger.skin, "myskin.jar", "my skin theme")'>install my skin</a> if you have jar files on your hard drive and would like to install them, then download/use this form.
...what you do is put your folder(s) into a .zip file and then when it's compressed make the .zip into a .jar ...
Creating a Skin for Firefox/Getting Started - Archive of obsolete content
install.rdf make a copy of install.rdf and place it in the my_theme directory, then open it up in your text editor.
... <a href='javascript:installtrigger.installchrome(installtrigger.skin, "myskin.jar", "my skin theme")'>install my skin</a> if you have jar files on your hard drive and would like to install them, then download/use this form.
...what you do is put your folder(s) into a .zip file and then when it's compressed make the .zip into a .jar ...
Document Loading - From Load Start to Finding a Handler - Archive of obsolete content
it then passes the channel to dochannelload, which does some more flag massaging and then calls into the uriloader.
...we then set the channel's nsiloadgroup to the one from the window context.
...then it calls nsdocumentopeninfo::dispatchcontent nsdocumentopeninfo::dispatchcontent starts doing the real dirty work.
Measuring add-on startup performance - Archive of obsolete content
to test with about:startup, you should set up a new firefox profile, install this add-on, and then open and quit firefox repeatedly.
...then look at the results in the about:startup page.
...then repeat the process with both about startup and your add-on installed.
Microsummary topics - Archive of obsolete content
upport was removed in gecko 6.0 (firefox 6.0 / thunderbird 6.0 / seamonkey 2.3) programmatically installing a microsummary generator to programmatically install a microsummary generator -- for example, in an extension that helps users create custom generators for their favorite sites -- obtain a reference to the nsimicrosummaryservice interface implemented by the nsimicrosummaryservice component, then call its installgenerator() method, passing it an xml document containing the generator.
...if the x-moz header is present, and its value is microsummary, then the request is a microsummary-related request.
...then only microsummary users will be affected by those headers.
Proxy UI - Archive of obsolete content
camino configured in os (networking preferences) (recently added - some support for reading os and account settings.)ui elements preferences panel overview the ui is based on selecting a proxy mode, then filling out any additional needed information in "related" ui.
...the preference changes selecting the proxy "mode" all product's proxy preference panels share a basic design: a radio button that selects the proxy mode, then "related proxy mode" ui when needed.
...if configured, socks is used as a default: if the protocol was proxyable and did not match any of the previous protocols), then use socks.
Table Cellmap - Archive of obsolete content
if mspan is 0 then morigcell is in effect 81 // and the data does not represent a span.
... if mspan is 1, then mbits is in 82 // effect and the data represents a span.
...if the address is odd then it holds some other info (mbits).
Creating XPI Installer Modules - Archive of obsolete content
this article describes the new packaging scheme of mozilla and offers a tutorial for creating a new package that can then be redistributed, installed, and made available to users.
...one way of another, the chrome registry is shown the contents.rdf files; the contents.rdf files in turn point to new resources, and the resources are then registered with mozilla and accessible to the user.
...ar source getfolder("chrome"), // target folder ""); // target subdir // registerchrome(type, location, source) registerchrome(package | delayed_chrome, getfolder("chrome","barley.jar"), "content/"); if (err==success) performinstall(); else cancelinstall(err); note that there is no version number on barley, and so the name + version parameter has a "v" and then nothing else.
Unix stub installer - Archive of obsolete content
if you don't want the installer to download then grab a nightly "full" installer, say from <ftp://ftp.mozilla.org/pub/mozilla/ni...gnu-sea.tar.gz>.
... then untar and gunzip this to /tmp.
...then add the componentx into the appropriate setup types so the installer module installs it when users select the setup types you choose it to be in.
Learn XPI Installer Scripting by Example - Archive of obsolete content
if you choose not to register the installed software or do the verifications at the front end of the installation, then at a minimum, the install scripts mustinitialize, add the files to be installed, and execute.
...if successful, this function returns a "0" and makes entries into theinstalled-chrome.txt file in the chrome subdirectory, which is then used to regenerate the various rdf files that make up the chrome registry.
...in the example in the executing the installation section and in many places in the installation script, the logcomment api is used to write data to a log file that can then be reviewed when things don't go as planned.
A XUL Bestiary - Archive of obsolete content
if you don't do anything about these events, then you probably never know about them.
...if no one at a particular level in the hierarchy is interested in the event, then the event bubbles up to the next highest level on out to the top of the hierarchy.
...the event listener is really a convenience; instead of using it, you could find out when an object fired an event, then go find out what that event was, and then write some event handling code as a response to that event, but the event listener provides an easy mechanism for writing event handlers for specific, common events.
Reading from Files - Archive of obsolete content
reading data from a file involves getting a reference to a file and then creating an input stream to read from it.
...to create an input stream, first get a reference to a nsifile, and then use nsiscriptableio.newinputstream() to open a stream for reading from it.
...then, this length is used to determine how many additional bytes of data to read.
Introduction to XUL - Archive of obsolete content
ui descriptions, then, look a great deal like html 4.
... </window> </package> and a window (or other service) could be instantiated by first parsing the whole package and then picking out a window from its contents package *package = loadpackage("http://xxx/package.xul"); instantiatewindow(package, getnodewithid("main"); this happy scheme doesn't work today, because the code expects the result of parsing an xml document to be a window.
...the whole system is then configured with different locale-specific dtds, and the correct dtd will be chosen for a given xml file at runtime, depending on the current locale settings.
MenuModification - Archive of obsolete content
first, we need to retrieve the menupopup for the menu, and then use the appendchild method to append a new item.
...then add menuitem to menupopup (all with appendchild to their parentelement).
...in this example, an item is appended to a menu, and then immediately removed again.
Filtering - Archive of obsolete content
for example, the resulting triple for the netherlands might be: <triple subject="?photo" predicate="http://www.xulplanet.com/rdf/country" object="http://www.daml.org/2001/09/countries/iso#nl"/> this triple is then appended to the query.
...then, a simple <member> element can be used to iterate over it.
...then, we could just look for all resources that were of the 'country' type.
RDF Modifications - Archive of obsolete content
then, rather than notify on every change, the datasource will send one notification when the changes are finished.
... the template builder then rebuilds the template completely when done.
...since the earlier query takes precedence, the builder handles this by removing the old content first and then adding the new content.
Adding Event Handlers - Archive of obsolete content
the event is then sent to the xul in phases.
... in the capturing phase, the event is first sent to the window, then to the document, followed by each ancestor of the xul element where the event occured downwards until it reaches that element.
... for example, when the mouse is moved over a button that is inside a box, a 'mousemove' event is generated, and sent first to the window, followed by the document, and then the box.
Adding Methods to XBL-defined Elements - Archive of obsolete content
if the name doesn't exist, then a new window is opened and the specified resource is loaded into its browsing context.">window.open().
...then, the 'showtitle' method is called, which functions as it did before.
...then, the new binding will be added in its place and its constructor invoked.
More Event Handlers - Archive of obsolete content
prevent default action if no event handlers have been registered for an event, then after completing the capturing and bubbling phases, the element will handle the event in a default way.
...you might then unhighlight the element or remove status text.
...this string is then assigned to the value property of the label.
Tree Selection - Archive of obsolete content
from the tree, you can get the selection using the tree's view property and then retrieve the view's selection property.
...you would then write a loop for the number of ranges, calling getrangeat() to get the actual indices of the start and end of the range.
...then, we iterate over the set of ranges, the number of which is returned by the getrangecount() function.
Tree View Details - Archive of obsolete content
the view should then perform any necessary operations to retrieve the child rows and then update the tree with the new rows.
...the tree will then redraw the tree as needed and the result is that the child rows will appear inside the container.
...then, we scan along the rows until we come to one that is at the same level.
Updating Commands - Archive of obsolete content
then, it checks to see whether the command is enabled, and then executes the command using the docommand method of the controller.
...this function could then be reused for all commands.
...it just gets the necessary controller, calls its iscommandenabled method, and then enables or disables the command.
XUL Structure - Archive of obsolete content
the tree is then converted into a set of objects that can be displayed on the screen.
... if you are going to use xul on a web site, you can just put the xul file on the web site as you would an html file, and then load its url in a browser http://localhost/xul.php.
...although you don't normally distribute a package this way, it is handy during development since you can edit the file directly and then reload the xul file without having to repackage or reinstall the files.
Creating XULRunner Apps with the Mozilla Build System - Archive of obsolete content
follow the instructions for meeting build requirements and getting the source, then come back here since the build process itself will be slightly different.
...building your application if you decided that you needed a custom-built xulrunner and read the previous section then you're way ahead of the game.
...to build your application, make sure you have the right .mozconfig file in your top-level source directory, then run the following from that directory: make -f client.mk build so if you are building xulrunner as well as your app, this will cause both to be built in sequence.
Getting started with XULRunner - Archive of obsolete content
first change the file extension to zip and then use your normal filesystem's decompression tool to open it up.
... windows from a windows command prompt opened to the myapp folder, we should be able to execute this: c:\path\to\xulrunner.exe application.ini of course, if you opted to install xulrunner then you could simply do ​%programfiles%\xulrunner.exe application.ini or on 64 bit systems ​%programfiles(x86)%\xulrunner.exe application.ini note: you can also install your application when you're finished debugging it.
...first change into the \myapp folder, then start the application by: xulrunner application.ini you should now see a window that looks something like this.
calICalendarViewController - Archive of obsolete content
if astarttime is specified, then the calievent is meant to be created 'silently', that is, without a more detailed dialog appearing.
...if no astarttime is specified, then an event-creation dialog should be displayed.
...just the time changed), // then do so; otherwise pop up the dialog if (anewstarttime && anewendtime && !anewstarttime.isdate && !anewendtime.isdate) { var instance = aoccurrence.clone(); instance.startdate = anewstarttime; instance.enddate = anewendtime; instance.calendar.modifyitem(instance, aoccurrence, null); } else { modifyeventwithdialog(aoccurrenc...
Archived Mozilla and build documentation - Archive of obsolete content
microsummary topics to programmatically install a microsummary generator -- for example, in an extension that helps users create custom generators for their favorite sites -- obtain a reference to the nsimicrosummaryservice interface implemented by the nsimicrosummaryservice component, then call its installgenerator() method, passing it an xml document containing the generator.
...if you wish to develop and distribute cryptographic software, particularly for commercial sale or distribution, then you should consult an attorney with expertise in the particular laws and regulations that apply in your jurisdiction.
...if tracemonkey is built with tracevis, and run with tracevis enabled, then tracemonkey will output a log of all its activity transitions.
Mozilla release FAQ - Archive of obsolete content
the code has been continually available since then via cvs (see section 1.8), and occasional binary releases (first as milestones, and more recently as versioned releases) have been made.
... likely to use mozilla does the os support multitasking well enough for mozilla does the os have a sufficiently evolved gui for mozilla to work does the os have sufficient networking support for mozilla is the os typically run on systems that have the resources to run mozilla does gcc or some other easily available compiler exist for the target platform if many of these answers are no, then there will be large issues that will hamper the port.
...if you think you're getting it from mozilla because the x-mailer field mentions mozilla, then you're misinterpreting the meaning of the x-mailer field -- it indicates that the sender is *using* netscape communicator to deliver the mail.
Vulnerabilities - Archive of obsolete content
the arp protocol was standardized over 25 years ago, and threats have changed a great deal since then, so the trust assumptions inherent in its design then are unlikely to still be reasonable today.
... an example is the number of consecutive failed authentication attempts to permit before locking out a user account.
...broken authentication & session management 4.
Processing XML with E4X - Archive of obsolete content
one must instead either calculate the variable with a javascript expression (e.g., bar={'a'+var1+var2}), define a new variable before the element literal which includes the full interpolation and then include that variable or retrieve the attribute after the literal to alter it (see below).
...if you create an xmllist as a subset of an existing xml object and then modify the original xml object, the xmllist will not reflect those changes; you will need to re-create it to get the most recent updates: var languages = <languages> <lang>javascript</lang> <lang>python</lang> </languages>; var lang = languages.lang; alert(lang.length()); // alerts 2 languages.lang += <lang>ruby</lang>; alert(lang.length()); // still alerts 2 lang = languages.lan...
... function xmlchildwalker (xml) { var i = 0; var child = xml.*[0]; while (child != undefined) { yield child; child = xml.*[++i]; } yield false; } var a = <a><b/><c/></a>; var xcw = xmlchildwalker(a); var child; while ((child = xcw.next()) !== false) { alert(child.toxmlstring()); // "<b/>" then "<c/>" } see also e4x e4x tutorial ...
Writing JavaScript for XHTML - Archive of obsolete content
for example: var string = '<div xmlns="http://www.w3.org/999/xhtml"><h1>hello world!</h1></div>'; var parser = new domparser(); var documentfragment = parser.parsefromstring(string, "text/xml"); body.appendchild(documentfragment); // assuming 'body' is the body element but be aware that if your string is not well-formed xml (e.g., you have an & where it should not be), then this method will crash, leaving you with a parser error.
...however, it can be used for data, and be converted into a string which can then be converted into a dom object.
... dom objects can similarly be converted into strings which can then be converted into e4x.
XForms Output Element - Archive of obsolete content
if binding attributes are present on the control then the value attribute is is ignored.
... image - if the instance node contains an image, then an output element can be used in combination with the mediatype element to display the image (fx 3.0 only, xhtml/xul).
... image if the bound instance node contains an image then you are free to use this representation to show the image instead of the byte sequence of the image data (fx 3.0 only, xhtml/xul).
Index - Game development
58 win the game 2d, beginner, canvas, games, javascript, phaser, tutorial, winning implementing winning in our game is quite easy: if you happen to destroy all the bricks, then you win.
...if you miss the ball with the paddle and let it reach the bottom edge of the screen, then it's game over.
...technically, we will be painting the ball on the screen, clearing it and then painting it again in a slightly different position every frame to make the impression of movement — just like how movement works with the movies.
Game distribution - Game development
you can just send them a direct url to access the game, which they can then click to play the game right away without the need to use third party plugins or download and install a large package.
...plus, it is usually easier to build and test the game first on desktop, and then move on to debugging mobile.
... if you're working on a side project just for fun, then leaving the source open will benefit those who would like to learn from what you've created.
Unconventional controls - Game development
playerx += 5; } if(verticaldegree > degreethreshold) { playery += 5; } else if(verticaldegree < -degreethreshold) { playery -= 5; } if(grabstrength == 1) { alert('boom!'); } ctx.drawimage(img, playerx, playery); requestanimationframe(draw); } if the horizontaldegree value is greater than our degreethreshold, which is 30 in this case, then the ship will be moved left 5 pixels on every frame.
... if its value is lower than the threshold's negative value, then the ship is moved right.
... if the frequency of the bounced sound is shifted from the original one, then we can detect that the movement of that object occured.
Implementing controls using the Gamepad API - Game development
demo the full version of the hungry fridge game was built first, and then to showcase the gamepad api in action and show the javascript source code, a simple demo was created.
...we then set the turbo property to true.
...then it loops through buttons and axes to get their actual states and values.
Game over - Game development
if you miss the ball with the paddle and let it reach the bottom edge of the screen, then it's game over.
... first, replace where you initially called setinterval() setinterval(draw, 10); with: var interval = setinterval(draw, 10); then replace the second if statement with the following: if(y + dy < ballradius) { dy = -dy; } else if(y + dy > canvas.height-ballradius) { alert("game over"); document.location.reload(); clearinterval(interval); // needed for chrome to end game } letting the paddle hit the ball the last thing to do in this lesson is to create some kind of collision detection between the ball and t...
...if yes, then it bounces off just like you'd expect; if not then the game is over as before.
HMAC - MDN Web Docs Glossary: Definitions of Web-related terms
hmac is a protocol used for cryptographically authenticating messages.
...with such a combination, the hmac verification algorithm is then known with a compound name such as hmac-sha1.
... hmac is used to ensure both integrity and authentication.
Parse - MDN Web Docs Glossary: Definitions of Web-related terms
when the browser encounters css styles, it parses the text into the css object model (or cssom), a data structure it then uses for styling layouts and painting.
... the browser then creates a render tree from both these structures to be able to paint the content to the screen.
... javascript is also downloaded, parsed, and then execute.
SQL Injection - MDN Web Docs Glossary: Definitions of Web-related terms
sql queries work as follows: "select count(*) from users where username=' " + txt.user.text+" ' and password=' "+ txt.password.text+" ' "; now suppose user enters the username: admin and password: passwd123, so after clicking on the log in button, sql query will run as follows: "select count(*) from users where username=' admin ' and password=' passwd123 ' "; if the credentials are correct, then the user is allowed to log in, so it's a very simple (and therefore insecure) mechanism.
...finally, due to the or operator, the value ( false or true ) is true, so authentication bypasses successfully.
...the revised magical string fails to bypass the authentication, and your database stays secure.
Vendor Prefix - MDN Web Docs Glossary: Definitions of Web-related terms
browser vendors sometimes add prefixes to experimental or nonstandard css properties and javascript apis, so developers can experiment with new ideas while—in theory—preventing their experiments from being relied upon and then breaking web developers' code during the standardization process.
...if an entire interface is experimental, then the interface's name is prefixed (but not the properties or methods within).
... if an experimental property or method is added to a standardized interface, then the individual method or property is prefixed.
HTML: A good basis for accessibility - Learn web development
you'll then likely (depending on which screen reader you're using) have to go down into the table as an object and look at its features separately, then get out of the table again to carry on navigating the content.
... you can then press enter/return to follow a focused link or press a button (we've included some javascript to make the buttons alert a message), or start typing to enter text in a text input.
...</p> in this case, we are not using the alt attribute at all — instead, we have presented our description of the image as a regular text paragraph, given it an id, and then used the aria-labelledby attribute to refer to that id, which causes screen readers to use that paragraph as the alt text/label for that image.
HTML: A good basis for accessibility - Learn web development
you'll then likely (depending on which screen reader you're using) have to go down into the table as an object and look at its features separately, then get out of the table again to carry on navigating the content.
... you can then press enter/return to follow a focused link or press a button (we've included some javascript to make the buttons alert a message), or start typing to enter text in a text input.
...</p> in this case, we are not using the alt attribute at all — instead, we have presented our description of the image as a regular text paragraph, given it an id, and then used the aria-labelledby attribute to refer to that id, which causes screen readers to use that paragraph as the alt text/label for that image.
Floats - Learn web development
add a class of special to the first paragraph of text, the one immediately following the floated box, then in your css add the following rules.
...then add the following to your css: .cleared { clear: left; } float example 3 <h1>simple float example</h1> <div class="box">float</div> <p class="special">lorem ipsum dolor sit amet, consectetur adipiscing elit.
...nulla luctus aliquam dolor, eu lacinia lorem placerat vulputate.</p> </div> in your css, add the following rule for the .wrapper class and then reload the page: .wrapper { background-color: rgb(79,185,227); padding: 10px; color: #fff; } in addition, remove the original .cleared class: .cleared { clear: left; } you will see that, just like in the example where we put a background color on the paragraph, the background color runs behind the float.
Test your skills: floats - Learn web development
if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page.
...the text should then appear between the two boxes as in the image below.
...then we want the first line of text to display next to that element, but the following line of text (which has a class of .below) to display underneath it.
CSS layout - Learn web development
this article will give you all you need to know to get started with page layout, then test your grid skills before moving on.
...in this lesson you will first learn about the syntax used in media queries, and then move on to use them in a worked example showing how a simple design might be made responsive.
...4, 6, or 12), and then fit your content columns inside these imaginary columns.
Web fonts - Learn web development
the syntax required looks something like this: first of all, you have a @font-face block at the start of the css, which specifies the font file(s) to download: @font-face { font-family: "myfont"; src: url("myfont.woff"); } below this you can then use the font family name specified inside @font-face to apply your custom font to anything you like, as normal: html { font-family: "myfont", "bitstream vera serif", serif; } the syntax does get a bit more complex than this; we'll go into more detail below.
... you then need to copy the css declarations listed into your css as appropriate, to apply the custom fonts to your html.
...if you are importing multiple weights of the same font, you can specify what their weight/style is and then use different values of font-weight/font-style to choose between them, rather than having to call all the different members of the font family different names.
How do you upload your files to a web server? - Learn web development
to install filezilla go to the filezilla downloads page, click the big download button, then install from the installer file in the usual way.
... in the site manager window, press the new site button, then fill in the site name as demozilla in the provided space.
... in the logon type: drop down, choose normal, then fill in your provided username and password in the relevant fields.
Advanced form styling - Learn web development
to fix this in our example we first used our old friend appearance: none to get rid of the icon altogether: select { -webkit-appearance: none; appearance: none; } we then created our own icon using generated content.
...ments (this is because generated content is placed relative to an element's formatting box, but form inputs work more like replaced elements — their display is generated by the browser and put in place — and therefore don't have one): <div class="select-wrapper"><select id="select" name="select"> <option>banana</option> <option>cherry</option> <option>lemon</option> </select></div> we then use generated content to generate a little down arrow, and put it in the right place using positioning: .select-wrapper { position: relative; } .select-wrapper::after { content: "▼"; font-size: 1rem; top: 6px; right: 10px; position: absolute; } the second, slightly more major issue is that you don't have control over the box that appears containing the options when you click on t...
...so you could hide the actual from input using something like this: input[type="file"] { height: 0; padding: 0; opacity: 0; } and then style the label to act like a button, which when pressed will open the file picker as expected: label[for="file"] { box-shadow: 1px 1px 3px #ccc; background: linear-gradient(to bottom, #eee, #ccc); border: 1px solid rgb(169, 169, 169); border-radius: 5px; text-align: center; line-height: 1.5; } label[for="file"]:hover { background: linear-gradient(to bottom, #fff, #ddd); } label[...
Dealing with files - Learn web development
so for example, if you put an image on your website at, test-site/myimage.jpg and then in a different file you try to invoke the image as test-site/myimage.jpg, it may not work.
...option, unchecking the hide extensions for known file types check box, then clicking ok.
... save your html file, then load it in your web browser (double-click the file).
Tips for authoring fast-loading HTML pages - Learn web development
then you just apply the same image each time you need it for a background and adjust the x/y coordinates appropriately.
... any dynamic features that require the page to complete loading before being used, should be initially disabled, and then only enabled after the page has loaded.
...first, browsers will have no need to perform error-correction when parsing the html (this is aside from the philosophical issue of whether to allow format variation in user input and then programmatically "correct" or normalize it; or whether, instead, to enforce a strict, no-tolerance input format).
Document and website structure - Learn web development
we'd like you to look at the example above, and then look over the listing below to see what parts make up what section of the visual.
...we aren't asking you to do much else in this article, because the key to understanding document layout is writing a sound html structure, and then laying it out with css.
...he read it hazily and sighed; "better get back to work then", he mused.</p> would render like this: planning a simple website once you've planned out the structure of a simple webpage, the next logical step is to try to work out what content you want to put on a whole website, what pages you need, and how they should be arranged and link to one another for the best possible user experience.
From object to iframe — other embedding technologies - Learn web development
these were considered the height of coolness in the mid to late 90s, and there was evidence that having a webpage split up into smaller chunks like this was better for download speeds — especially noticeable with network connections being so slow back then.
...and then you constantly got annoying alerts about updating flash player and your java runtime environment.
...in 2015, alex stamos, then-chief security officer at facebook, requested that adobe discontinue flash.
Build your own function - Learn web development
we then use yet another dom api function called element.setattribute() to set a class attribute on our panel with a value of msgbox.
...change the following line: btn.onclick = displaymessage; to this block: btn.onclick = function() { displaymessage('woo, this is a different message!'); }; if we want to specify parameters inside parentheses for the function we are calling, then we can't call it directly — we need to put it inside an anonymous function so that it isn't in the immediate scope and therefore isn't called immediately.
...if the msgtype parameter is not set at all (or to something different), then the else { ...
Test your skills: Loops - Learn web development
note: you can try out solutions for the tasks below by downloading the code, putting it in an online tool such as codepen, jsfiddle, or glitch, then working on the tasks.
... if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page.
... loops 2 in this next task, we want you to write a simple program that, given a name, searches an array of objects containing names and phone numbers (phonebook) and, if it finds the name, outputs the name and phone number into the paragraph (para) and then exits the loop before it has run its course.
Object-oriented JavaScript for beginners - Learn web development
previous overview: objects next with the basics out of the way, we'll now focus on object-oriented javascript (oojs) — this article presents a basic view of object-oriented programming (oop) theory, then explores how javascript emulates object classes via constructor functions, and how to create object instances.
...you can then add properties and methods to this object using dot or bracket notation as desired; try these examples in your console: person1.name = 'chris'; person1['age'] = 38; person1.greeting = function() { alert('hi!
...i\'m ' + this.name + '.'); } }); using the create() method constructors can help you give your code order—you can create constructors in one place, then create instances as needed, and it is clear where they came from.
Test your skills: Object basics - Learn web development
if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page.
... once you've done this, you should then write a string to the variable bandinfo, which will contain a small biography detailing their name, nationality, years active, and style, and the title and release date of their first album.
...if you are not sure, then don't worry — this is what we'll be looking at in future articles in the series!
Introduction to the server side - Learn web development
a new html page, or an image, etc...), which could then be displayed by the web browser.
...as in the previous diagram, browsers send http requests to the server, then the server processes the requests and returns appropriate http responses.
...support for sessions, support for users and authentication, easy database access, templating libraries, etc.).
Ember Interactivity: Footer functionality, conditional rendering - Learn web development
to fix this, we'll have to add a getter to todo-data.js to return the result of this.incomplete.length === 1, and then call that in our template.
... get todocountisone() { return this.incomplete.length === 1; } then go back over to footer.hbs and update the previous template section we edited to the following: <strong>{{this.todos.incomplete.length}}</strong> {{#if this.todos.todocountisone}} todo {{else}} todos {{/if}} left now save and test, and you'll see the correct pluralization used when you only have one todo item present!
... try restarting the dev server and going to localhost:4200 again, and you'll now see that we have a fully-operational battlestation “todos left” counter and clear button: if you're asking yourself why we're not just doing the toggle on the component, since the function is entirely self-contained and not at all needing anything from the service, then you are 100% right to ask that question!
Getting started with Vue - Learn web development
to install the cli, run the following command in your terminal: npm install --global @vue/cli or if you'd prefer to use yarn: yarn global add @vue/cli once installed, to initialize a new project you can then open a terminal in the directory you want to create the project in, and run vue create <project-name>.
... the cli will then give you a list of project configurations you can use.
...follow the steps below: in terminal, cd to where you'd like to create your sample app, then run vue create moz-todo-vue.
Capturing a minidump
for example, if the application is hanging (not responding to input, but hasn't crashed) then breakpad is not triggered, and it can be difficult to determine where the problem lies.
...(you'll want the 32-bit version of windbg only if you are using a 32-bit version of firefox) then install it, the standard settings in the installation process are fine.
... if firefox is not already running, then open windbg from the start menu (start->all programs->debugging tools for windows->windbg).
Simple SeaMonkey build
insert "mac os x install disc 2", then open xcodetools.mpkg.
...(if you get a message saying this application did not install properly then you should see a windows dialog giving you the option to re-install with the 'correct settings'.
... how to build again later in your comm-central directory, run these commands: # get the latest source python client.py checkout then just re-run the "(moz)make -f client.mk" command above.
Simple Thunderbird build
so firstly complete the instructions for your os and then continue following these build instructions.
...then, get the latest thunderbird source code from mozilla's comm-central mercurial code repository.
... or same commands shorter: hg pull -u; (cd comm; hg pull -u) then just re-run the mach command above.
Obsolete Build Caveats and Tips
alternatively you can install the command-line compiler as part of the windows 7 sdk, but you are then expected to use the included windbg debugger.
... the visual c++ 8 command-line compiler is included with the vista sdk, but you are then expected to use the included windbg debugger.
... if you are building mozilla source code from before firefox 5, then you must first select the mozilla application that you want to build (see below), and you will probably also need to set at least some of the other basic configuration options (such as whether to build a debug build or not) to get the type of build that you need.
mach
$ cd objdir-firefox $ mach build adding mach to your shell's search path if you add mach to your path (by modifying the path environment variable to include your source directory, or by copying mach to a directory in the default path like /usr/local/bin) then you can type mach anywhere in your source directory or your objdir.
...generally speaking, if you have some piece of functionality or action that is useful to multiple people (especially if it results in productivity wins), then you should consider implementing a mach command for it.
...it's a python script that creates an instance of the mach core, registers commands with it, then tells the mach core to execute.
Displaying Places information using views
if your view implements nsinavhistoryresultobserver, then you can pass your viewer object.
...(the three built-in views take this approach.) the results object then communicates to your view via this instance, notifying it about changes in the underlying data so it can update its display.
...because the object implementing nsitreeview also implements nsinavhistoryresultobserver, the viewer then disconnects itself from the result by calling removeobserver().) is this still right when using nsinavhistoryresultobserver?
Frame script loading and lifetime
ne the mapping between a chrome:// url and a frame script packaged with an extension, use a "chrome.manifest" file to register a chrome url: // chrome.manifest content my-e10s-extension chrome/content/ // chrome script mm.loadframescript("chrome://my-e10s-extension/content/content.js", true); allowdelayedload if the message manager is a global frame message manager or a window message manager then: if allowdelayedload is true, the frame script will be loaded into any new frame, which has opened after the loadframescript() call.
...for example, from bootstrap.js: services.mm.addmessagelistener( 'my-addon-id', { receivemessage: function() { console.log('incoming message from frame script:', amsg.data); } }, true // must set this argument to true, otherwise sending message from framescript will not work during and after the unload event on the contentmessagemanager triggers ); then in your frame script, listen for the unload event of the message manager (which is the global this), and sending a message.
... var gcontentframemessagemanager = this; addeventlistener('unload', function(aevent) { if (aevent.target == gcontentframemessagemanager) { sendasyncmessage('my-addon-id', 'framescript-died'); // if you did not set third argument of `services.mm.addmessagelistener` to `true`, then this will fail to send a message } }, false); note about unload during uninstallation/upgrade when your add-on is uninstalled, or disabled, you should: cancel it, if you have used allowdelayedload, by calling removedelayedframescript; ensuring the frame script is not loaded into any new tabs.
Message manager overview
similarly, if you send a message using the global frame message manager, it's received by all content tabs, and is then delivered to any frame scripts that are listening for it.
... you can mix and match: so for example, you could load a script into every tab using the global message manager, but then send a message to the script instance loaded into a specific tab by using the browser message manager.
...with a cpmm, you can send messages to the parent process: these messages are received first by the corresponding ppmm, then by the gppmm.
Message manager overview
you can mix and match: so for example, you could load a script into every <browser> using the global message manager, but then send a message to the script instance loaded into a specific <browser> using the browser message manager.
...with a cpmm, you can send messages to the parent process: these messages are received first by the corresponding ppmm, then by the gppmm.
... the jsm can then use the child process message manager to exchange messages with the parent process message manager.
Storage access policy: Block cookies from trackers
we’ll keep this page updated with the newest information as we strengthen our protections.
...as an example, if a resource from tracker.example is granted storage access on foo.example.com, then tracker.example will be able to access its cookies on bar.foo.example.com but not example.com.
... if the preference does not exist, click "string" and then "+" to create a new preference.
Tracking Protection
most obviously, it means that when tracking protection is enabled: content served from third-party trackers will not be visible to users your site won't be able to use third-party advertising or analytics services that engage in tracking more subtly, if other parts of your site depend on trackers being loaded, then these parts will also be broken when tracking protection is enabled.
... for example, if your site includes a callback that runs when content from a tracking site is loaded, then the callback will not execute.
... note: depending on a third party in this way is not a good practice anyway, because then your site can be broken if the third party is slow or unavailable, or if the tracker has been blocked by an add-on.
Embedding the editor
thence, lots of javascript in editor.js, composercommands.js and the various dialog js files assume that they can get at the one true editor via window.editorshell.
...if we continue to use window.editorshell, then this needs to be updated on focus changes.
...if an embedder wants a fully native ui, then they'll have to code their own dialogs, and associated logic, but the apis should already be available to them.
How to get a stacktrace for a bug report
expand "~/library/logs" and "crashreporter", then look for logs for "firefox-bin".
... if breakpad successfully sends the crash report to the reporting server then, by default, the files added to the 'pending' subdirectory for the crash are removed, and a .txt file is placed in the 'submitted' directory containing the crash id created by the reporting server.
... if you want breakpad to leave the .dump and .extra files on your computer so that you can examine them locally, then set the moz_crashreporter_no_delete_dump environment variable to 1.
Download
this property can become true, then it can be reset to false when a canceled download is restarted.
... if the cancel() method was called but the cancellation process has not finished yet, this method waits for the cancellation to finish, then restarts the download immediately.
...if the cancel() method was called but the cancellation process has not finished yet, this method waits for the cancellation to finish, then removes the partial data.
Downloads.jsm
.jsm"); components.utils.import("resource://gre/modules/osfile.jsm") components.utils.import("resource://gre/modules/task.jsm"); task.spawn(function () { yield downloads.fetch("http://www.mozilla.org/", os.path.join(os.constants.path.tmpdir, "example-download.html")); console.log("example-download.html has been downloaded."); }).then(null, components.utils.reporterror); observing downloads this example logs a message every time a change occurs in one of the global download lists.
...close the message to stop."); } finally { yield list.remove(download); yield download.finalize(true); } } finally { yield list.removeview(view); } }).then(null, components.utils.reporterror); conversion from nsidownloadmanager starting in firefox for desktop version 26, the nsidownloadmanager and nsidownload interfaces are not available anymore.
... then you should declare the new nsitransfer object during the startup of your app.
NetUtil.jsm
to use these utilities, you first need to import the code module into your javascript scope: components.utils.import("resource://gre/modules/netutil.jsm"); once you've imported the module, you can then use its methods.
... get("tmpd", ci.nsifile); file.append("test-file.tmp"); file.createunique(ci.nsifile.normal_file_type, 0666); // then, we need an output stream to our output file.
...the callback may then consume data from the input stream passed to the callback.
Promise.jsm
to observe the state of a promise, its then method must be used.
...see the documentation of the then method for details.
...if this value is a promise, then the returned promise will be resolved with the value, i.e.
Mozilla Style System Documentation
for frames: const nsstyledisplay *display; ::getstyledata(frame, &display); or for style contexts: const nsstyledisplay *display; ::getstyledata(sc, &display); these functions cause an appropriate struct to be computed if it hasn't been computed already and then fill in the struct pointer.
...therefore, inherited structs are cached on the style context (but only the top style contexts pointing to them actually "owns" them), but structs that are shared between rule nodes are stored only on the highest rule node to which they apply and then retrieved from that most upper rule node every time they are needed.
...then the style struct is computed from the declaration and stored at the appropriate location in the rule tree or on the style context.
BloatView
if they aren't, then you're not using the ns_impl_addref and ns_impl_release (or ns_impl_isupports which calls them) for xpcom objects, or moz_count_ctor and moz_count_dtor for non-xpcom objects.
... you'll want to modify are listed below: linux: unittests/linux_unittest.py mac: unittests/mac_unittest.py windows: unittests/win_unittest.py android: android/androidarm_4_3.py how to instrument your objects for bloatview first, if your object is an xpcom object and you use the ns_impl_addref and ns_impl_release (or a variation thereof) macro to implement your addref and release methods, then there is nothing you need do.
... if your object is not an xpcom object then some manual editing is in order.
Scroll-linked effects
scrolling effects explained often scrolling effects are implemented by listening for the scroll event and then updating elements on the page in some way (usually the css position or transform property.) you can find a sampling of such effects at css scroll api: use cases.
...instead, it will move with the user's scrolling, and then "snap" back into position when the scroll event handler runs.
...if it is, then it triggers an animation to "snap" the scroll position to the top of the div.
TimerFirings logging
then comes the function kind, one of one_shot (a single-use timer), slack or precise (repeating timers of differing precision).
... then comes the timer period, measured in milliseconds.
...if the output is redirected to a file called out, then the following command will pull out the timer-related lines, count how many times each unique line appears, and then print them with the most common ones first.
TraceMalloc
<script type="text/javascript"> var filename = window.prompt("filename to log: "); if (filename) tracemallocdumpallocations(filename); </script> one can then use the script tools/trace-malloc/diffbloatdump.pl to compare trace-malloc dumps before and after doing an action that might leak.
...(this can be done by examining the unprocessed output of an xpcom_mem_refcnt_log, one of the nstracerefcnt logs.) you should use the --use-address argument to diffbloatdump.pl, and then the diff tree can be run through fix_linux_stack.py or fix_macosx_stack.py as needed.
...the output of leaksoup begins with all the leak roots, and then lists all the non-root allocations.
nss tech note1
if only an asn.1 tag is specified without a modifier, then the decoder will enforce the presence of a component of that type, and fail if it does not match.
... if kind is an asn.1 sequence tag (sec_asn1_sequence), then you must specify additional templates in a null-terminated array to define the content of the of the asn.1 sequence.
...if kind contains the sec_asn1_inline or sec_asn1_pointer modifiers, then it must point to the required subtemplate.
nss tech note3
the list of known seccertusages is short: certusagesslclient ........... an ssl client authentication cert certusagesslserver ........... an ordinary ssl server cert certusagesslserverwithstepup.. an ssl server cert that allows export clients to use strong crypto.
...if the extension is present and has the value true, then this cert is taken to be a ca cert.
... this allows all ssl client authentication certs with email addresses to also be used as email certs (provded they have adequate key usage).
nss tech note7
if you have the modulus and public exponent, you need to first encode them into an rsa public key and then import the public key into nss.
...} inpubkey; secitem derpubkey; seckeypublickey *pubkey; const sec_asn1template myrsapublickeytemplate[] = { { sec_asn1_sequence, 0, null, sizeof(myrsapublickey) }, { sec_asn1_integer, offsetof(myrsapublickey,m_modulus), }, { sec_asn1_integer, offsetof(myrsapublickey,m_exponent), }, { 0, } }; prarenapool *arena; /* * point inpubkey.m_modulus and m_exponent at the data, and * then set their types to unsigned integers.
... if you need to interoperate with a protocol that isn't implemented by nss, then you may need to use the pk11_ functions.
nss tech note8
the protocol code builds such a structure, and then asks the cache code (client or server) to save the info.
...however since nss was delivered as archive libraries, client programs merely declared these two variables for themselves, and then were able to alter those variables directly.
...if zero, then the called cache function would compute the correct expiration time by adding the chosen timeout (from one of those two global variables) to the sid's creationtime, giving the expirationtime.
NSS tools : pk12util
if the prefix sql: is not used, then the tool assumes that the given databases are in the old format.
...0:03:4d:7b:a1:63:3c:15:ea:67:37:62:1f iteration count: 1 (0x1) certificate: data: version: 3 (0x2) serial number: 13 (0xd) signature algorithm: pkcs #1 sha-1 with rsa encryption issuer: "e=personal-freemail@thawte.com,cn=thawte personal freemail c a,ou=certification services division,o=thawte consulting,l=cape t own,st=western cape,c=za" alternatively, the -r prints the certificates and then exports them into separate der binary files.
...if the cryptographic module does not support the requested algorithm, then the next best fit will be selected (usually the default).
gtstd.html
>mkdir server_db >certutil -n -d server_db import the new ca certificate into the server's certificate database, and mark it trusted for issuing certificates for ssl client and server authentication.
... >mkdir client_db >certutil -n -d client_db import the new ca certificate into the client's certificate database, and mark it trusted for issuing certificates for ssl client and server authentication.
...this is necessary for the ssl client to be able to authenticate to the server.
NSS Tools certutil
the key and certificate management process generally begins with creating keys in the key database, then generating and managing certificates in the certificate database.
... -c issuer identify the certificate of the ca from which a new certificate will derive its authenticity.
...in each category position use zero or more of the following attribute codes: p prohibited (explicitly distrusted) p trusted peer c valid ca t trusted ca to issue client certificates (implies c) c trusted ca to issue server certificates (ssl only) (implies c) u certificate can be used for authentication or signing w send warning (use with other attributes to include a warning when the certificate is used in that context) the attribute codes for the categories are separated by commas, and the entire set of attributes enclosed by quotation marks.
NSS tools : pk12util
if the prefix sql: is not used, then the tool assumes that the given databases are in the old format.
... alternatively, the -r prints the certificates and then exports them into separate der binary files.
...if the cryptographic module does not support the requested algorithm, then the next best fit will be selected (usually the default).
NSS tools : signtool
when testing is finished and you are ready to disitribute your software, you should obtain an object-signing certificate from one of two kinds of sources: * an independent certificate authority (ca) that authenticates your identity and charges you a fee.
...then run signtool with standard input redirected from your file as follows: signtool -g mytestcert inputfile the prompts show up on the screen, but the responses will be automatically read from the file.
... 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.
Installing Pork
svn co https://mcpp.svn.sourceforge.net/svnroot/mcpp/trunk mcpp cd mcpp ./configure --enable-replace-cpp make sudo make install note: if you followed the dehydra installation instructions for linux and compiled your own gcc, then you should not need to "sudo" make install.
...-f gcc${gcc_maj_ver}${gcc_min_ver}_predef_std.h; then - echo " generating g*.h header files" - ${cc} -e -xc -dm /dev/null | sort | grep ' *#define *_' \ + echo " generating g*.h header files: ${cppflags}" + ${cc} ${cppflags} -e -xc -dm /dev/null | sort | grep ' *#define *_' \ > gcc${gcc_maj_ver}${gcc_min_ver}_predef_std.h - ${cc} -e -xc -dm /dev/null | sort | grep -e ' *#define *[a-za-z]+' \ + ${cc} ${...
...x} ${cppflags} -e -xc++ -dm /dev/null | sort | grep ' *#define *_' \ > gxx${gcc_maj_ver}${gcc_min_ver}_predef_std.h - ${cxx} -e -xc++ -dm /dev/null | sort | grep -e ' *#define *[a-za-z]+' \ + ${cxx} ${cppflags} -e -xc++ -dm /dev/null | sort | grep -e ' *#define *[a-za-z]+' \ > gxx${gcc_maj_ver}${gcc_min_ver}_predef_old.h fi if test ${host_system} = sys_cygwin; then if you don't do this, mcpp will get the wrong set of automatic definitions and you'll end up with an unpleasant hybrid x86-64/i686 build system.
How to embed the JavaScript engine
then click the view source button, and copy the code from the window that appears.
... * args.rval().setint32(args[0].toint32() + args[1].toint32()); */ return true; } then to wire it up to js, you could write: ok = js_definefunction(cx, global, "doit", doit, doit_minargs, 0); or, if you had a bunch of native functions to define, you would probably put them in a table: static jsfunctionspec my_functions[] = { js_fn("doit", doit, doit_minargs, 0), /* etc...
...// js::autovaluevector argv(cx); // argv.resize(2); js::autovaluearray<2> argv(cx); argv[0].setint32(1); argv[1].setint32(2); then call the function: // [spidermonkey 24] pass arguments length and the 'jsval *' pointer.
Introduction to the JavaScript shell
from a bash console when using a pre-compiled binary, try <path to your firefox's run-mozilla.sh>/run-mozilla.sh ./js -- that worked for me] if you'd like to run the javascript code in the file foo.js, you can use this command: js foo.js to run foo.js then drop into the interactive shell, do this: js -f foo.js -i reference note: because the javascript shell is used as a test environment for the javascript engine, the available options and built-in functions can change over time.
... -p if the first line of the file is "/usr/bin/env js -p", then the file content will be interpreted by the javascript engine.
... for example, if you enter the javascript function below: function test() { var i = 3; print(i+2); } then run the command dis(test);, you get this output: main: 00000: uint16 3 00003: setvar 0 00006: pop 00007: name "print" 00010: pushobj 00011: getvar 0 00014: uint16 2 00017: add 00018: call 1 00021: pop 00022: stop source notes: 0: 0 [ 0] newline 1: 3 [ 3] decl offset 0 2: 7 [ 4] newline 3: 18 [ 11] xdelta 4: 18 [ 0] pcbase offset 11 dissrc(...
JSClass.flags
if the global object does not have this flag, then scripts may cause nonstandard behavior by replacing standard constructors or prototypes (such as function.prototype.) objects that can end up with the wrong prototype object, if this flag is not present, include: arguments objects (ecma 262-3 §10.1.8 specifies "the original object prototype"), function objects (ecma 262-3 §13.2 specifies "the original function prototype"), and objects crea...
... if this class has a finalizer that makes use of state shared with the main thread then this option must be specified.
... if this class has a finalizer that can be safely run concurrently with the main thread then this option can be specified.
JSDeletePropertyOp
if a jsdeletepropertyop does nothing and returns true, then property delete is unaffected.
... this callback may veto the ongoing property operation by optionally reporting an error or raising an exception and then returning false.
... the operation then fails, and the error is propagated to the caller.
JS_GetProperty
if the lookup proceeds without error, exactly one of the following cases applies: if the property is not found, then *vp is set to undefined.
... then the jsclass.getproperty hook of obj's class is called with the arguments (cx, obj, id, vp).
...otherwise *vp is set to the property's stored value, or undefined if the property does not have a stored value, and then the property's getter is called with the arguments (cx, obj, id, vp).
Split object
if page a gets a reference to that function, then by calling it, it is indirectly accessing tab tb's window.
...this makes the problem resistant to a wrapper-based approach.) older versions of firefox accomplished this by blowing away all window properties every time a user navigated to another page, then reusing the window.
...but then the page that called window.open could use a with statement to inject that window into its scope chain, gaining access to that window's privileges.
TPS Bookmark Lists
that is, the first item is appended to its parent folder, then the second, and so forth.
...if location is specified without position, then the bookmark is moved to the end of the specified folder.
... if position is specified without location, then the bookmark is moved to the specified position within the current folder.
Feed content access API
use an xmlhttprequest to load the feed, then pass its string to an nsifeedprocessor to parse the feed.
...arsing feed."); } } } httprequest = new xmlhttprequest(); httprequest.open("get", feedurl, true); try { httprequest.onload = inforeceived; httprequest.send(null); } catch(e) { alert(e); } } the nsifeedprocessor interface lets you parse the feed data from several possible sources; in this case, we're loading a document into a string, then parsing that string using its parsefromstring() method.
...we then scan the array of items in the feed by looking at the feed.items nsiarray.
Mork
MozillaTechMork
if the scope is not specified, then it is the default scope of the table (if it has one) or 'r' otherwise.
...these defaults are used if the scope is not specified (by having the ':' then the scope).
...you pass in a file to parsefile, select the tables, and then pass in callback functions for the meta-row and row enumeration functions.
Querying Places
the conditions for different query objects are then ored together.
...the current behavior does the normal query and then selects keywords from the first query and filters all the results.
...your implementation would then reflect these changes in the ui.
Avoiding leaks in JavaScript XPCOM components
if object a owns object b, and object b owns object a, then neither one will ever be destroyed.
...mozilla's javascript engine uses one of the most common garbage collection algorithms, mark and sweep, in which the garbage collector clears the mark bit on each object, sets the mark bits on all roots and all objects reachable from them, and then finalizes all objects not marked and returns the memory they used to the heap.
...these properties have to be preserved across garbage collections, even if the wrapper is not reachable from any garbage collection root, since the javascript programmer could access the dom node again the same way he did the first time, and would then expect the added properties to still be there.
Component Internals
if xpcom registered your component, then it will be available to other parts of the xpcom system.
...but if there is a component loader for javascript installed, then you can also write a javascript component.
...you shouldn't have to link to the xpcom library to create a xpcom component - in fact, if your component has to, then something is wrong.
Setting up the Gecko SDK
then, from the new dialog, select "win32 dynamic-link library".
...to add these libraries, select the link tab, then choose the input category.
... then copy the .xpt file to the c:\program files (x86)\mozilla firefox\components directory.
Using XPCOM Components
when a user selects one of the cookies displayed in the list and then clicks the remove button, the remove method in the nsicookiemanager interface is called.
... if your application is written in c++, then managing cookies from cpp shows the steps you take to get an xpcom component, specify the interface on that component you want to use, and call methods on that interface.
...to instantiate an xpcom component in javascript, you create a new component object and pass in the contract id for the component you want and ask for either a singleton or an instance of that component to be returned: var cmgr = components.classes["@mozilla.org/cookiemanager;1"] .getservice(); the resulting cookiemanager object then provides access to all of the methods for that component that have been defined in idl and compiled into the type library.
XPCOM Stream Guide
MozillaTechXPCOMGuideStreams
if we think of the water as data, then the spout represents an input stream: a controller for data coming out of something.
...however, it is usually better to create an input stream that you then feed to the output stream: var outstream = components.classes["@mozilla.org/storagestream;1"] .createinstance(components.interfaces.nsistoragestream) .getoutputstream(); var instream = components.classes["@mozilla.org/io/string-input-stream;1"] .createinstance(components.interfaces.nsistringinputstream); var data = "hel...
... then, write that data to the underlying stream.
Interfacing with the XPCOM cycle collector
if the collector finds a group of objects that all refer back to one another, and establishes that the objects' reference counts are all accounted for by internal pointers within the group, it considers that group cyclical garbage, which it then attempts to free.
... handling jsobjects fields if your class needs to store a pointer to a jsobject then you need to tell the cycle collector about it.
...ns_impl_cycle_collection_traverse_end finally, you need to manually add the js object to the trace method: ns_impl_cycle_collection_trace_begin(nsfoo) //if your class is a wrapper cache: //ns_impl_cycle_collection_trace_preserved_wrapper ns_impl_cycle_collection_trace_js_member_callback(msomeobj) ns_impl_cycle_collection_trace_end note that if your class is a wrapper cache then you likely have generate code that uses ns_impl_cycle_collection_wrappercache_# macro instead of ns_impl_cycle_collection_#.
Components.utils.cloneInto
it returns a reference to the clone: var clonedobject = cloneinto(myobject, targetwindow); you can then assign the clone to an object in the target scope as an expando property, and scripts running in that scope can access it: targetwindow.foo = clonedobject; in this way privileged code, such as an add-on, can share an object with less-privileged code like a normal web page script.
...if you do pass this flag, then functions in the object are cloned using the same mechanism as that used in components.utils.exportfunction: // add-on script var addonscriptobject = { greetme: function() { alert("hello from add-on"); } }; contentwindow.addonscriptobject = cloneinto(addonscriptobject, contentwindow, {clonefunctions: t...
...if you pass the {wrapreflectors:true} flag, then the object you clone is allowed to contain these objects: // add-on script var addonscriptobject = { body: contentwindow.document.body }; contentwindow.addonscriptobject = cloneinto(addonscriptobject, contentwindow, {wrapreflectors: true}); // page script var test = document.getelementbyid("test"); test.add...
Components.utils.importGlobalProperties
therefore readystate must be checked, if it is not complete, then a load listener must be attached.
... once readystate is complete then the objects can be used.
... var domfile = services.appshell.hiddendomwindow.file('/path/to/file'); xpcom components some objects have an xpcom alternative, which typically allows more flexibility then the dom version here is an example of how to use the dom xmlhttprequest through xpcom interface of nsixmlhttprequest: var oreq = cc["@mozilla.org/xmlextras/xmlhttprequest;1"].createinstance(ci.nsixmlhttprequest); ...
Components.utils.unwaiveXrays
privileged code can waive xray vision using waivexrays, and it will then see expandos.
... it can then use unwaivexrays to restore its xray vision for the object.
...the chrome code can then use unwaivexrays to restore xray protection: // chrome code // contentwindow is an xray var isxray = components.utils.isxraywrapper(gbrowser.contentwindow); // true // expandos are not visible in xrays var foo = gbrowser.contentwindow.foo; // undefined // you can waive xray vision for an object var waived = components.utils.waivexrays(gbrowser.contentwindow); i...
IAccessibleValue
if this object has no upper bound then an empty object is returned.
...if this object has no lower bound then an empty object is returned.
...the argument is clipped to the valid interval whose upper and lower bounds are returned by the methods maximumvalue() and minimumvalue(), that is if it is lower than the minimum value the new value will be the minimum and if it is greater than the maximum then the new value will be the maximum.
nsIAbCard
ismaillist boolean maillisturi string if ismaillist is true then maillisturi will contain the uri of the associated mailing list.
...if this bundle is not supplied, then the function will obtain the bundle itself.
... if cached by the caller and supplied to this function, then performance will be improved over many calls.
nsIAlertsService
1.0 66 introduced gecko 1.7 inherits from: nsisupports last changed in gecko 22 (firefox 22 / thunderbird 22 / seamonkey 2.19) by default a message is displayed in a small window that slides up from the bottom of the screen, holds there for a few seconds, then slides down.
...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 ## new messages.
...if no name is provided then only a notification created with no name (if any) will be closed.
nsIAppShellService
obsolete since gecko 1.8 eattemptquit 2 try to close all windows, then quit if successful.
... obsolete since gecko 1.8 eforcequit 3 force all windows to close, then quit.
...to get an out of process element you want to communicate with via message manager, then append a browser element with remote attribute set to true.
nsIChannel
then, the uri can be fetched by calling open() or asyncopen().
... if a charset parameter is given, then its value will replace the the contentcharset attribute of the channel.
...if the notification callbacks are changed, then a cached interface pointer may become invalid and may therefore need to be re-queried.
nsIComponentRegistrar
xpcom <= 1.8: if aspec is null, then the application component's directory as defined by ns_xpcom_component_dir will be registered.
...if aspec is null, then the application component's directory as defined by ns_xpcom_component_dir will be unregistered.
...this value is passed into thensimodule.registerself() callback and must be forwarded unmodified when registering factories via their location.
nsIContentPrefService2
if the preference is neither cached nor known not to exist, then null is returned, and get() must be called to determine whether the preference exists.
...if a preference for a particular subdomain is known not to exist, then an object corresponding to that preference will be present in the array, and, as with getcachedbydomainandname(), its value attribute will be undefined.
...as with getcachedbydomainandname(), if the preference is cached then it is returned; if the preference is known not to exist, then the value attribute of the returned object will be undefined; if the preference is neither cached nor known not to exist, then null is returned.
nsIHttpChannel
if the new channel supports nsihttpchannel, then it will be assigned a value to its redirectionlimit attribute one less than the value of the redirected channel's redirectionlimit attribute.
...if this flag is false, then the header value will be replaced with the contents of avalue.
...if this flag is false, then the header value will be replaced with the contents of value.
Using nsILoginManager
the hostname, username and password attributes are mandatory, while the other fields are set based on whether the login is for a web page form or an http/ftp authentication site login.
...fo = new nslogininfo( hostname, formsubmiturl, httprealm, username, password, usernamefield, passwordfield ); examples creating a login for a web page var formlogininfo = new nslogininfo( 'http://www.example.com', 'http://login.example.com', null, 'joe', 'secret123', 'uname', 'pword' ); this login would correspond to a html form such as: <form action="http://login.example.com/foo/authenticate.cgi"> <div>please log in.</div> <label>username:</label> <input type="text" name="uname"> <label>password:</label> <input type="password" name="pword"> </form> creating a site authentication login var authlogininfo = new nslogininfo( 'http://www.example.com', null, 'exampleco login', 'alice', 'secret321', "", "" ); this would correspond to a login on http://www.example.com wh...
...en the server sends a reply such as: http/1.0 401 authorization required server: apache/1.3.27 www-authenticate: basic realm="exampleco login" creating a local extension login var extlogininfo = new nslogininfo( 'chrome://firefoo', null, 'user registration', 'bob', '123secret', "", "" ); from a component creating a new info block is done slightly differently: var nslogininfo = new constructor("@org/manager/ci.init"); var extlogininfo = new aformsubmiturl, ausername, ausernamefield, ...
nsILoginManager
ahttprealm for protocol logins, specify the http realm for which the login applies; this is obtained from the www-authenticate header (see rfc 2617).
...called when looking for logins that might be applicable to a given form or authentication request.
... ahttprealm for protocol logins, specify the http realm for which the login applies; this is obtained from the www-authenticate header (see rfc 2617).
nsIMessenger
if this window contains a messagepane element (i think this may mean a xul:browser element with its id set to "messagepane"?), then the nsidocshell will be used for future nsimessenger operations.
... if there is no messagepane element, then the root xul nsidocshell will be used (so that openurl() will still work).
... if null is passed in then observers are removed in preparation for shutdown.
nsINavHistoryObserver
if an error occurs in between these two steps (for example, an out of memory error), then you may get a notification even though the page doesn't wind up getting deleted.
...if an error occurs in between these two steps (for example, an out of memory error), then you may get a notification even though the page doesn't wind up getting deleted.
...if a page entry is removed, then you can be sure that we don't have anymore visits for it.
nsINavHistoryResultTreeViewer
it's important to be aware of this—if you want to reuse the same viewer, you need to keep your own reference to it, then reinitialize it when the tree changes.
... if you use this object and attach it to a result without attaching it to a tree, then forget about it, it will leak.
...when you sort by date, the multiple entries will then appear because they will be separated (unless you clicked reload a bunch of times in a row).
nsIPushSubscription
the remote server can use these keys to encrypt and authenticate message payloads.
... auth the shared authentication secret, used as the salt in the hkdf invocation.
... request = cc["@mozilla.org/xmlextras/xmlhttprequest;1"] .createinstance(ci.nsixmlhttprequest); request.open("post", "https://example.com/register-for-push", true); request.addeventlistener("error", () => { cu.reporterror("error sending subscription to server"); }); request.send(json.stringify({ endpoint: subscription.endpoint, // base64-encode the key and authentication secret.
nsISessionStore
if the previously saved value was originally a complex data (ie a javascript object) it can then be deserialized using json.parse cf.
... if the preference browser.sessionstate.enabled is false when this method is called, then you will get an exception about "awindows[i] has no properties".
... if the previously saved value was originally a complex data (ie a javascript object) it can then be deserialized using json.parse cf.
nsIURL
if the url denotes a path to a directory and not a file, for example http://host/foo/bar/, then the directory attribute accesses the complete /foo/bar/ portion, and the filename is the empty string.
... if the trailing slash is omitted, then the directory is /foo/ and the file is bar (that is this is a syntactic, not a semantic breakdown of the path).
...if the url denotes a path to a directory and not a file, for example http://host/foo/bar/, then the directory attribute accesses the complete /foo/bar/ portion, and the filename is the empty string.
nsIWebProgressListener
for any given request, onstatechange() is called once with the state_start flag, zero or more times with the state_transferring flag or once with the state_redirecting flag, and then finally once with the state_stop flag.
...if activity only occurs in a child nsiwebprogress instance, then this flag will be set to indicate the start and stop of that activity.
... note: if any progress value is unknown, or if its value would exceed the maximum value of type long, then its value is replaced with -1.
nsIWindowMediator
example: of window listener object and how to register then unregister.
... this example below waits for listens to when a window opens, and then after that window opens it adds event listener to listen to when the window completes loading, after that it fires a function.
... important: this will attach the functionality to future opened windows, so if you copy paste this code to scratchpad, then after running this script, you need to open a new window by pressing ctrl + n and then in the new window, selecting tabs will fire the alert.
Mail and RDF
(the details of rdf resource factories will be left to rdf documentation for now.) from an rdf resource, it is possible to queryinterface() to the appropriate mail/news object, and then access information from there.
...to get the total messages, the datasource would then call nsimsgfolder.gettotalmessages().
...the folder datasource then translates these property changes into onassert() or onunassert() calls to the observers.
Zombie compartments
for example, if i open https://bugzilla.mozilla.org/show_bug.cgi?id=668871 in one tab, then compartment(https://bugzilla.mozilla.org/show_bug.cgi?id=668871) will show up in about:memory.
... if i then open https://bugzilla.mozilla.org/show_bug.cgi?id=700547 and close the first tab, the same compartment will continue to be used.
... you could try waiting 20 minutes or so, then reload about:memory again.
CData
here is a method to read "malformed", it attempts to do readstring on it, if it errors then it tries to read it in another way, so this is an alternative to readstringreplacemalformed, it is an attempt at readingmalformed function readaschar8thenaschar16(stringptr, known_len, jschar) { // when reading as jschar it assumes max length of 500 // stringptr is either char or jschar, if you know its jschar for sure, pass 2nd arg as true // if known_len is passed, then assumption...
...but its not possible, it has be known, i tried this: //"stringptr.contents.tostring()" "95" //"stringptr.tostring()" "ctypes.unsigned_char.ptr(ctypes.uint64("0x7f73d5c87650"))" // so as we see neither of these is 77, this is for the example of "_scratchpad/entehandle.js at master · noitidart/_scratchpad mdnfirefox" // tries to do read string on stringptr, if it fails then it falls to read as jschar var readjscharstring = function() { var assumption_max_len = known_len ?
...har we see chineese characters in all spots expect spaces even null terminator is a chineese character console.info('ptrasarr.length:', ptrasarr.length); //console.log('debug-msg :: datacasted:', datacasted, uneval(datacasted), datacasted.tostring()); var charcode = []; var fromcharcode = [] for (var i=0; i<ptrasarr.length; i++) { //if known_len is correct, then will not hit null terminator so like in example of "_scratchpad/entehandle.js at master · noitidart/_scratchpad mdnfirefox" if you pass length of 77, then null term will not get hit by this loop as null term is at pos 77 and we go till `< known_len` var thisunsignedcharcode = ptrasarr.addressofelement(i).contents; if (thisunsignedcharcode == 0) { // reache...
Mozilla
the component can then call methods on the observer interface to signal the external code when predefined events occur.
...reftest will then compare them and verify whether they produce the same bitmap.
... integrated authentication this entails support for the the simple and protected gss-api negotiation mechanism (spnego) internet standard (rfc 2478) to negotiate either kerberos, ntlm, or other authentication protocols supported by the operating system.
PKCS #11 Netscape Trust Objects - Network Security Services
examples of purposes are: email, code signing, authenticating a server.
... cka_trust_server_auth ck_trust level of trust for server authentication purpose.
... cka_trust_client_auth ck_trust level of trust for client authentication purpose.
Browser Toolbox - Firefox Developer Tools
note: if you want to debug a specific add-on that is restartless or sdk-based then try the add-on debugger.
... opening the browser toolbox open the browser toolbox through the menu button and the menu items "developer" then "browser toolbox".
...altogether you will have access to the following developer tools: debugger (note: if you want to debug a specific add-on that is restartless or sdk-based then try the add-on debugger.) console style editor performance network monitor page inspector accessibility inspector you can debug chrome: and about: pages using the normal debugger, just as if they were ordinary content pages.
Examine, modify, and watch variables - Firefox Developer Tools
if a variable exists in the source but has been optimized away by the javascript engine, then it is shown in the variables view, but is given the value (optimized away), and is not editable.
...you can then examine the results of these expressions.
... then start running your code.
Set event listener breakpoints - Firefox Developer Tools
use event breakpoints to stop execution at the triggering event for the action that fails, then step through the code or watch the console to see what happens.
...selecting this and then choosing some events to break on will mean that when you step through code, information about events fired will be logged to the console instead of the devtools breaking on each one.
... so if we choose to log keyboard events, for example, the code no longer pauses as each event is fired: instead, we can then switch to the console, and whenever we press a key we are given a log of where related events were fired.
Debugger.Frame - Firefox Developer Tools
if the non-debuggee function eventually calls back into debuggee code, then those frames are visible.
... when spidermonkey calls an onpop handler for a frame that is throwing an exception or being terminated, and the handler returns undefined, then spidermonkey proceeds with the exception or termination.
... ifcode is not strict mode code, then variable declarations incode affect the environment of this frame.
Debugger.Memory - Firefox Developer Tools
ifdbg is a debugger instance, then the methods and accessor properties of dbg.memory control howdbg observes its debuggees’ memory use.
... allocation logging ifdbg is a debugger instance, and dbg.memory.trackingallocationsites is set to true, then the javascript engine logs each object allocated bydbg’s debuggee code.
... accessor properties of the debugger.memory.prototype object ifdbg is a debugger instance, then <i>dbg</i>.memory is a debugger.memory instance, which inherits the following accessor properties from its prototype: trackingallocationsites a boolean value indicating whether this debugger.memory instance is capturing the javascript execution stack when each object is allocated.
Debugger.Object - Firefox Developer Tools
if the referent uses destructuring parameters, then the array’s elements reflect the structure of the parameters.
...} then this debugger.object instance’s parameternames property would have the value: ["a", ["b", "c"], {d:"d", e:"f"}] script if the referent is a function that is debuggee code, this is that function’s script, as a debugger.script instance.
...these are: return values of then() calls on the promise.
Dominators - Firefox Developer Tools
so when an object becomes unreachable (for example, because it is only referenced by a single local variable which goes out of scope) then any objects it references also become unreachable, as long as no other objects reference them: conversely, this means that objects are kept alive as long as some other reachable object is holding a reference to them.
...node b is said to dominate node a if every path from the root to a passes through b: if any of node a's dominators are freed, then node a itself becomes eligible for garbage collection.
... if node b dominates node a, but does not dominate any of a's other dominators, then b is the immediate dominator of a: one slight subtlety here is that if an object a is referenced by two other objects b and c, then neither object is its dominator, because you could remove either b or c from the graph, and a would still be retained by its other referrer.
Edit CSS filters - Firefox Developer Tools
once you have added an effect, enter the settings you want and then press enter to update the effect.
... type a name for your preset, and then click the plus sign to add it to the list of presets.
... you can then apply saved filters to new elements.
Allocations - Firefox Developer Tools
then record a profile as usual, and you will see a new tab labeled "allocations" in the toolbar: anatomy of the allocations view the allocations view looks something like this: the allocations view periodically samples allocations that are made over the recording.
... with a garbage-collected language, like javascript, the runtime periodically needs to walk the heap looking for objects that are no longer reachable, and then freeing the memory they occupy.
... if a gc event was caused by allocation pressure, then the sidebar on the right of the marker in the waterfall view contains a link labeled "show allocation triggers".
Waterfall - Firefox Developer Tools
recalculate style: if the browser thinks the computed styles for page elements have changed, it must then recalculate them.
...one last step is not shown in this sequence: the page may be split into layers, which are painted independently and then combined in a process called "composition".
... for example, consider code like this: var timerbutton = document.getelementbyid("timer"); timerbutton.addeventlistener("click", handleclick, false); function handleclick() { console.time("timer"); runtimer(1000).then(timerfinished); } function timerfinished() { console.timeend("timer"); console.log("ready!"); } function runtimer(t) { return new promise(function(resolve) { settimeout(resolve, t); }); } the waterfall will display a marker for the period between time() and timeend(), and if you select it, you'll see the async stack in the sidebar: timestamp markers timestamps enable you to mar...
Web Audio Editor - Firefox Developer Tools
within that context they then construct a number of audio nodes, including: nodes providing the audio source, such as an oscillator or a data buffer source nodes performing transformations such as delay and gain nodes representing the destination of the audio stream, such as the speakers each node has zero or more audioparam properties that configure its operation.
...you can then examine and edit the audioparam properties for each node in the graph.
...if, instead, you've connected a node to an audioparam in another node, then the connection is shown as a dashed line between the nodes, and is labeled with the name of the audioparam: inspecting and modifying audionodes if you click on a node, it's highlighted and you get a node inspector on the right hand side.
Console messages - Firefox Developer Tools
the console then provides a link to the filename and line number that generated the message.
...then any messages or errors your source generates will show up in the web console with a link back to the original source, not the compressed version.
... however, if some javascript code reads a style that has been modified, then the browser must perform a synchronous reflow in order to calculate the computed style to return.
Web Console remoting - Firefox Developer Tools
this document describes the latest protocol, with changes that have been made since then.
...the web console can then inspect the arguments.
...this nodeactor can then be referred to by the $0 jsterm helper.
AddressErrors - Web APIs
request.show().then(function(instrumentresponse) { // do something with the response from the ui.
... that's done by removing all shipping options currently set on the request, then set up an object named shippingaddresserrors which contains a country property which is an error message describing why the stated country isn't being permitted as a value.
... then a paymentdetailsupdate object is created with its error set to a generic message about address errors and with the reset of the object's values taken from shippingaddresserrors, and, using "...defaultpaymentdetails" as the final entry in the object, the remeainder of the properties' values are taken from defaultpaymentdetails.
AudioContext.createMediaElementSource() - Web APIs
the createmediaelementsource() method of the audiocontext interface is used to create a new mediaelementaudiosourcenode object, given an existing html <audio> or <video> element, the audio from which can then be played and manipulated.
... example this simple example creates a source from an <audio> element using createmediaelementsource(), then passes the audio through a gainnode before feeding it into the audiodestinationnode for playback.
...yscript.innerhtml; // create a mediaelementaudiosourcenode // feed the htmlmediaelement into it var source = audioctx.createmediaelementsource(myaudio); // create a gain node var gainnode = audioctx.creategain(); // create variables to store mouse pointer y coordinate // and height of screen var cury; var height = window.innerheight; // get new mouse pointer coordinates when mouse is moved // then set new gain value document.onmousemove = updatepage; function updatepage(e) { cury = (window.event) ?
AudioContext.createMediaStreamTrackSource() - Web APIs
then a biquadfilternode is created using createbiquadfilter(), and it's configured as desired to perform a lowshelf filter on the audio coming from the source.
... the output from the microphone is then routed into the new biquad filter, and the filter's output is in turn routed to the audio context's destination.
... 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.frequency.value = 3000; biquadfilter.gain.value = 20; source.connect(biquadfilter); biquadfilter.connect(audioctx.destination); }) .catch(function(err) { // handle getusermedia() error }); specifications specification status comment web audio apithe definition of 'createmediastreamtracksource()' in that specification.
AudioScheduledSourceNode.start() - Web APIs
if no time is specified, then the sound begins playing immediately.
...if 0 is passed then the playback will start from the beginning.
...if no value is passed then the duration will be equal to the length of the audio buffer minus the offset value return value undefined exceptions invalidstatenode the node has already been started.
BaseAudioContext.createBuffer() - Web APIs
the createbuffer() method of the baseaudiocontext interface is used to create a new, empty audiobuffer object, which can then be populated by data, and played via an audiobuffersourcenode for more details about audio buffers, check out the audiobuffer reference page.
...the asynchronous method decodeaudiodata() does the same thing — takes compressed audio, say, an mp3 file, and directly gives you back an audiobuffer that you can then set to play via in an audiobuffersourcenode.
... now let's look at a more complex createbuffer() example, in which we create a three second buffer, fill it with white noise, and then play it via an audiobuffersourcenode.
Body.body - Web APIs
WebAPIBodybody
example in our simple stream pump example we fetch an image, expose the response's stream using response.body, create a reader using readablestream.getreader(), then enqueue that stream's chunks into a second, custom readable stream — effectively creating an identical copy of the image.
... const image = document.getelementbyid('target'); // fetch the original image fetch('./tortoise.png') // retrieve its body as readablestream .then(response => response.body) .then(body => { const reader = body.getreader(); return new readablestream({ start(controller) { return pump(); function pump() { return reader.read().then(({ done, value }) => { // when no more data needs to be consumed, close the stream if (done) { controller.close(); return; } // enqueue the next data chunk into our target stream controller.enqueue(value); return pump(); }); } } }) }) .then(stream => new response(stream)) .then(response => response.blob()) .then(blob => url.createobjec...
...turl(blob)) .then(url => console.log(image.src = url)) .catch(err => console.error(err)); specifications specification status comment fetchthe definition of 'body' in that specification.
Body.bodyUsed - Web APIs
WebAPIBodybodyUsed
example in our fetch request example (run fetch request live), we create a new request using the request() constructor, then use it to fetch a jpg.
... when the fetch is successful, we read a blob out of the response using blob(), put it into an object url using url.createobjecturl, and then set that url as the source of an <img> element to display the image.
... html content <img class="my-image" src="https://udn.realityripple.com/samples/46/29059a2b39.png"> js content var myimage = document.queryselector('.my-image'); fetch('https://upload.wikimedia.org/wikipedia/commons/7/77/delete_key1.jpg').then(function(response) { console.log(response.bodyused); var res = response.blob(); console.log(response.bodyused); return res; }).then(function(response) { var objecturl = url.createobjecturl(response); myimage.src = objecturl; }); specifications specification status comment fetchthe definition of 'bodyused' in that specification.
Using the CSS properties and values API - Web APIs
in this example, the custom property --registered has been registered using the syntax <color> and then used in a linear gradient.
... that property is then transitioned on hover or focus to a different color.
...when registered, though, you've told the browser what type of value it should expect, and because it knows that, it can then set up the transitions properly.
Cache.match() - Web APIs
WebAPICachematch
syntax cache.match(request, {options}).then(function(response) { // do something with the response }); parameters request the request for which you are attempting to find responses in the cache.
...if our if() condition is false, then this fetch handler won't intercept the request.
... if (event.request.method === 'get' && event.request.headers.get('accept').indexof('text/html') !== -1) { console.log('handling fetch event for', event.request.url); event.respondwith( fetch(event.request).catch(function(e) { console.error('fetch failed; returning offline page instead.', e); return caches.open(offline_cache).then(function(cache) { return cache.match(offline_url); }); }) ); } }); specifications specification status comment service workersthe definition of 'cache match' in that specification.
CacheStorage.has() - Web APIs
WebAPICacheStoragehas
syntax caches.has(cachename).then(function(boolean) { // true: your cache exists!
...if not then we run some kind of cache set-up function.
... caches.has('v1').then(function(hascache) { if (!hascache) { somecachesetupfunction(); } else { caches.open('v1').then(function(cache) { return cache.addall(myassets); }); } }).catch(function() { // handle exception here.
CacheStorage.match() - Web APIs
syntax caches.match(request, options).then(function(response) { // do something with the response }); parameters request the request you want to match.
... self.addeventlistener('fetch', function(event) { event.respondwith(caches.match(event.request).then(function(response) { // caches.match() always resolves // but in case of success response will have value if (response !== undefined) { return response; } else { return fetch(event.request).then(function (response) { // response may be used only once // we need to save clone to put one copy in cache // and serve second one let responsecl...
...one = response.clone(); caches.open('v1').then(function (cache) { cache.put(event.request, responseclone); }); return response; }).catch(function () { return caches.match('/sw-test/gallery/mylittlevader.jpg'); }); } })); }); specifications specification status comment service workersthe definition of 'cachestorage: match' in that specification.
CanvasRenderingContext2D.setTransform() - Web APIs
the canvasrenderingcontext2d.settransform() method of the canvas 2d api resets (overrides) the current transformation to the identity matrix, and then invokes a transformation described by the arguments of this method.
...we apply a transform to the first one's context using the first type of settransform() and draw a square on it, then retrieve the matrix from it using canvasrenderingcontext2d.gettransform().
... we then apply the retrieved matrix directly to the second canvas context by passing the dommatrix object directly to settransform() (i.e.
Applying styles and colors - Web APIs
note: when you set the strokestyle and/or fillstyle property, the new value becomes the default for all shapes being drawn from then on.
...it is then equal to the cosecant of half the minimum inner angle of connecting segments below which no miter join will be rendered, but only a bevel join: miterlimit = max miterlength / linewidth = 1 / sin ( min θ / 2 ) the default miter limit of 10.0 will strip all miters for sharp angles below about 11 degrees.
...we can then assign this object to the fillstyle or strokestyle properties.
Clients.openWindow() - Web APIs
syntax self.clients.openwindow(url).then(function(windowclient) { // do something with your windowclient }); parameters url a usvstring representing the url of the client you want to open in the window.
...location.origin + '/some/path' }, // data: { url: 'http://example.com' }, }; self.registration.shownotification('you\'ve got messages!', notificationobject); } // notification click event listener self.addeventlistener('notificationclick', e => { // close the notification popout e.notification.close(); // get all the window clients e.waituntil(clients.matchall({ type: 'window' }).then(clientsarr => { // if a window tab matching the targeted url already exists, focus that; const hadwindowtofocus = clientsarr.some(windowclient => windowclient.url === e.notification.data.url ?
... if (!hadwindowtofocus) clients.openwindow(e.notification.data.url).then(windowclient => windowclient ?
Clipboard.write() - Web APIs
WebAPIClipboardwrite
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.
...then write() is called, specifying both a fulfilment function and an error function.
... 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.
Content Index API - Web APIs
the browser can then use these entries to display offline reading to a user.
... feature detection and interface access here we get a reference to the serviceworkerregistration, then check for the index property, which gives us access to the content index interface.
... self.addeventlistener('contentdelete', (event) => { console.log(event.id); // logs content index id, which can then be used to determine what content to delete from your cache }); the contentdelete event is only fired when the deletion happens due to interaction with the browser's built-in user interface.
CredentialsContainer.get() - Web APIs
from the resulting set of credentials, it then selects the best one.
...for example: if options.password exists, then the passwordcredential.[[collectfromcredentialstore]] is called.
... web authentication: an api for accessing public key credentials level 1 recommendation initial definition.
DOMTokenList.toggle() - Web APIs
if set to false, then token will only be removed, but not added.
... if set to true, then token will only be added, but not removed.
...we then replace a token in the list, and write the list into the <span>'s node.textcontent.
DataTransfer.dropEffect - Web APIs
on setting, if the new value is one of the values listed below, then the property's current value will be set to the new value and other values will be ignored.
...in a dragend event, for instance, if the desired dropeffect is "move", then the data being dragged should be removed from the source.
... html content <div> <p id="source" ondragstart="dragstart_handler(event);" draggable="true"> select this element, drag it to the drop zone and then release the selection to move the element.
Document.cookie - Web APIs
WebAPIDocumentcookie
it can be easily bypassed using the dom, for example by creating a hidden <iframe> element with the path of the cookie, then accessing this iframe's contentdocument.cookie property.
... cookies are often used in web application to identify a user and their authenticated session.
... so stealing the cookie from a web application, will lead to hijacking the authenticated user's session.
Document.requestStorageAccess() - Web APIs
for example, if you want to configure firefox to automatically grant access on the first site where requeststorageaccess() is called and then prompt afterwards, you should adjust the value of the dom.storage_access.max_concurrent_auto_grants preference to 1.
... when the promise gets resolved, the resolve handler will run as if a user gesture is being processed, whether the promise was fulfilled or rejected: in the former case, code can then start to call apis that require user activation and things can move forward.
... examples document.requeststorageaccess().then( () => { console.log('access granted') }, () => { console.log('access denied') } ); specifications the api is currently only at the proposal stage — the standardization process has yet to begin.
How whitespace is handled by HTML, CSS, and in the DOM - Web APIs
if an element contains at least one block element, then it instead establishes what is called a block formatting context.
...blocks occupy the full width available and are stacked on top of each other, which means that we end up with a layout composed of this list of blocks: <block>⏎⇥</block> <block>◦◦hello◦◦</block> <block>⏎◦◦◦</block> <block>◦◦world!◦◦</block> <block>◦◦⏎</block> this is then simplified further by applying the processing rules for whitespace in inline formatting contexts to these blocks: <block></block> <block>hello</block> <block></block> <block>world!</block> <block></block> the 3 empty blocks we now have are not going to occupy any space in the final layout, because they don’t contain anything, so we’ll end up with only 2 blocks taking up space in the ...
...it iterates over the children of an element (whose children are all elements) to find the one whose text is "this is the third paragraph", and then changes the class attribute and the contents of that paragraph.
FileSystemFlags.create - Web APIs
true false path exists the existing file or directory is removed and replaced with a new one, then the successcallback is called with a filesystemfileentry or a filesystemdirectoryentry, as appropriate.
... true false path doesn't exist the file or directory is created, then a filesystemfileentry or a filesystemdirectoryentry is passed to the successcallback, as appropriate.
... true true path doesn't exist the file or directory is created, then a filesystemfileentry or a filesystemdirectoryentry is passed to the successcallback, as appropriate.
FileSystemFlags.exclusive - Web APIs
true false path exists the existing file or directory is removed and replaced with a new one, then the successcallback is called with a filesystemfileentry or a filesystemdirectoryentry, as appropriate.
... true false path doesn't exist the file or directory is created, then a filesystemfileentry or a filesystemdirectoryentry is passed to the successcallback, as appropriate.
... true true path doesn't exist the file or directory is created, then a filesystemfileentry or a filesystemdirectoryentry is passed to the successcallback, as appropriate.
FileSystemFlags - Web APIs
true false path exists the existing file or directory is removed and replaced with a new one, then the successcallback is called with a filesystemfileentry or a filesystemdirectoryentry, as appropriate.
... true false path doesn't exist the file or directory is created, then a filesystemfileentry or a filesystemdirectoryentry is passed to the successcallback, as appropriate.
... true true path doesn't exist the file or directory is created, then a filesystemfileentry or a filesystemdirectoryentry is passed to the successcallback, as appropriate.
HTMLCanvasElement - Web APIs
if no [separate] css height is assigned to the <canvas>, then this value will also be used as the height of the canvas in the length-unit css pixel.
...if no [separate] css width is assigned to the <canvas>, then this value will also be used as the width of the canvas in the length-unit css pixel.
...the callback can get the context to draw to from the printstate object and must then call done() on it when finished.
HTMLImageElement.decode() - Web APIs
usage notes one potential use case for decode(): when loading very large images (for example, in an online photo album), you can present a low resolution thumbnail image initially and then replace that image with the full-resolution image by instantiating a new htmlimageelement, setting its source to the full-resolution image's url, then using decode() to get a promise which is resolved once the full-resolution image is ready for use.
... at that time, you can then replace the low-resolution image with the full-resolution one that's now available.
... const img = new image(); img.src = 'nebula.jpg'; img.decode() .then(() => { document.body.appendchild(img); }) .catch((encodingerror) => { // do something with the error.
HTMLScriptElement - Web APIs
there are three possible execution modes: if the async attribute is present, then the script will be executed asynchronously as soon as it downloads.
... if the async attribute is absent but the defer attribute is present, then the script is executed when the page has finished parsing.
... if neither attribute is present, then the script is fetched and executed immediately, blocking further parsing of the page.
In depth: Microtasks and the JavaScript runtime environment - Web APIs
as one of these code segments begins execution, a new context is constructed in which to run it; that context is then destroyed when the code exits.
...it then runs any pending javascript tasks, then any pending microtasks, then performs any needed rendering and painting before looping again to check for pending tasks.
... the event loop, then, drives everything that happens in the browser as it pertains to the interaction with the user, but more importantly for our purposes here, it is responsible for the scheduling and execution of every piece of code that runs within its thread.
The HTML DOM API - Web APIs
the element, then, includes the anchor-specific properties and methods described in that class's documentation, but also those defined by htmlelement and element, as well as from node and, finally, eventtarget.
... then addeventlistener() is called to add a handler for the input event to the user name input.
... this code looks at the length of the current value of the input; if it's zero, then the "send" button is disabled if it's not already disabled.
Working with the History API - Web APIs
suppose now that the user navigates to http://google.com, then clicks the back button.
... suppose now that the user navigates to http://www.microsoft.com, then clicks the back button.
... this can happen, for example, if the page sets a state object (using pushstate() or replacestate()) and then the user restarts their browser.
IDBFactory.open() - Web APIs
WebAPIIDBFactoryopen
if an error occurs while the database connection is being opened, then an error event is fired on the request object returned from this method.
...if the version is not provided and the database exists, then a connection to the database will be opened without changing its version.
... if the version is not provided and the database does not exist, then it will be created with version 1.
IDBIndex.count() - Web APIs
WebAPIIDBIndexcount
example in the following example we open a transaction and an object store, then get the index lname from a simple contacts database.
... we then open a basic cursor on the index using idbindex.opencursor — this works the same as opening a cursor directly on an objectstore using idbobjectstore.opencursor except that the returned records are sorted based on the index, not the primary key.
... myindex.count() is then used to count the number of records in the index, and the result of that request is logged to the console when its success callback returns.
IDBIndex.getKey() - Web APIs
WebAPIIDBIndexgetKey
example in the following example we open a transaction and an object store, then get the index lname from a simple contacts database.
... we then open a basic cursor on the index using idbindex.opencursor — this works the same as opening a cursor directly on an objectstore using idbobjectstore.opencursor except that the returned records are sorted based on the index, not the primary key.
... myindex.getkey('bungle') is then used to retrieve the primary key of the record with an lname of bungle, and the result of that request is logged to the console when its success callback returns.
IDBIndex - Web APIs
WebAPIIDBIndex
if false, then there is one record for each key that is an array.
... example in the following example we open a transaction and an object store, then get the index lname from a simple contacts database.
... we then open a basic cursor on the index using idbindex.opencursor — this works the same as opening a cursor directly on an objectstore using idbobjectstore.opencursor except that the returned records are sorted based on the index, not the primary key.
KeyboardEvent.key - Web APIs
WebAPIKeyboardEventkey
if the key is held down further and the key produces a character key, then the event continues to be emitted in a platform implementation dependent interval and the keyboardevent.repeat read only property is set to true.
... try experimenting using the following two test cases: press and hold the shift key, then press 2 and release it.
... press and hold the shift key, then press and hold 2.
KeyboardEvent - Web APIs
num lock was supported on some older laptop models (2007 models and older), but since then, macos hasn't supported num lock even on external keyboards.
...on those platforms, then, an auto-repeat key will generate the following sequence of events: keydown keypress keyup keydown keypress keyup <<repeating until the user releases the key>> keyup in these environments, unfortunately, there's no way for web content to tell the difference between auto-repeating keys and keys that are just being pressed repeatedly.
... working draft the keyboardevent interface specification went through numerous draft versions, first under dom events level 2 where it was dropped as no consensus arose, then under dom events level 3.
MediaDeviceInfo.groupId - Web APIs
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 devli...
MediaPositionState.playbackRate - Web APIs
this information can then, in turn, be used by the user agent to provide a user interface which displays media playback information to the viewer.
...negative values can be specified to indicate the media is playing in reverse, with decreasing values then indicating faster and faster reverse playback.
...it begins by creating a mediapositionstate object, then submits it to the browser it by calling navigator.mediasession.setpositionstate().
Using the Media Capabilities API - Web APIs
handling the response instead of the assigning the promise to a variable, we can output the values returned by the promise to the console: navigator.mediacapabilities.decodinginfo(videoconfiguration).then(result => { console.log('this configuration is ' + (result.supported ?
... navigator.mediacapabilities.decodinginfo(videoconfiguration).then( console.log('it worked') ).catch(error => console.log('it failed: ' + error) ); media capabilities live example css li { margin : 1em; } html <form> <p>select your video configuration and find out if this browser supports the codec, and whether decoding will be smooth and power efficient:</p> <ul> <li> <label for="codec">select a codec</label> <select id="codec"> <opt...
... type: 'file', video: { contenttype: document.getelementbyid('codec').value, width: size[0], height: size[1], bitrate: document.getelementbyid('bitrate').value, framerate: document.getelementbyid('framerate').value, } } }, testit: function () { let content = ''; navigator.mediacapabilities.decodinginfo(mc.videoconfiguration).then(result => { var li = document.createelement('li'), mcv = mc.videoconfiguration.video; content = 'a ' + mcv.width + 'x' + mcv.height + ', ' + mcv.contenttype + ' at ' + mcv.framerate + 'fps and ' + mcv.bitrate + ' bps video ' + (result.supported ?
Media Capabilities API - Web APIs
examples detect audio file support and expected performance this example defines a audio configuration then checks to see if the user agent supports decoding that media configuration, and whether it will perform well in terms of smoothness and power efficiency.
... 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 ?
... to test support, smoothness and power efficiency of a video or audio file, you define the media configuration you want to test, and then pass the audio or video configuration as the parameter of the mediacapabilities interface's encodinginfo() and decodinginfo() methods.
Media Session API - Web APIs
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'...
...the following example adds a pointerup event to an on-page play button, which is then used to kick off the media session code: playbutton.addeventlistener('pointerup', function(event) { var audio = document.queryselector('audio'); // user interacted with the page.
... audio.play() .then(_ => { /* set up media session controls, as shown above.
Microdata DOM API - Web APIs
if there are no tokens specified in the argument, then the method must return a nodelist containing all the top-level microdata items in the document.
... code example this sample gets the first item of type "http://example.net/user" and then pops up an alert using the "name" property from that item.
...this script looks up the first such item and then lists all its values.
Node.insertBefore() - Web APIs
WebAPINodeinsertBefore
if this is null, then newnode is inserted at the end of parentnode's child nodes.
... in the previous example, sp1 could be inserted after sp2 using: parentdiv.insertbefore(sp1, sp2.nextsibling) if sp2 does not have a next sibling, then it must be the last child — sp2.nextsibling returns null, and sp1 is inserted at the end of the child node list (immediately after sp2).
... // get the parent element let parentelement = document.getelementbyid('parentelement') // get the parent's first child let thefirstchild = parentelement.firstchild // create a new element let newelement = document.createelement("div") // insert the new element before the first child parentelement.insertbefore(newelement, thefirstchild) when the element does not have a first child, then firstchild is null.
Notification.requestPermission() - Web APIs
syntax the latest spec has updated this method to a promise-based syntax that works like this: notification.requestpermission().then(function(permission) { ...
...possible values for this string are: granted denied default examples assume this basic html: <button onclick="notifyme()">notify me!</button> it's possible to send a notification as follows — here we present a fairly verbose and complete set of code you could use if you wanted to first check whether notifications are supported, then check if permission has been granted for the current origin to send notifications, then request permission if required, before then sending a notification.
... notification"); } // let's check whether notification permissions have already been granted else if (notification.permission === "granted") { // if it's okay let's create a notification var notification = new notification("hi there!"); } // otherwise, we need to ask the user for permission else if (notification.permission !== "denied") { notification.requestpermission().then(function (permission) { // if the user accepts, let's create a notification if (permission === "granted") { var notification = new notification("hi there!"); } }); } // at last, if the user has denied notifications, and you // want to be respectful there is no need to bother them any more.
OfflineAudioContext - Web APIs
we use the audiocontext to load an audio track via xhr (audiocontext.decodeaudiodata), then the offlineaudiocontext to render the audio into an audiobuffersourcenode and play the track through.
...this is then played as part of a simple standard audio graph.
... request.open('get', 'viper.ogg', true); request.responsetype = 'arraybuffer'; request.onload = function() { var audiodata = request.response; audioctx.decodeaudiodata(audiodata, function(buffer) { mybuffer = buffer; source.buffer = mybuffer; source.connect(offlinectx.destination); source.start(); //source.loop = true; offlinectx.startrendering().then(function(renderedbuffer) { console.log('rendering completed successfully'); var song = audioctx.createbuffersource(); song.buffer = renderedbuffer; song.connect(audioctx.destination); play.onclick = function() { song.start(); } }).catch(function(err) { console.log('rendering failed: ' + err); // note: the promis...
PaymentRequest: merchantvalidation event - Web APIs
request.addeventlistener("merchantvalidation", event => { event.complete(async () => { const merchantserverurl = window.location.origin + '/validate?url=' + encodeuricomponent(event.validationurl); // get validation data, and complete validation; return await fetch(merchantserverurl).then(response => response.text()); }, false); }; const response = await request.show(); how merchant server handles the validation depends on the server implementation and payment method documentation.
... the content delivered by the validation server is forwarded to the merchant server and is then returned from the fetch() call's fulfillment handler to the complete() method on the event.
... you can also use the onmerchantvalidation event handler property to set up the handler for this event: request.onmerchantvalidation = event => { event.complete(async () => { const merchantserverurl = window.location.origin + '/validate?url=' + encodeuricomponent(event.validationurl); // get validation data, and complete validation; return await fetch(merchantserverurl).then(response => response.text()); }); }; const response = await request.show(); for more information, see merchant validation in payment processing concepts.
Pointer Lock API - Web APIs
the buttons are then freed up for other actions.
...when you click the canvas, pointer lock is then used to remove the mouse pointer and allow you to move the ball directly using the mouse.
...to avoid this limitation, first unlock the locked iframe, and then lock the other.
PublicKeyCredentialCreationOptions.user - Web APIs
this an opaque identifier which can be used by the authenticator to link the user account with its corresponding credentials.
... this value will later be used when fetching the credentials in authenticatorassertionresponse.userhandle.
...in.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 credentials level 1the definition of 'user' in th...
PushManager.getSubscription() - Web APIs
syntax ​pushmanager.getsubscription().then(function(pushsubscription) { ...
...(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?
... serviceworkerregistration.pushmanager.getsubscription() .then(function(subscription) { // enable any ui which subscribes / unsubscribes from // push messages.
PushSubscription.getKey() - Web APIs
the getkey() method of the pushsubscription interface returns an arraybuffer representing a client public key, which can then be sent to a server and used in encrypting push message data.
... auth: an authentication secret, as described in message encryption for web push.
... example reg.pushmanager.getsubscription() .then(function(subscription) { // enable any ui which subscribes / unsubscribes from // push messages.
RTCPeerConnection: negotiationneeded event - Web APIs
pc.addeventlistener("negotiationneeded", ev => { pc.createoffer() .then(offer => return pc.setlocaldescription(offer)) .then(() => sendsignalingmessage({ type: "video-offer", sdp: pc.localdescription })) .catch(err => { /* handle error */ ); }, false); after creating the offer, the local end is configured by calling rtcpeerconnection.setlocaldescription(); then a signaling message is created and sent to the remote peer through the signaling serv...
...the other peer should recognize this message and follow up by creating its own rtcpeerconnection, setting the remote description with setremotedescription(), and then creating an answer to send back to the offering peer.
... you can also set an event handler for the negotiationneeded event by assigning the event handler function to the rtcpeerconnection.onnegotiationneeded property: pc.onnegotiationneeded = ev => { pc.createoffer() .then(offer => return pc.setlocaldescription(offer)) .then(() => sendsignalingmessage({ type: "video-offer", sdp: pc.localdescription })) .catch(err => { /* handle error */ ); }; for a more detailed example, see starting negotiation in signaling and video calling.
RTCPeerConnection.setLocalDescription() - Web APIs
only then does the agreed-upon configuration take effect.
...they're interchangeable: mypeerconnection.createoffer().then(function(offer) { return mypeerconnection.setlocaldescription(offer); }); this is equivalent to: mypeerconnection.createoffer().then(function(offer) { return mypeerconnection.setlocaldescription(new rtcsessiondescription(offer)); }); for this reason, the rtcsessiondescription() constructor is deprecated.
...we can then send the newly-created offer along to the other peer using the signaling server, which here is done by calling a function called signalremotepeer().
ReadableStream.cancel() - Web APIs
var searchterm = "service workers"; // chars to show either side of the result in the match var contextbefore = 30; var contextafter = 30; var caseinsensitive = true; var url = 'https://html.spec.whatwg.org/'; console.log(`searching '${url}' for '${searchterm}'`); fetch(url).then(response => { console.log('received headers'); var decoder = new textdecoder(); var reader = response.body.getreader(); var tomatch = caseinsensitive ?
... searchterm.tolowercase() : searchterm; var buffersize = math.max(tomatch.length - 1, contextbefore); var bytesreceived = 0; var buffer = ''; var matchfoundat = -1; return reader.read().then(function process(result) { if (result.done) { console.log('failed to find match'); return; } bytesreceived += result.value.length; console.log(`received ${bytesreceived} bytes of data so far`); buffer += decoder.decode(result.value, {stream: true}); // already found match & just context-gathering?
...tafter) { console.log("here's the match:") console.log(buffer.slice( math.max(0, matchfoundat - contextbefore), matchfoundat + tomatch.length + contextafter )); console.log("cancelling fetch"); reader.cancel(); return; } else { console.log('found match, but need more context…'); } // keep reading return reader.read().then(process); }); }).catch(err => { console.log("something went wrong.
ReadableStream.pipeThrough() - Web APIs
signal: if set to an abortsignal object, ongoing pipe operations can then be aborted via the corresponding abortcontroller.
...next, we log the contents of the readable stream, use pipethrough() to send it to a new function that creates a gray-scaled version of the stream, then log the new stream's contents too.
... // fetch the original image fetch('png-logo.png') // retrieve its body as readablestream .then(response => response.body) .then(rs => logreadablestream('fetch response stream', rs)) // create a gray-scaled png stream out of the original .then(body => body.pipethrough(new pngtransformstream())) .then(rs => logreadablestream('png chunk stream', rs)) specifications specification status comment streamsthe definition of 'pipethrough()' in that specification.
Report - Web APIs
WebAPIReport
reports can be accessed in a number of ways: via the reportingobserver.takerecords() method — this returns all reports in an observer's report queue, and then empties the queue.
... examples in our deprecation_report.html example, we create a simple reporting observer to observe usage of deprecated features on our web page: let options = { types: ['deprecation'], buffered: true } let observer = new reportingobserver(function(reports, observer) { reportbtn.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(); because of the event handler we set up inside the reportingobserver() constructor, we can now click the button to display the report details.
...we loop over each report using a basic for loop, then iterate over each entry of in the report's body using a for...in structure, displaying each key/value pair inside a list item.
Request - Web APIs
WebAPIRequest
examples in the following snippet, we create a new request using the request() constructor (for an image file in the same directory as the script), then return some property values of the request: const request = new request('https://www.mozilla.org/favicon.ico'); const url = request.url; const method = request.method; const credentials = request.credentials; you could then fetch this request by passing the request object in as a parameter to a windoworworkerglobalscope.fetch() call, for example: fetch(request) .then(response => response.b...
...lob()) .then(blob => { image.src = url.createobjecturl(blob); }); in the following snippet, we create a new request using the request() constructor with some initial data and body content for an api request which need a body payload: const request = new request('https://example.com', {method: 'post', body: '{"foo": "bar"}'}); const url = request.url; const method = request.method; const credentials = request.credentials; const bodyused = request.bodyused; note: the body type can only be a blob, buffersource, formdata, urlsearchparams, usvstring or readablestream type, so for adding a json object to the payload you need to stringify that object.
... you could then fetch this api request by passing the request object in as a parameter to a windoworworkerglobalscope.fetch() call, for example and get the response: fetch(request) .then(response => { if (response.status === 200) { return response.json(); } else { throw new error('something went wrong on api server!'); } }) .then(response => { console.debug(response); // ...
Resize Observer API - Web APIs
the window resize event), then figure out what the new dimensions or other features of the element after a resize using element.getboundingclientrect or window.getcomputedstyle, for example.
... usage is simple, and pretty much the same as other observers, such as performance observer or intersection observer — you create a new resizeobserver object using the resizeobserver() constructor, then use resizeobserver.observe() to make it look for changes to a specific element's size.
... a callback function set up inside the constructor then runs every time the size changes, providing access to the new dimensions and allowing you to do anything you like in response to those changes.
Using the Storage Access API - Web APIs
if that call returns false, we can then call document.requeststorageaccess(), returning the result so that then we can chain it onto the previous promise call.
... in the final then, we'll have first-party storage access.
... document.hasstorageaccess().then(hasaccess => { if (!hasaccess) { return document.requeststorageaccess(); } }).then(_ => { // now we have first-party storage access!
SubtleCrypto.deriveBits() - Web APIs
we then use alice's private key and bob's public key to derive a shared secret.
...pairs // separately and exchange public keys securely const generatealiceskeypair = window.crypto.subtle.generatekey( { name: "ecdh", namedcurve: "p-384" }, false, ["derivebits"] ); const generatebobskeypair = window.crypto.subtle.generatekey( { name: "ecdh", namedcurve: "p-384" }, false, ["derivebits"] ); promise.all([generatealiceskeypair, generatebobskeypair]).then(values => { const aliceskeypair = values[0]; const bobskeypair = values[1]; const derivebitsbutton = document.queryselector(".ecdh .derive-bits-button"); derivebitsbutton.addeventlistener("click", () => { // alice then generates a secret using her private key and bob's public key.
... derivesharedsecret(aliceskeypair.privatekey, bobskeypair.publickey); }); }); pbkdf2 in this example we ask the user for a password, then use it to derive some bits using pbkdf2.
SubtleCrypto.digest() - Web APIs
hint: if you are looking here for how to create an keyed-hash message authentication code (hmac), you need to use the subtlecrypto.sign() instead.
... examples basic example this example encodes a message, then calculates its sha-256 digest and logs the digest length: const text = 'an obscure body in the s-k system, your majesty.
...this example calculates a digest, then converts the arraybuffer to a hex string: const text = 'an obscure body in the s-k system, your majesty.
SubtleCrypto - Web APIs
cryptography functions these are the functions you can use to implement security features such as privacy and authentication in a system.
... if the key is sensitive you should use wrapkey(), which exports the key and then encrypts it using another key; the api calls a "key-wrapping key".
... the inverse of wrapkey() is unwrapkey(), which decrypts then imports the key.
Compressed texture formats - Web APIs
ext.compressed_rgba_s3tc_dxt1_ext for the webgl_compressed_texture_s3tc extension.) these can then be used with compressedteximage[23]d or compressedtexsubimage[23]d instead of teximage2d calls.
... note that webgl makes no functionality available to compress or decompress textures: they must already be in a compressed format and can then be directly uploaded to video memory.
...ssedtextureifavailable(gl) { const texture = gl.createtexture(); gl.bindtexture(gl.texture_2d, texture); // create texture object on gpu const ext = gl.getextension('webgl_compressed_texture_s3tc'); // will be null if not supported if (ext) { // the file is already in the correct compressed format const dataarraybuffer = await fetch('/textures/foobar512x512.rgba_s3tc_dxt1') .then(response => response.arraybuffer()); gl.compressedteximage2d(gl.texture_2d, 0, // set the base image level ext.compressed_rgba_s3tc_dxt1_ext, // the compressed format we are using 512, 512, // width, height of the image 0, // border, always 0 new dataview(dataarraybuffer)); gl.generatemipmap(); // create mipmap levels, like we would for a standard image r...
Using shaders to apply color in WebGL - Web APIs
to do this, we first need to create an array of vertex colors, then store it into a webgl buffer.
...then a new webgl buffer is allocated to store these colors, and the array is converted into floats and stored into the buffer.
... then, drawscene() can have the following added to it so it actually uses these colors when drawing the square: // tell webgl how to pull out the colors from the color buffer // into the vertexcolor attribute.
Lifetime of a WebRTC session - Web APIs
one peer can output a data object that can be printed out, physically carried (on foot or by carrier pigeon) to another device, entered into that device, and a response then output by that device to be returned on foot, and so forth, until the webrtc peer connection is open.
...then media shifts to the new network connection and the old one is closed.
...then handle the connection process from then on just like you normally would.
Writing WebSocket client applications - Web APIs
see the code, then try out the example for yourself.
... connection errors if an error occurs while attempting to connect, first a simple event with the name error is sent to the websocket object (thereby invoking its onerror handler), and then the closeevent is sent to the websocket object (thereby invoking its onclose handler) to indicate the reason for the connection's closing.
...erlist": var ul = ""; for (i=0; i < msg.users.length; i++) { ul += msg.users[i] + "<br>"; } document.getelementbyid("userlistbox").innerhtml = ul; break; } if (text.length) { f.write(text); document.getelementbyid("chatbox").contentwindow.scrollbypages(1); } }; here we use json.parse() to convert the json object back into the original object, then examine and act upon its contents.
Basic concepts behind Web Audio API - Web APIs
audio nodes are linked via their inputs and outputs, forming a chain that starts with one or more sources, goes through one or more nodes, then ends up at a destination.
... when a buffer plays, you will hear the left most sample frame, and then the one right next to it, etc.
... visualizations in general, audio visualizations are achieved by accessing an output of audio data over time, usually gain or frequency data, and then using a graphical technology to turn that into a visual output, such as a graph.
Migrating from webkitAudioContext - Web APIs
the example below shows old code which downloads an audio file over the network, and then decoded it using createbuffer(): var xhr = new xmlhttprequest(); xhr.open("get", "/path/to/audio.ogg", true); xhr.responsetype = "arraybuffer"; xhr.send(); xhr.onload = function() { var decodedbuffer = context.createbuffer(xhr.response, false); if (decodedbuffer) { // decoding was successful, do something useful with the audio buffer } else { alert("decoding the audio buffer failed...
...type = "arraybuffer"; xhr.send(); xhr.onload = function() { context.decodeaudiodata(xhr.response, function onsuccess(decodedbuffer) { // decoding was successful, do something useful with the audio buffer }, function onfailure() { alert("decoding the audio buffer failed"); }); }; note that the decodeaudiodata() method is asynchronous, which means that it will return immediately, and then when the decoding finishes, one of the success or failure callback functions will get called depending on whether the audio decoding was successful.
...instead of setting a gain property directly on an audio source, you connect the source to a gain node and then control the gain using that node's gain parameter.
Using the Web Audio API - Web APIs
we'll briefly look at some concepts, then study a simple boombox example that allows us to load an audio track, play and pause it, and change its volume and stereo panning.
...this then gives us access to all the features and functionality of the api.
...we'll use the factory method in our code: const gainnode = audiocontext.creategain(); now we have to update our audio graph from before, so the input is connected to the gain, then the gain node is connected to the destination: track.connect(gainnode).connect(audiocontext.destination); this will make our audio graph look like this: the default value for gain is 1; this keeps the current volume the same.
Web audio spatialization basics - Web APIs
the pannernode can then calculate its sound position relative to the position of the listener.
...we can keep that at the default value of 1 as well: const refdistance = 1; then there's the roll-off factor (rollofffactor) — how quickly does the volume reduce as the panner moves away from the listener.
...first, we'll get references to the elements we want to move, then we'll store references to the values we'll change when we set up css transforms to actually do the movement.
Window.openDialog() - Web APIs
WebAPIWindowopenDialog
these parameters may be used, then, to pass arguments to and from the dialog window.
... passing extra parameters to the dialog to pass extra parameters into the dialog, you can simply supply them after the windowfeatures parameter: opendialog("http://example.tld/zzz.xul", "dlg", "", "pizza", 6.98); the extra parameters will then get packed into a property named arguments of type array, and this property gets added to the newly opened dialog window.
...you can then access this object from within the dialog code and set properties on it, containing the values you want to return or preserve past the window.close() operation.
WritableStream.WritableStream() - Web APIs
it then calls a function called sendmessage(), passing the newly created stream and a string.
... const list = document.queryselector('ul'); function sendmessage(message, writablestream) { // defaultwriter is of type writablestreamdefaultwriter const defaultwriter = writablestream.getwriter(); const encoder = new textencoder(); const encoded = encoder.encode(message, { stream: true }); encoded.foreach((chunk) => { defaultwriter.ready .then(() => { return defaultwriter.write(chunk); }) .then(() => { console.log("chunk written to sink."); }) .catch((err) => { console.log("chunk error:", err); }); }); // call ready again to ensure that all chunks are written // before closing the writer.
... defaultwriter.ready .then(() => { defaultwriter.close(); }) .then(() => { console.log("all chunks written"); }) .catch((err) => { console.log("stream error:", err); }); } const decoder = new textdecoder("utf-8"); const queuingstrategy = new countqueuingstrategy({ highwatermark: 1 }); let result = ""; const writablestream = new writablestream({ // implement the sink write(chunk) { return new promise((resolve, reject) => { var buffer = new arraybuffer(2); var view = new uint16array(buffer); view[0] = chunk; var decoded = decoder.decode(view, { stream: true }); var listitem = document.createelement('li'); listitem.textcontent = "chunk decoded: " + decoded; list.appendchild(listitem); result += de...
WritableStream.getWriter() - Web APIs
it then calls a function called sendmessage(), passing the newly created stream and a string.
... const list = document.queryselector('ul'); function sendmessage(message, writablestream) { // defaultwriter is of type writablestreamdefaultwriter const defaultwriter = writablestream.getwriter(); const encoder = new textencoder(); const encoded = encoder.encode(message, { stream: true }); encoded.foreach((chunk) => { defaultwriter.ready .then(() => { return defaultwriter.write(chunk); }) .then(() => { console.log("chunk written to sink."); }) .catch((err) => { console.log("chunk error:", err); }); }); // call ready again to ensure that all chunks are written // before closing the writer.
... defaultwriter.ready .then(() => { defaultwriter.close(); }) .then(() => { console.log("all chunks written"); }) .catch((err) => { console.log("stream error:", err); }); } const decoder = new textdecoder("utf-8"); const queuingstrategy = new countqueuingstrategy({ highwatermark: 1 }); let result = ""; const writablestream = new writablestream({ // implement the sink write(chunk) { return new promise((resolve, reject) => { var buffer = new arraybuffer(2); var view = new uint16array(buffer); view[0] = chunk; var decoded = decoder.decode(view, { stream: true }); var listitem = document.createelement('li'); listitem.textcontent = "chunk decoded: " + decoded; list.appendchild(listitem); result += de...
WritableStream - Web APIs
it then calls a function called sendmessage(), passing the newly created stream and a string.
... const list = document.queryselector('ul'); function sendmessage(message, writablestream) { // defaultwriter is of type writablestreamdefaultwriter const defaultwriter = writablestream.getwriter(); const encoder = new textencoder(); const encoded = encoder.encode(message, { stream: true }); encoded.foreach((chunk) => { defaultwriter.ready .then(() => { return defaultwriter.write(chunk); }) .then(() => { console.log("chunk written to sink."); }) .catch((err) => { console.log("chunk error:", err); }); }); // call ready again to ensure that all chunks are written // before closing the writer.
... defaultwriter.ready .then(() => { defaultwriter.close(); }) .then(() => { console.log("all chunks written"); }) .catch((err) => { console.log("stream error:", err); }); } const decoder = new textdecoder("utf-8"); const queuingstrategy = new countqueuingstrategy({ highwatermark: 1 }); let result = ""; const writablestream = new writablestream({ // implement the sink write(chunk) { return new promise((resolve, reject) => { var buffer = new arraybuffer(2); var view = new uint16array(buffer); view[0] = chunk; var decoded = decoder.decode(view, { stream: true }); var listitem = document.createelement('li'); listitem.textcontent = "chunk decoded: " + decoded; list.appendchild(listitem); result += de...
WritableStreamDefaultWriter.WritableStreamDefaultWriter() - Web APIs
it then calls a function called sendmessage(), passing the newly created stream and a string.
... const list = document.queryselector('ul'); function sendmessage(message, writablestream) { // defaultwriter is of type writablestreamdefaultwriter const defaultwriter = writablestream.getwriter(); const encoder = new textencoder(); const encoded = encoder.encode(message, { stream: true }); encoded.foreach((chunk) => { defaultwriter.ready .then(() => { return defaultwriter.write(chunk); }) .then(() => { console.log("chunk written to sink."); }) .catch((err) => { console.log("chunk error:", err); }); }); // call ready again to ensure that all chunks are written // before closing the writer.
... defaultwriter.ready .then(() => { defaultwriter.close(); }) .then(() => { console.log("all chunks written"); }) .catch((err) => { console.log("stream error:", err); }); } const decoder = new textdecoder("utf-8"); const queuingstrategy = new countqueuingstrategy({ highwatermark: 1 }); let result = ""; const writablestream = new writablestream({ // implement the sink write(chunk) { return new promise((resolve, reject) => { var buffer = new arraybuffer(2); var view = new uint16array(buffer); view[0] = chunk; var decoded = decoder.decode(view, { stream: true }); var listitem = document.createelement('li'); listitem.textcontent = "chunk decoded: " + decoded; list.appendchild(listitem); result += de...
WritableStreamDefaultWriter.close() - Web APIs
it then calls a function called sendmessage(), passing the newly created stream and a string.
... const list = document.queryselector('ul'); function sendmessage(message, writablestream) { // defaultwriter is of type writablestreamdefaultwriter const defaultwriter = writablestream.getwriter(); const encoder = new textencoder(); const encoded = encoder.encode(message, { stream: true }); encoded.foreach((chunk) => { defaultwriter.ready .then(() => { return defaultwriter.write(chunk); }) .then(() => { console.log("chunk written to sink."); }) .catch((err) => { console.log("chunk error:", err); }); }); // call ready again to ensure that all chunks are written // before closing the writer.
... defaultwriter.ready .then(() => { defaultwriter.close(); }) .then(() => { console.log("all chunks written"); }) .catch((err) => { console.log("stream error:", err); }); } const decoder = new textdecoder("utf-8"); const queuingstrategy = new countqueuingstrategy({ highwatermark: 1 }); let result = ""; const writablestream = new writablestream({ // implement the sink write(chunk) { return new promise((resolve, reject) => { var buffer = new arraybuffer(2); var view = new uint16array(buffer); view[0] = chunk; var decoded = decoder.decode(view, { stream: true }); var listitem = document.createelement('li'); listitem.textcontent = "chunk decoded: " + decoded; list.appendchild(listitem); result += de...
XMLSerializer - Web APIs
var s = new xmlserializer(); var d = document; var str = s.serializetostring(d); savexml(str); this involves creating a new xmlserializer object, then passing the document to be serialized into serializetostring(), which returns the xml equivalent of the document.
... note: in the real world, you should usually instead call importnode() method to import the new node into the dom, then call one of the following methods to add the node to the dom tree: the document and element methods append() and prepend() the node.replacewith() method (to replace an existing node with the new one) the document.insertadjacentelement() and element.insertadjacentelement() methods.
... var inp = document.createelement('input'); var xmls = new xmlserializer(); var inp_xmls = xmls.serializetostring(inp); // first convert dom node into a string // insert the newly created node into the document's body document.body.insertadjacenthtml('afterbegin', inp_xmls); the code creates a new <input> element by calling document.createelement(), then serializes it into xml using serializetostring().
XRRigidTransform() - Web APIs
examples in this example, the beginning of the animation of a scene is shown, starting with a request for a reference space of a given type, then shifting the coordinate system based on a transform before requesting the first animation frame.
... let animationframerequestid = 0; xrsession.requestreferencespace("local-floor") .then((refspace) => { xrreferencespace = refspace.getoffsetreferencespace( new xrrigidtransform(viewerposition, viewerorientation)); animationframerequestid = xrsession.requestanimationframe(drawframe); }); after requesting a reference space of type local-floor, the returned promise is eventually resolved, at which time we receive a new reference space object, refspace.
... then requestanimationframe() is called to ask for a new animation frame to draw into.
XRRigidTransform.matrix - Web APIs
the returned matrix can then be premultiplied with a column vector to rotate the vector by the 3d rotation specified by the orientation, then translate it by the position.
... [100px010py001pz0001]\begin{bmatrix} 1 & 0 & 0 & x\\ 0 & 1 & 0 & y\\ 0 & 0 & 1 & z\\ 0 & 0 & 0 & 1 \end{bmatrix} then a rotation matrix is created by computing a column-vector rotation matrix from the unit quaternion specified by orientation: [1-2(qy2+qz2)2(qxqy-qzqw)2(qxqz+qyqw)02(qxqy+qzqw)1-2(qx2+qz2)2(qyqz-qxqw)02(qxqz-qyqw)2(qyqz+qxqw)1-2(qx2+qy2)00001]\begin{bmatrix} 1 - 2(q_y^2 + q_z^2) & 2(q_xq_y - q_zq_w) & 2(q_xq_z + q_yq_w) & p_x\\ 2(q_xq_y + q_zq_w) & 1 - 2(q_x^2 + q_z^2) & 2(q_yq_z - q_xq_w) & p_y\...
...the matrix is then passed into a library function that uses webgl to render an object matching a given name using the transform matrix specified to position and orient it.
XRSession.onsqueezestart - Web APIs
the xrsession interface's onsqueezestart event handler property can be set to a function which is then invoked to handle the squeezestart event that's sent when the user successfully begins a primary squeeze action on a webxr input device.
... examples this snippet of code adds a simple handler for the squeezestart event, which responds only to events on the user's dominant hand by getting the target ray, then calling a function findobjectusingray() to identify the object that the user is pointing at.
... this object is then stored in a heldobject variable in the user object we're using to represent user information.
XRSession.requestAnimationFrame() - Web APIs
note: a real application should check that the device and the user agent support webxr api at all and then that they both support the desired session type via xr.issessionsupported().
... // 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, xrviewport.height) // webgl draw calls will now be rendered into the appropriate viewport.
...function startxrsession() { navigator.xr.requestsession('immersive-vr').then((session) => { xrsession = session xrsession.addeventlistener('end', onxrsessionended) // do necessary session setup here.
XRSystem - Web APIs
WebAPIXRSystem
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(() => { // onsessionstarted() not shown for reasons of brevity and clarity.
... 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.
...to determine this, we call issessionsupported(), passing it the desired session option before enabling the button, immersivebutton, which the user can then use to switch to immersive mode only if immersive vr mode is available.
ARIA Test Cases - Accessibility
alertdialog alert dialog yui alert dialog (3rd button in this page) expected at behavior: at should speak the fact that this is an alert, the title and contents of the dialog, then place virtual focus or the real focus on the desired control (like a button).
... markup used: role="img" notes: if the screen reader does not provide the required behavior, then most likely it is a browser issue, for not respecting "children presentational: true" for that role.
... - n/a - - zoom (leopard) pass n/a pass pass zoomtext - - - - orca - - - - menubar and menu yui menubar menubar 1 dojo nightly build - popup menu expected at behavior: (mz) as focus is placed inside a menu or menubar, a screen reader should announce the name (if any) of the menu, the role of the menu, and then read the current menu item.
ARIA: tabpanel role - Accessibility
the first rule of aria use is you can use a native feature with the semantics and behavior you require already built in, instead of re-purposing an element and adding an aria role, state or property to make it accessible, then do so.
... then post full details in best practices section below.
... examples fill in a simple example that nicely shows a typical usage of the property, then perhaps some more complex examples.
ARIA: tab role - Accessibility
then, if the right arrow is being pressed, we increase our tab focus counter by one.
...if the left arrow is being pressed, we decrease our tab focus counter by one, and if it is then less than 0, we set it number of tab elements minus one (to get to the last element).
...we then find all tabs with aria-selected=true inside the parent element and sets it to false, then sets the triggering element's aria-selected to true.
range - CSS: Cascading Style Sheets
if a counter value is outside the specified range, then the fallback style will be used to construct the representation of that marker.
... if value is auto, then for cyclic, numeric, and fixed system, the range will be from negative infinity to positive infinity.
...if infinite is specified as the first value in a range, then it is interpreted as negative infinity.
system - CSS: Cascading Style Sheets
if the algorithm specified in the system descriptor is unable to construct the representation for a particular counter value, then that value's representation will be constructed using the fallback system provided.
...if the characters "a" to "z" are specified as symbols in a counter style, with the alphabetic system, then the first 26 counter representations will be "a", "b" upto "z".
...however, in the numeric system, the first counter symbol is interpreted as 0, the next as 1, then 2, and so on.
Detecting CSS animation support - CSS: Cascading Style Sheets
then we check if the css animation-name property on the style collection for the element specified by the variable elem is set.
...if it is true then both the animation property name and the keyframe prefix will be the right ones.
...then the new <style> element is inserted into the document's <head>, thereby adding the new style sheet to the document.
Basic Concepts of Multicol - CSS: Cascading Style Sheets
the browser will then assign the correct amount of space to each column box to create the requested number of columns.
...the content, including the children of .container is then split between the three columns.
... using column-count and column-width together if you specify both properties on a multicol container then column-count will act as a maximum number of columns.
Using feature queries - CSS: Cascading Style Sheets
feature queries are created using the css at-rule @supports, and are useful as they give web developers a way to test to see if a browser has support for a certain feature, and then provide css that will only run based on the result of that test.
...it doesn't matter which value you use in a lot of cases: if all you want is to check that the browser supports this property, then any valid value will do.
... in the above scenario, it doesn't matter that ie11 doesn't support feature queries or css grid — it would get the floated version anyway, which is then overwritten by browsers that do support grid.
CSS Containment - CSS: Cascading Style Sheets
the browser can then use this information to make decisions about how to render the content.
...with height: auto), then the browser may need to account for its size changing).
...the main use case is to prevent situations where a css counter could be changed in an element, which could then affect the rest of the tree.
CSS Grid Layout and Accessibility - CSS: Cascading Style Sheets
back in the early days of web design, the way we constructed page layout was to use html tables, then fragment our design into the cells of those tables in order to create a layout.
...the ultimate aim being that we could create a semantic and well structured document, then apply css to create the layout we desired.
...an example would be where some content was semantically marked up as a list but you decide to use a set of <div> elements instead as then you can have the element to be a direct child of a container set to display: grid.
Consistent list indentation - CSS: Cascading Style Sheets
if it's changed to inside, then the markers are brought inside the <li>'s content, as though they're an inline box placed at the very beginning of the <li>.
...if you want to reproduce the default display in netscape 6.x, you write: ul {margin-left: 0; padding-left: 40px;} if you're more interested in following the internet explorer/opera model, then: ul {margin-left: 40px; padding-left: 0;} of course, you can fill in your own preferred values.
...if you want to reset lists to have no indentation, then you still have to zero out both padding and margin: ul {margin-left: 0; padding-left: 0;} remember, though, that in so doing, you'll have the bullets hanging outside the list and its parent element.
Basic Shapes - CSS: Cascading Style Sheets
our circle therefore accepts one radius value, which may be a length, a percentage or the closest-side or farthest side keyword then optionally the keyword at followed by a position value.
...i have then set the position value to 30%.
... these may then be followed by position values as with circle() to move the centre of the ellipse around.
Using CSS custom properties (variables) - CSS: Cascading Style Sheets
custom properties allow a value to be stored in one place, then referenced in multiple other places.
...if you had written color: 16px without any variable substitutes, then it was a syntax error.
... the previous declaration will then be used.
box-lines - CSS: Cascading Style Sheets
WebCSSbox-lines
if a value of multiple is specified, however, then the box is allowed to expand to multiple lines (that is, multiple rows or columns) in order to accommodate all of its children.
... if the children in a horizontal box still do not fit on a line after being reduced to their minimum widths, then children are moved one by one onto a new line, until the elements remaining on the previous line fit.
...if a line contains only a single element that doesn't fit, then the element should stay on that line and overflow out of the box.
calc() - CSS: Cascading Style Sheets
WebCSScalc
then, to ensure that input fields retain an appropriate size, we use calc() again to establish that they should be the width of their container minus 1em.
... then, the following html makes use of this css: <form> <div id="formbox"> <label>type something:</label> <input type="text"> </div> </form> nested calc() with css variables you can also use calc() with css variables.
... consider the following code: .foo { --widtha: 100px; --widthb: calc(var(--widtha) / 2); --widthc: calc(var(--widthb) / 2); width: var(--widthc); } after all variables are expanded, widthc's value will be calc( calc( 100px / 2) / 2), then when it's assigned to .foo's width property, all inner calc()s (no matter how deeply nested) will be flattened to just parentheses, so the width property's value will be eventually calc( ( 100px / 2) / 2), i.e.
Adapting to the new two-value syntax of display - CSS: Cascading Style Sheets
if you remove the line display: flow-root then the float will poke out of the bottom of the box.
... if only an inner value of flex, grid, or flow-root is specified then the specification explains that the outer value should be set to block: "if a <display-inside> value is specified but <display-outside> is omitted, the element’s outer display type defaults to block—except for ruby, which defaults to inline." finally, we have some legacy pre-composed inline-level values of: inline-block inline-table inline-flex inline-grid if a supporting browser ...
...comes across these as single values then it treats them the same as the two-value versions: inline flow-root inline table inline flex inline grid so all of the current situations are neatly covered, meaning that we maintain compatibility of existing and new sites that use the single values, while allowing the spec to evolve.
repeat() - CSS: Cascading Style Sheets
WebCSSrepeat
if the size of the grid container depends on the size of its tracks, then the <percentage> must be treated as auto.
... auto-fill if the grid container has a definite or maximal size in the relevant axis, then the number of repetitions is the largest possible positive integer that does not cause the grid to overflow its grid container.
...if any number of repetitions would overflow, then the repetition is 1.
revert - CSS: Cascading Style Sheets
WebCSSrevert
but if you have a rule to make all paragraphs red then all paragraphs will still be red in all sections.
... so in the below example, we set custom font-weight in a global stylesheet, but then try to unset and revert.
...ht: normal; color: blue; } <h3 style="font-weight: unset; color: unset;">this will still have font-weight: normal, but color: black</h3> <p>just some text</p> <h3 style="font-weight: revert; color: revert;">this should have its original font-weight (bold) and color: black</h3> <p>just some text</p> revert all reverting all values is useful when you did heavy modifications for something and then want to revert to defaults.
Adding captions and subtitles to HTML5 video - Developer guides
first of all an option is added to allow the user to switch all subtitles off, and then buttons are added for each text track, reading the language and label from each one.
... once the menu is built, it is then inserted into the dom at the bottom of the videocontainer.
...n text-shadow background shorthand properties outline shorthand properties font shorthand properties, including line-height white-space for example, to change the text colour of the text track cues you can write: ::cue { color:#ccc; } if the webvtt file uses voice spans, which allow cues to be defined as having a particular "voice": 0 00:00:00.000 --> 00:00:12.000 <v test>[test]</v> then this specific 'voice' will be stylable like so: ::cue(v[voice='test']) { color:#fff; background:#0095dd; } note: some of the styling of cues with ::cue currently works on chrome, opera, and safari, but not yet on firefox.
Media events - Developer guides
then, in line 3, the example sets the element's currenttime attribute to 10.0, which initiates a seek operation to the 10-second mark in the media.
... this causes a seeking event to be sent when the operation begins, then a seeked event to be dispatched when the seek is completed.
... in other words, this example seeks to the 10-second mark in the media, then begins playback as soon as that's finished.
HTML5 Parser - Developer guides
WebGuideHTMLHTML5HTML5 Parser
if you previously tested your code in ie and opera, then you probably don't have any tags like this.
... if you tested your site only with gecko 1.x or webkit (for example, firefox-only intranets or webkit-oriented mobile sites), then you might have tags that match this pattern, and they will behave differently with gecko 2.
... some contexts from which you should not call document.write() include: scripts created using document.createelement() event handlers settimeout() setinterval() <script async src="..."> <script defer src="..."> if you use the same mechanism for loading script libraries for all browsers including ie, then your code probably will not be affected by this change.
The HTML autocomplete attribute - HTML: Hypertext Markup Language
perhaps the browser offers the ability to save encrypted credit card information, for autocompletion following an authentication procedure.
... if an <input>, <select> or <textarea> element has no autocomplete attribute, then browsers use the autocomplete attribute of the element's form owner, which is either the <form> element that the element is a descendant of, or the <form> whose id is specified by the form attribute of the element.
...this can be split further into two parts, for phone numbers which have an exchange number and then a number within the exchange.
disabled - HTML: Hypertext Markup Language
if this attribute is not specified, the control inherits its setting from the containing element, for example fieldset; if there is no containing element with the disabled attribute set, and the control itself does not have the attribute, then the control is enabled.
...if this attribute isn't set, the button can still be disabled from a containing element, for example <fieldset>; if there is no containing element with the disabled attribute set, then the button is enabled.
... constraint validation if the element is disabled, then the element's value can not receive focus and cannot be updated by the user, and does not participate in constraint validation.
HTML attribute: multiple - HTML: Hypertext Markup Language
by holding down shift or control, and then clicking).
...depending on the operating system, mouse users can hold the ctrl, command, or shift keys and then click multiple options to select/deselect them.
...when using the multiple attribute, inform the user that multiple values are allowed and provide directions on how to provide multiple values, such as "separate email addresses with a comma." setting size="1" on a multiple select can make it appear as a single select in some browsers, but then it doesn't expand on focus, harming usability.
<input type="button"> - HTML: Hypertext Markup Language
WebHTMLElementinputbutton
addeventlistener() is then used to establish a function that will be run when click events occur on the button.
...a settimeout() function is then used to reset the button back to its enabled state after two seconds.
...this makes it possible to enable and disable groups of elements all at once by enclosing them in a container such as a <fieldset> element, and then setting disabled on the container.
<input type="color"> - HTML: Hypertext Markup Language
WebHTMLElementinputcolor
here we establish some variables, setting up a variable that contains the color we'll set the color well to when we first load up, and then setting up a load handler to do the main startup work once the page is fully loaded.
...the page is loaded, our load event handler, startup(), is called: function startup() { colorwell = document.queryselector("#colorwell"); colorwell.value = defaultcolor; colorwell.addeventlistener("input", updatefirst, false); colorwell.addeventlistener("change", updateall, false); colorwell.select(); } this gets a reference to the color <input> element in a variable called colorwell, then sets the color input's value to the value in defaultcolor.
... then the color input's input event is set up to call our updatefirst() function, and the change event is set to call updateall().
<input type="range"> - HTML: Hypertext Markup Language
WebHTMLElementinputrange
if the value of the max attribute isn't a number, then the element has no maximum value.
... the default stepping value for range inputs is 1, allowing only integers to be entered, unless the stepping base is not an integer; for example, if you set min to -10 and value to 1.5, then a step of 1 will allow only values such as 1.5, 2.5, 3.5,...
... .slider-wrapper { display: inline-block; width: 20px; height: 150px; padding: 0; } then comes the style information for the <input> element within the reserved space: .slider-wrapper input { width: 150px; height: 20px; margin: 0; transform-origin: 75px 75px; transform: rotate(-90deg); } the size of the control is set to be 150 pixels long by 20 pixels tall.
<input type="week"> - HTML: Hypertext Markup Language
WebHTMLElementinputweek
if the value of the max attribute isn't a valid week string, then the element has no maximum value.
... we'll look at basic and more complex uses of <input type="week">, then offer advice on mitigating the browser support issue later on (see handling browser support).
...to detect whether the browser supports <input type="week">, we create a new <input> element, try setting its type to week, then immediately check what its type is set to.
<kbd>: The Keyboard Input element - HTML: Hypertext Markup Language
WebHTMLElementkbd
html <p>you can also create a new document using the keyboard shortcut <kbd><kbd>ctrl</kbd>+<kbd>n</kbd></kbd>.</p> this wraps the entire key sequence in an outer <kbd> element, then each individual key within its own, in order to denote the components of the sequence.
... result the output looks like this without a style sheet applied: with custom styles we can make more sense of this by adding some css: css we add a new style for <kbd> elements, key, which we can apply when rendering keyboard keys: kbd.key { border-radius: 3px; padding: 1px 2px 0; border: 1px solid black; } html then we update the html to use this class on the keys in the output to be presented: <p>you can also create a new document by pressing <kbd><kbd class="key">ctrl</kbd>+<kbd class="key">n</kbd></kbd>.</p> result the result is just what we want!
...then, inside that, both the menu and menu item names are contained within both <kbd> and <samp>, indicating an input which is selected from a screen widget.
<keygen> - HTML: Hypertext Markup Language
WebHTMLElementkeygen
(note that only a subset of the curves named there may actually be supported in any particular browser.) if the keyparams parameter string is not a recognized curve name string, then a curve is chosen according to the user's chosen key strength (low, medium, high), using the curve named "secp384r1" for high, and the curve named "secp256r1" for medium keys.
... publickeyandchallenge ::= sequence { spki subjectpublickeyinfo, challenge ia5string } signedpublickeyandchallenge ::= sequence { publickeyandchallenge publickeyandchallenge, signaturealgorithm algorithmidentifier, signature bit string } the public key and challenge string are der encoded as publickeyandchallenge, and then digitally signed with the private key to produce a signedpublickeyandchallenge.
...if no challenge string is provided, then it will be encoded as an ia5string of length zero.
<tr>: The Table Row element - HTML: Hypertext Markup Language
WebHTMLElementtr
the row's cells can then be established using a mix of <td> (data cell) and <th> (header cell) elements.
...then we set the bottom border of the top header to be a two-pixel wide line.
...end tag may be omitted if the <tr> element is immediately followed by a <tr> element, or if the row is the last element in its parent table group (<thead>, <tbody> or <tfoot>) element permitted parents <table> (only if the table has no child <tbody> element, and even then only after any <caption>, <colgroup>, and <thead> elements); otherwise, the parent must be <thead>, <tbody> or <tfoot> implicit aria role row permitted aria roles any dom interface htmltablerowelement specifications specification status comment html living standardthe definition of 'tr element' in that specification.
Content Security Policy (CSP) - HTTP
WebHTTPCSP
a csp compatible browser will then only execute scripts loaded in source files received from those allowlisted domains, ignoring all other script (including inline scripts and event-handling html attributes).
...to enable violation reporting, you need to specify the report-uri policy directive, providing at least one uri to which to deliver the reports: content-security-policy: default-src 'self'; report-uri http://reportcollector.example.com/collector.cgi then you need to set up your server to receive the reports; it can store or process them in whatever manner you determine is appropriate.
...if the blocked uri is from a different origin than the document-uri, then the blocked uri is truncated to contain just the scheme, host, and port.
Compression in HTTP - HTTP
compression happens at three different levels: first some file formats are compressed with specific optimized methods, then general encryption can happen at the http level (the resource is transmitted compressed from end to end), and finally compression can be defined at the connection level, between two nodes of an http connection.
... some formats can be used for both loss-less or lossy compression, like webp, and usually lossy algorithm can be configured to compress more or less, which then of course leads to less or more quality.
... hop-by-hop compression hop-by-hop compression, though similar to end-to-end compression, differs by one fundamental element: the compression doesn't happen on the resource in the server, creating a specific representation that is then transmitted, but on the body of the message between any two nodes on the path between the client and the server.
HTTP conditional requests - HTTP
the more flexible one makes use of if-unmodified-since and if-match and the server returns an error if the precondition fails; the client then restarts the download from the beginning: even if this method works, it adds an extra response/request exchange when the document has been changed.
...the concept is to allow all clients to get copies of the resource, then let them modify it locally, controlling concurrency by successfully allowing the first client submitting an update.
...it is then up to the client to deal with the error: either by notifying the user to start again (this time on the newest version), or by showing the user a diff of both versions, helping them decide which changes they wish to keep.
Configuring servers for Ogg media - HTTP
include regular key frames when the browser seeks through ogg media to a specified time, it has to seek to the nearest key frame before the seek target, then download and decode the video from there until the requested target time.
...you'll need to convert it to seconds only, then serve that as your x-content-duration value.
... just parse out the hh, mm, and ss into numbers, then do (hh*3600)+(mm*60)+ss to get the value you should report.
Protocol upgrade mechanism - HTTP
for example, opening a websocket connection is as simple as: websocket = new websocket("ws://destination.server.ext", "optionalprotocol"); the websocket() constructor does all the work of creating an initial http/1.1 connection then handling the handshaking and upgrade process for you.
...in essence, then, this key simply confirms that "yes, i really mean to open a websocket connection." this header is automatically added by clients that choose to use it; it cannot be added using the xmlhttprequest.setrequestheader() method.
...that value is then base64 encoded to obtain the value of this property.
A re-introduction to JavaScript (JS tutorial) - JavaScript
the special values infinity and -infinity: 1 / 0; // infinity -1 / 0; // -infinity you can test for infinity, -infinity and nan values using the built-in isfinite() function: isfinite(1 / 0); // false isfinite(-infinity); // false isfinite(nan); // false the parseint() and parsefloat() functions parse a string until they reach a character that isn't valid for the specified number format, then return the number parsed up to that point.
...it creates a brand new empty object, and then calls the function specified, with this set to that new object.
...makeadder() then returns a newly created function.
JavaScript data types and data structures - JavaScript
special primitive type having additional usage for its value: if object is not inherited, then null is shown; object : typeof instance === "object".
...unfortunately, when the separator is used in one of the "list" elements, then, the list is broken.
...with the object literal syntax, a limited set of properties are initialized; then properties can be added and removed.
Indexed collections - JavaScript
let myarray = new array('1', '2', '3', '4', '5') myarray.splice(1, 3, 'a', 'b', 'c', 'd') // myarray is now ["1", "a", "b", "c", "d", "5"] // this code started at index one (or where the "2" was), // removed 3 elements there, and then inserted all consecutive // elements in its place.
... if initialvalue is specified, then callback is called with initialvalue as the first parameter value and the value of the first item in the array as the second parameter value.
... if initialvalue is not specified, then callback's first two parameter values will be the first and second elements of the array.
constructor - JavaScript
class person { constructor(name) { this.name = name; } introduce() { console.log(`hello, my name is ${this.name}`); } } const otto = new person('otto'); otto.introduce(); if you don't provide your own constructor, then a default constructor will be supplied for you.
...the default constructor then takes care of initializing the parent error from the argument it is given.
... however, if you provide your own constructor, and your class derives from some parent class, then you must explicitly call the parent class constructor using super.
Array.from() - JavaScript
mapfn(kvalue, k) : mapfn.call(t, kvalue, k); } else { a[k] = kvalue; } } k += 1; } if (isiterator) { throw new typeerror( 'array.from: provided arraylike or iterator has length more then 2 ** 52 - 1' ); } else { a.length = len; } return a; }; // the length property of the from method is 1.
...if mapfn is undefined, then let mapping be false.
...if isconstructor(c) is true, then // 13.
FinalizationRegistry - JavaScript
}); then you register any objects you want a cleanup callback for by calling the `register` method, passing in the object and a *held value* for it: registry.register(theobject, "some value"); the registry does not keep a strong reference to the object, as that would defeat the purpose (if the registry held it strongly, the object would never be reclaimed).
...when a registered object is reclaimed, any cleanup callbacks for it may be called then, or some time later, or not at all.
...}); registering objects for cleanup then you register any objects you want a cleanup callback for by calling the `register` method, passing in the object and a *held value* for it: registry.register(theobject, "some value"); specifications specification weakrefsthe definition of 'finalizationregistry' in that specification.
Function.prototype.bind() - JavaScript
if you do not understand any of the deviations from the specification above, then it is safe in this particular case to not worry about these noncompliant deviation details.
... a common mistake for new javascript programmers is to extract a method from an object, then to later call that function and expect it to use the original object as its this (e.g., by using the method in callback-based code).
... these arguments (if any) follow the provided this value and are then inserted at the start of the arguments passed to the target function, followed by whatever arguments are passed bound function at the time it is called.
JSON.parse() - JavaScript
if that is so, then the text is safe for eval.
... walk({ "": j }, "") : j; } // if the text is not json parseable, then a syntaxerror is thrown.
...then it is called, with the object containing the property being processed as this, and with the property name as a string, and the property value as arguments.
Promise() constructor - JavaScript
therefore, the code within the executor has the opportunity to perform some operation and then reflect the operation's outcome(if the value is not another promise object) as either "fulfilled" or "rejected" by terminating with an invocation of either the resolutionfunc or the rejectionfunc, respectively.
... the promiseobj (asynchronously) invokes any .then() associated with it.
... the value received by promiseobj.then() is passed to the invocation of handlefulfilled as an input parameter (see "chained promises" section).
Promise.allSettled() - JavaScript
if the status is fulfilled, then a value is present.
... if the status is rejected, then a reason is present.
... examples using promise.allsettled promise.allsettled([ promise.resolve(33), new promise(resolve => settimeout(() => resolve(66), 0)), 99, promise.reject(new error('an error')) ]) .then(values => console.log(values)); // [ // {status: "fulfilled", value: 33}, // {status: "fulfilled", value: 66}, // {status: "fulfilled", value: 99}, // {status: "rejected", reason: error: an error} // ] specifications specification ecmascript (ecma-262)the definition of 'promise.allsettled' in that specification.
RegExpInstance.lastIndex - JavaScript
the following rules apply: if lastindex is greater than the length of the string, test() and exec() fail, then lastindex is set to 0.
... if lastindex is equal to or less than the length of the string and if the regular expression matches the empty string, then the regular expression matches input starting from lastindex.
... if lastindex is equal to the length of the string and if the regular expression does not match the empty string, then the regular expression mismatches input, and lastindex is reset to 0.
WebAssembly.Module - JavaScript
examples sending a compiled module to a worker the following example (see our index-compile.html demo on github, and view it live also) compiles the loaded simple.wasm byte code using the webassembly.compilestreaming() method and then sends the resulting module instance to a worker using postmessage().
... var worker = new worker("wasm_worker.js"); webassembly.compilestreaming(fetch('simple.wasm')) .then(mod => worker.postmessage(mod) ); in the worker (see wasm_worker.js) we define an import object for the module to use, then set up an event handler to receive the module from the main thread.
... var importobject = { imports: { imported_func: function(arg) { console.log(arg); } } }; onmessage = function(e) { console.log('module received from main thread'); var mod = e.data; webassembly.instantiate(mod, importobject).then(function(instance) { instance.exports.exported_func(); }); }; specifications specification webassembly javascript interfacethe definition of 'webassembly.module()' in that specification.
WebAssembly.Table() constructor - JavaScript
we then print out the table length and contents of the two indexes (retrieved via table.prototype.get() to show that the length is two and both elements are null.
... var tbl = new webassembly.table({initial:2, element:"anyfunc"}); console.log(tbl.length); // "2" console.log(tbl.get(0)); // "null" console.log(tbl.get(1)); // "null" we then create an import object that contains the table: var importobj = { js: { tbl:tbl } }; finally, we load and instantiate a wasm module (table2.wasm) using the webassembly.instantiatestreaming() method.
... webassembly.instantiatestreaming(fetch('table2.wasm'), importobject) .then(function(obj) { console.log(tbl.length); console.log(tbl.get(0)()); console.log(tbl.get(1)()); }); note how you've got to include a second function invocation operator at the end of the accessor to actually invoke the referenced function and log the value stored inside it (e.g.
WebAssembly.Table - JavaScript
we then print out the table length and contents of the two indexes (retrieved via table.prototype.get() to show that the length is two and both elements are null.
... var tbl = new webassembly.table({initial:2, element:"anyfunc"}); console.log(tbl.length); // "2" console.log(tbl.get(0)); // "null" console.log(tbl.get(1)); // "null" we then create an import object that contains the table: var importobj = { js: { tbl:tbl } }; finally, we load and instantiate a wasm module (table2.wasm) using the webassembly.instantiatestreaming() method.
... webassembly.instantiatestreaming(fetch('table2.wasm'), importobject) .then(function(obj) { console.log(tbl.length); console.log(tbl.get(0)()); console.log(tbl.get(1)()); }); note how you've got to include a second function invocation operator at the end of the accessor to actually invoke the referenced function and log the value stored inside it (e.g.
new operator - JavaScript
the following code adds a color property with value "original color" to all objects of type car, and then overwrites that value with the string "black" only in the instance object car1.
...then the value of mycar.make is the string "eagle", mycar.year is the integer 1993, and so on.
...for example: var kenscar = new car('nissan', '300zx', 1992); object property that is itself another object suppose you define an object called person as follows: function person(name, age, sex) { this.name = name; this.age = age; this.sex = sex; } and then instantiate two new person objects as follows: var rand = new person('rand mcnally', 33, 'm'); var ken = new person('ken jones', 39, 'm'); then you can rewrite the definition of car to include an owner property that takes a person object, as follows: function car(make, model, year, owner) { this.make = make; this.model = model; this.year = year; this.owner = owner; } to instantiate the new objects, you then use the following: var car1 = new car('eagle', '...
var - JavaScript
then, y is assigned the value 'a'.
...} f(); console.log(x, y); implicit globals and outer function scope variables that appear to be implicit globals may be references to variables in an outer function scope: var x = 0; // declares x within file scope, then assigns it a value of 0.
... console.log(typeof z); // "undefined", since z doesn't exist yet function a() { var y = 2; // declares y within scope of function a, then assigns it a value of 2.
Template literals (Template strings) - JavaScript
in that case, the tag expression (usually a function) gets called with the template literal, which you can then manipulate before outputting.
... for instance, if condition a is true, then return this templated literal.
... the tag function can then perform whatever operations on these arguments you wish, and return the manipulated string.
Autoplay guide for media and Web Audio APIs - Web media technologies
you might use code like this to accomplish the job: let startplaypromise = videoelem.play(); if (startplaypromise !== undefined) { startplaypromise.then(() => { // start whatever you need to do only after playback // has begun.
... if the promise returned by play() is resolved without error, the then() clause is run and can begin whatever needs to be done when autoplay has begun.
... we then add a catch() handler to the promise.
Performance fundamentals - Web Performance
then when the data is needed later, hopefully it's already available and the application doesn't have to wait.
...that doesn’t mean you can't use straight html as the source; just read it once and then scroll 10 elements, changing the content of the first and last accordingly to your position in the results list, instead of moving 100 elements that aren’t visible.
...if so, edit the static files to remove any private information, then send them to others for help (submit a bugzilla report, for example, or host it on a server and share the url).
Privacy, permissions, and information security
these start at the web server, include the very communication layer used over the network, and then extend through the web browser's security offerings before reaching your web app code and the efforts it takes to secure itself and the data the user entrusts to it.
...in this case, it's possible for the user to wind up being prompted repeatedly for that same resource, first by the main page, then by the document in the frame.
...for example, in firefox 73, the user permission requests were revised so that when an <iframe> uses the allow keyword to delegate permission to the embeded document, the browser asks the user to grant the parent document permission to use the resource, and that permission is then shared with the embedded content that requested the resource to begin with.
How to make PWAs installable - Progressive web apps (PWAs)
the installed web app can then be launched by users just as if it were any native app.
... these technologies allow the app to be launched directly from the device's home screen, rather than the user having to open the browser and then navigate to the site by using a bookmark or typing the url.
... summary in this article, we learned about how we can make pwas installable with a properly-configured web manifest, and how the user can then install the pwa with the "add to home screen" feature of their browser.
Graphic design for responsive sites - Progressive web apps (PWAs)
high res and low res image copies one option here is to create a hi res and a low res set of images, then use resolution media queries to serve the hi res images only to hi res devices.
... webgl/canvas you can create a canvas to draw interactive graphics on using the html <canvas> element, then use the canvas api to create shapes, lines, import image files, create text, do compositing operations, and much more.
... standard javascript can then be used to animate the image output, etc.
requiredExtensions - SVG: Scalable Vector Graphics
if all of the given extensions are supported, then the attribute evaluates to true; otherwise, the current element and its children are skipped and thus will not be rendered.
...if the attribute is used in other situations, then it represents a simple switch on the given element whether to render the element or not.
... if the attribute is not present, then it implicitly evaluates to "true".
rx - SVG: Scalable Vector Graphics
WebSVGAttributerx
the way the value of the rx attribute is interpreted depend on both the ry attribute and the width of the rectangle: if a properly specified value is provided for rx but not for ry (or the opposite), then the browser will consider the missing value equal to the defined one.
... if neither rx nor ry has a properly specified value, then the browser will draw a rectangle with square corners.
... if rx is greater than half of the width of the rectangle, then the browser will consider the value for rx as half of the width of the rectangle.
ry - SVG: Scalable Vector Graphics
WebSVGAttributery
the way the value of the ry attribute is interpreted depend on both the rx attribute and the width of the rectangle: if a properly specified value is provided for ry but not for rx (or the opposite), then the browser will consider the missing value equal to the defined one.
... if neither ry nor rx has a properly specified value, then the browser will draw a rectangle with square corners.
... if ry is greater than half of the width of the rectangle, then the browser will consider the value for ry as half of the width of the rectangle.
Getting started - SVG: Scalable Vector Graphics
then open the file in firefox.
...if you find that your server is not sending the headers with the values given above, then you should contact your web host.
...if your server is not configured to send the correct headers with the svg files it serves, then firefox will most likely show the markup of the files as text or encoded garbage, or even ask the viewer to choose an application to open them.
Positions - SVG: Scalable Vector Graphics
positions are then measured in pixels from the top left corner, with the positive x direction being to the right, and the positive y direction being to the bottom.
...(however, the device may decide, what it understands as one pixel.) lengths in the svg file with specific dimensions, like "in" or "cm", are then calculated in a way that makes them appear 1:1 in the resulting image.
...then, for all processing of svg content: [...] "1cm" equals "35.43307px" (and therefore 35.43307 user units) « previousnext » ...
How to turn off form autocompletion - Web security
if a browser keeps on making suggestions even after setting autocomplete to off, then you have to change the name attribute of the input element.
... for this reason, many modern browsers do not support autocomplete="off" for login fields: if a site sets autocomplete="off" for a <form>, and the form includes username and password input fields, then the browser still offers to remember this login, and if the user agrees, the browser will autofill those fields the next time the user visits the page.
... if a site sets autocomplete="off" for username and password <input> fields, then the browser still offers to remember this login, and if the user agrees, the browser will autofill those fields the next time the user visits the page.
Using custom elements - Web Components
in this case we attach a shadow root to the custom element, use some dom manipulation to create the element's internal shadow dom structure — which is then attached to the shadow root — and finally attach some css to the shadow root to style it.
...o apply to the shadow dom const style = document.createelement('style'); style.textcontent = '.wrapper {' + // css truncated for brevity // attach the created elements to the shadow dom this.shadowroot.append(style,wrapper); finally, we register our custom element on the customelementregistry using the define() method we mentioned earlier — in the parameters we specify the element name, and then the class name that defines its functionality: customelements.define('popup-info', popupinfo); it is now available to use on our page.
...the custom element looks like this: <custom-square l="100" c="red"></custom-square> the class constructor is really simple — here we attach a shadow dom to the element, then attach empty <div> and <style> elements to the shadow root: const shadow = this.attachshadow({mode: 'open'}); const div = document.createelement('div'); const style = document.createelement('style'); shadow.appendchild(style); shadow.appendchild(div); the key function in this example is updatestyle() — this takes an element, gets its shadow root, finds its <style> element, and adds width, he...
Using templates and slots - Web Components
this article explains how you can use the <template> and <slot> elements to create a flexible template that can then be used to populate the shadow dom of a web component.
... let's look at a trivial quick example: <template id="my-paragraph"> <p>my paragraph</p> </template> this won't appear in your page until you grab a reference to it with javascript and then append it to the dom, using something like the following: let template = document.getelementbyid('my-paragraph'); let templatecontent = template.content; document.body.appendchild(templatecontent); although trivial, you can already start to see how this could be useful.
... and because we are appending its contents to a shadow dom, we can include some styling information inside the template in a <style> element, which is then encapsulated inside the custom element.
Module structure of the SDK - Archive of obsolete content
for example, this add-on places external modules in a "dependencies" directory: my-addon lib main.js dependencies geolocation.js it can then load them in the same way it would load a local module.
... you can then use that to import commonjs modules.
private-browsing - Archive of obsolete content
opting into private browsing add-ons built using the sdk must opt into private browsing by setting the following key in their package.json file: "permissions": {"private-browsing": true} if an add-on has not opted in, then the high-level sdk modules will not expose private windows, or objects (such as tabs) that are associated with private windows: the windows module will not list any private browser windows, generate any events for private browser windows, or let the add-on open any private browser windows the tabs module will not list any tabs that belong to private browser windows, and the add-on won...
...for example, the "downloads" window might want to display all downloads while there are still some private windows open, then clean out all the private data when all private windows have closed.
places/history - Archive of obsolete content
usage this module exports a single function, search(), which synchronously returns a placesemitter object which then asynchronously emits data and end or error events that contain information about the state of the operation.
...multiple query objects are then or'd together.
remote/child - Archive of obsolete content
each frame then has a content property that's the top-level dom window for the frame, and addeventlistener/removeeventlistener functions that enable you to listen to dom events dispatched by the frame.
...this is a shortcut for enumerating existing frames and then listening for attach events.
test/utils - Archive of obsolete content
if the callback is defined, then the beforefn is considered asynchronous, and the callback must be invoked before the test runs.
...if the callback is defined, then the afterfn is considered asynchronous, and the callback must be invoked before the next test runs.
ui/frame - Archive of obsolete content
right now it can be used in conjunction with a toolbar: you create a frame, then supply it to the toolbar's constructor, and the content is then displayed inside the toolbar.
...if you use the uri, then the message will only be dispatched to the window whose document matches that uri.
Creating annotations - Archive of obsolete content
if the page element is eligible for annotation, then the selector highlights that element and binds a click handler to it.
...first, import the panel module: var panels = require('sdk/panel'); then add the following code to the main() function: var annotationeditor = panels.panel({ width: 220, height: 220, contenturl: data.url('editor/annotation-editor.html'), contentscriptfile: data.url('editor/annotation-editor.js'), onmessage: function(annotationtext) { if (annotationtext) { console.log(this.annotationanchor); console.log(annotationtext); } annotationed...
Creating Event Targets - Archive of obsolete content
then open "index.js" and add the following code: var {cc, ci} = require("chrome"); var { xpcomutils } = require("resource://gre/modules/xpcomutils.jsm"); var bookmarkservice = cc["@mozilla.org/browser/nav-bookmarks-service;1"] .getservice(ci.nsinavbookmarksservice); var bookmarkobserver = { onitemadded: function(aitemid, afolder, aindex) { console.log("added ", bookma...
...this consists of three functions: on(): start listening for events or a given type once(): listen for the next occurrence of a given event, and then stop removelistener(): stop listening for events of a given type the on() and once() exports delegate to the corresponding function from event/core, and use bind() to pass the exports object itself as the target argument to the underlying function.
Getting started (cfx) - Archive of obsolete content
navigate to it, type cfx init, and hit enter: mkdir my-addon cd my-addon cfx init you'll see some output like this: * lib directory created * data directory created * test directory created * doc directory created * readme.md written * package.json written * test/test-main.js written * lib/main.js written * doc/main.md written your sample add-on is now ready for testing: try "cfx test" and then "cfx run".
... then when you invoke cfx run or cfx xpi, you pass the "-o" option: cfx run -o this instructs cfx to use the local copies of the sdk modules, not the ones in firefox.
Logging - Archive of obsolete content
the following add-on logs the html content of every tab the user loads, by calling console.log() inside a content script: require("sdk/tabs").on("ready", function(tab) { tab.attach({ contentscript: "console.log(document.body.innerhtml);" }); }); console output if you are running your add-on from the command line (for example, executing jpm run or jpm test) then the console's messages appear in the command shell you used.
... if you've installed the add-on in firefox then the messages appear in firefox's browser console.
Modifying the Page Hosted by a Tab - Archive of obsolete content
then open any web page in the browser window, and click the button .
...so you can load jquery, and then your content script can use that.
Open a Web Page - Archive of obsolete content
the callback is assigned to the onready property, and will be passed the tab as an argument: var tabs = require("sdk/tabs"); tabs.open({ url: "http://www.example.com", onready: function onready(tab) { console.log(tab.title); } }); even then, you don't get direct access to any content hosted in the tab.
...this add-on loads a page, then attaches a script to the page which adds a red border to it: var tabs = require("sdk/tabs"); tabs.open({ url: "http://www.example.com", onready: runscript }); function runscript(tab) { tab.attach({ contentscript: "document.body.style.border = '5px solid red';" }); } learning more to learn more about working with tabs in the sdk, see the tabs api reference.
Bookmarks - Archive of obsolete content
for example, to create a new folder in the bookmarks menu: var menufolder = bmsvc.bookmarksmenufolder; // bookmarks menu folder var newfolderid = bmsvc.createfolder(menufolder, "folder name here", bmsvc.default_index); this code locates the bookmarks menu's folder, then creates a new folder named "folder name here" in it.
... var ios = components.classes["@mozilla.org/network/io-service;1"] .getservice(components.interfaces.nsiioservice); var uri = ios.newuri("http://google.com/", null, null); var newbkmkid = bmsvc.insertbookmark(newfolderid, uri, bmsvc.default_index, ""); this example instantiates the nsiioservice and uses it to create an nsiuri referring to the google web site, then calls nsinavbookmarksservice.insertbookmark() to create a new bookmark to google, placing it at the end of the bookmarks folder referenced by newbkmkid.
File I/O - Archive of obsolete content
then you may use file.append("myfile.txt"); to make it point to myfile.txt inside that directory.
...it overwrites the file if it is there, and if it is not there it creates a file then writes into it.
HTML to DOM - Archive of obsolete content
entns("http://www.w3.org/1999/xhtml", "body"); html.documentelement.appendchild(body); body.appendchild(components.classes["@mozilla.org/feed-unescapehtml;1"] .getservice(components.interfaces.nsiscriptableunescapehtml) .parsefragment(ahtmlstring, false, null, body)); return body; } it works by creating a content-level (this is safer than chrome-level) <div> in the current page, then parsing the html fragment and attaching that fragment to the <div>.
... <vbox hidden="false" height="0"> <iframe type="content" src="" name="donkey-browser" hidden="false" id="donkey-browser" height="0"/> </vbox> then, in your extension's "load" event handler: onload: function() { donkeybrowser = document.getelementbyid("donkey-browser"); if (donkeybrowser) { donkeybrowser.style.height = "0px"; donkeybrowser.webnavigation.allowauth = true; donkeybrowser.webnavigation.allowimages = false; donkeybrowser.webnavigation.allowjavascript = false; donkeybrowser.webnavigation.allowmetaredirects = true; d...
Miscellaneous - Archive of obsolete content
ar 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.
... then create a xpcom service that adds the certificates inside that directory to the certs database on application startup.
Extension Theming Guidelines - Archive of obsolete content
custom themes may then register a replacement for your skin package allowing them to provide their own styles for all of your content.
...if you are not then you run a risk of conflicting with content that other extensions add to the window.
Inline options - Archive of obsolete content
<setting pref="extensions.throbberrestored.showtxtontoolbar" title="show text on toolbar button" type="bool" oninputchanged="alert('new value is = ' + this.value); this.style.backgroundcolor='red';"> if labels on other toolbar buttons are visible (like by using add-on "classic theme restorer") then show label on throbber toolbar button </setting> note in order for the oninputchanged to execute, the setting must have a pref attribute, otherwise the oninputchanged will not trigger.
... some discussion on the subject at stackoverflow: how to use addeventlistener on inputchanged of inline options display notifications if you want to use the settings ui for anything more than storing preferences, then you will probably need to initialize them when they first appear.
Multiple item extension packaging - Archive of obsolete content
a multiple item package provides the ability to package multiple installable bundles which can then be downloaded and installed by a user, or provided pre-packaged with an application or by an external program.
... the extension manager will read the install.rdf install manifest to determine if this is a multiple item package and then start the installation of the individual packages it contains automatically.
Appendix: What you should know about open-source software licenses - Archive of obsolete content
of course, customers who buys the software can then redistribute it themselves, so unless you provide some added value, you’ll have a hard time building a business.
... but the team may not permit just anyone to contribute additional code whenever they want—if they did, then viruses and back-doors could wind up being distributed in the official version.
Adding windows and dialogs - Archive of obsolete content
all it does is display a text message that the user can read and then click the ok button to dismiss it.
...if the user closes and then reopens your window, all the controls are reset to their defaults, which may not be what you want.
Appendix F: Monitoring DOM changes - Archive of obsolete content
t originaldoawesomedomstuff = doawesomedomstuff; doawesomedomstuff = function _doawesomedomstuff() { let res = originaldoawesomedomstuff.apply(this, arguments); doawesomerdomstuff(res, arguments); return res; }; } now, whenever doawesomedomstuff() is called, the original function will be called, followed by your own doawesomerdomstuff() function, which can then further modify the dom as needed.
...for instance, if you need to know about attribute changes to a particular node, then you should replace its setattribute method with a function that calls the original setattribute function as originalsetattribute.apply(this, arguments) before running your necessary event code.
Local Storage - Archive of obsolete content
you first specify the file using nsifile and then use nsifile.create() to actually write it out to disk.
... and then logging is done with any of the following methods, depending on the kind of message being logged: this._logger.fatal("this is a fatal message."); this._logger.error("this is an error message."); this._logger.warn("this is a warning message."); this._logger.info("this is an info message."); this._logger.config("this is a config message."); this._logger.debug("this is a debug message."); this._log...
Session store API - Archive of obsolete content
in order to properly restore your extension's state when a tab is restored, it needs to use the session store api's settabvalue() method to save any data it will need in order to restore its state, and then call gettabvalue() to retrieve the previous setting when the tab is restored.
... there's not really a way to determine when the last tab has been restored unless you determine how many tabs need to be restored then count the sstabrestored events.
Tabbed browser - Archive of obsolete content
k, 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.
... openuilinkin( url, where, allowthirdpartyfixup, postdata, referrerurl ) where: "current" current tab (if there aren't any browser windows, then in a new window instead) "tab" new tab (if there aren't any browser windows, then in a new window instead) "tabshifted" same as "tab" but in background if default is to select new tabs, and vice versa "window" new window "save" save to disk (with no filename hint!) openuilink( url, e, ignorebutton, ignorealt, allowkeywordfixup, postdata, referrerurl ) the following code will op...
Promises - Archive of obsolete content
("login", { username: user, password: password }); if (response.messages) { try { yield publish({ username: user, messages: response.messages }); } catch (e) { self.reporterror("publication failed", e); } } }); can be converted to a pure promise-based equivalent as such: request("login", { username: user, password: password }) .then(response => { if (response.messages) return publish({ username: user, messages: response.messages }); }) .then(null, (e) => { self.reporterror("publication failed", e); }); file io file io in add-ons should be done via the os.file api, which provides a simple, but powerful, interface for reading, writing, and manipulating both text and binary files.
... */ jsonstore.prototype.save = function () { return this.saver.savechanges(); }; example usage: var addon_id = "extension@example.com"; var config_default = { "foo": "bar", }; new jsonstore("config", config_default).then(store => { console.log(store.data); store.data.baz = "quux"; store.save(); }) the following changes will remove the dependency on aom wrappers: let addon = yield new promise(accept => addonmanager.getaddonbyid(addon_id, accept)); let dir = yield new promise(accept => addon.getdatadirectory(accept)); xmlhttprequest function request(url, opt...
JXON - Archive of obsolete content
*/ /* element.prototype.appendjxon = function (oobjtree) { loadobjtree(document, this, oobjtree); return this; }; */ example imagine you want to populate the following htmlelement through json: <div id="form_container"></div> then, the following code: document.getelementbyid("form_container").appendjxon({ "form": { "script": { "@type": "text/javascript", "keyvalue": "\n function numbersonly (otocheckfield, okeyevent) {\n return okeyevent.charcode === 0 || /\\d/.test(string.fromcharcode(okeyevent.charcode));\n }\n" }, "input": [{ "@type": "hidden", "@name": "instid", "@value":...
...it turns out then that for some xml dialects jxon can be not the best choise, while it can be a really powerful tool in dealing with standard xml.
Compiling The npruntime Sample Plugin in Visual Studio - Archive of obsolete content
build create a new project in visual studio for a win32 gui library (dll) (in .net 2003: win32 template, then switch to dll in application settings in the following dialog, export symbols too?)(in visual studio 2008, it is visualc++|win32|win32 project, then check dll in the wizard).
... if a wizard gives you a checkbox to create an empty project, then check it.
Finding the file to modify - Archive of obsolete content
to access it, go to the "tools" menu, select the "web development" submenu, then select the "dom inspector" item.
... in the dom inspector window, go to the file menu, select the inspect a window submenu, then select the mozilla browser window item (named after the page currently loaded in the browser).
Making it into a dynamic overlay and packaging it up for distribution - Archive of obsolete content
then we'll modify urls in our files so they point to the right place.
....png"); } statusbarpanel#tinderbox-status[status="success"] { list-style-image: url("chrome://tinderstatus/content/tb-success.png"); } statusbarpanel#tinderbox-status[status="testfailed"] { list-style-image: url("chrome://tinderstatus/content/tb-testfailed.png"); } statusbarpanel#tinderbox-status[status="busted"] { list-style-image: url("chrome://tinderstatus/content/tb-busted.png"); } then we need to create two files in the directory, one called contents.rdf which contains information for the chrome registry about the component being installed and one called install.js that contains the code to install the component.
Creating regular expressions for a microsummary generator - Archive of obsolete content
for example, both of the following urls might point to the same page: http://www.example.com/index.html https://www.example.com/index.html to make a regular expression that matches both pages, we just need to start the expression with "https" and then add a question mark (?) after that string, for example: ^https?://www\.example\.com/index\.html the question mark makes the previous character optional, so the regular expression matches strings that include the "s" in "https" as well as ones that don't.
... conclusion if we include both of these regular expressions in a microsummary generator for ebay auction item pages, the generator will then apply to just about all ebay auction item pages (at least all the ones we've seen so far!).
Drag and Drop JavaScript Wrapper - Archive of obsolete content
in this case above, the html flavour (text/html) comes first and then the text flavour (text/unicode).
...if you want to send more then one data object, (for example multiple files) you must use an transferdataset as follows: var textobserver = { ondragstart: function (event) { var txt1 = 'hello'; var txt2 = 'there'; transferdata.data = new transferdataset(); var tmp = new transferdata(); tmp.adddataforflavour("text/unicode",txt1); transferdata.data.push(tmp); new transferdata(); tmp.adddatafor...
Exception logging in JavaScript - Archive of obsolete content
consider this call chain: here we see c++ code calling javascript, which calls back into c++, which then calls back into javascript.
...if the javascript in frame 2 either receives an exception from frame 3 or generates its own exception, and that exception remains unandled, then the exception will always be logged to the error console before control returns to the c++ in frame 1.
Block and Line Layout Cheat Sheet - Archive of obsolete content
(what is a frame's "bounding box"?) if this flag is set, then <code>moverflowarea</code> will contain the total area of the frame, including the overflow.
...if the flag hasn't been set in the block reflow state, then shouldapplytopmargin() will crawl the line list to see if a block frame precedes the specified frame.
Content states and the style system - Archive of obsolete content
if that has happened, then the style could depend on the state that changed and we have to reresolve style.
...we then try matching the node against these selectors, with the assumption that both :hover and :not(:hover) match the node.
JavaScript Client API - Archive of obsolete content
}, create: function(record) { // create a new item based on the values in record }, update: function(record) { // look up the stored record with id = record.id, then set // its values to those of new record }, remove: function(record) { // look up the stored record with id = record.id, then delete it.
...also, for me, doing weave.engines.register(fooengine) worked better then doing weave.fooengine = fooengine.
HTTP Class Overview - Archive of obsolete content
nshttphandler implements nsiprotocolhandler manages preferences owns the authentication cache holds references to frequently used services nshttpchannel implements nsihttpchannel talks to the cache initiates http transactions processes http response codes intercepts progress notifications nshttpconnection implements nsistreamlistener & nsistreamprovider talks to the socket transport service feeds data to its transaction object routes progress notifications nshttpconnectioninfo identifie...
...ng data nshttpchunkeddecoder owned by a transaction strips chunked transfer encoding nshttprequesthead owns a nshttpheaderarray knows how to fill a request buffer nshttpresponsehead owns a nshttpheaderarray knows how to parse response lines performs common header manipulations/calculations nshttpheaderarray stores http "<header>:<value>" pairs nshttpauthcache stores authentication credentials for http auth domains nshttpbasicauth implements nsihttpauthenticator generates basic auth credentials from user:pass nshttpdigestauth implements nsihttpauthenticator generates digest auth credentials from user:pass original document information author(s): darin fisher last updated date: august 5, 2002 copyright information: portions of this content are © ...
Creating a Help Content Pack - Archive of obsolete content
for example, if your glossary, index, and table of contents rdf files are all located at chrome://myapp/locale/help/*, then you could put chrome://myapp/locale/help/ here and use only the actual file names without path when needed later.
...then, to describe that entry, you set an rdf:about attribute to the value of the entry's rdf:id, prefixed by a #.
Java in Firefox Extensions - Archive of obsolete content
these 2 objects let you make use of the standard jdk classes, e.g., var ajavalist = new java.util.linkedlist(); if you want to load your own jars, then you can create your own java class loader.
...if you call java from xul, then each firefox window will have its own class loader and hence its own "singleton".
Menu - Archive of obsolete content
ArchiveMozillaJetpackUIMenu
set(items) equivalent to calling reset() and then add(items).
...they may then modify the menu.
Metro browser chrome tests - Archive of obsolete content
running the metro browser chrome tests to run mochitest, first build mozilla with your changes; then run ./mach mochitest-metro this will launch metro browser chrome tests in the default immersive browser.
...if the path points to the root tests directory, then all metro browser chrome tests will be run.
Monitoring downloads - Archive of obsolete content
we find a // record for the same source uri and start time, then update the end // time, size, and speed entries in the record.
...it starts by opening the sqlite database containing the log information, then creates a select sql statement to pull all entries from the database.
Plug-n-Hack Phase1 - Archive of obsolete content
the configuration document should then listen for a number of other events: configuresectoolstarted - this notifies the document that the browser is processing the configuration; if this event is not received within a reasonable amount of time after the configuresectool event has been fired, you might want to warn the user that pnh does not seem to be supported by this browser (perhaps prompting them to install the appropriate addo...
...so if you select the “zap scan” command then you will be prompted to select a site from the list of sites currently known to zap.
Plug-n-Hack - Archive of obsolete content
for example, to configure a browser to use an intercepting proxy that can handle https traffic, the user must typically: configure their browser to proxy via the tool configure the tool to proxy via their corporate proxy import the tool’s ssl certificate into their browser if any of these steps are carried out incorrectly then the browser will typically fail to connect to any website – debugging such problems can be frustrating and time-consuming.
...a browser that supports pnh can then allow the user to invoke such functionality without having to switch to and from the tool.
Porting NSPR to Unix Platforms - Archive of obsolete content
you can build the <tt>gencfg</tt> tool as follows: cd mozilla/nsprpub/pr/include gmake gencfg gencfg > foo.bar then you use the macro values in <tt>foo.bar</tt> as a basis for the <tt>_xxxos.cfg</tt> file.
...on some platforms, <tt>jmp_buf</tt> is a struct, then you should look for a struct member named <tt>sp</tt> or something similar.
Bundles - Archive of obsolete content
the web application is then launched without the unpacking overhead.
...the user can then decide to install the webapp.
New Skin Notes - Archive of obsolete content
oh, i went back to login page, logged in and then from there went to the /test/ pages and it's like the old look (with menu bar at the left), where indeed, the logout link is as it should be on the left in personal tools.
...--mmondor 12:25, 26 aug 2005 (pdt) hmm, note that when logged-in, the theme is all fine like the old one, it's when a user doesn't login and reads the docs through the test site that the menu bar then is at the right and is slightly too large...
Supporting per-window private browsing - Archive of obsolete content
you can then take action based on this value, as any data or actions originating from this window should be considered private.
... // might use doc.hasattribute("privatebrowsingmode") then instead) try { var inprivatebrowsing = components.classes["@mozilla.org/privatebrowsing;1"].
Supporting private browsing mode - Archive of obsolete content
ponents.classes["@mozilla.org/privatebrowsing;1"] .getservice(components.interfaces.nsiprivatebrowsingservice); var oldprivatemode = pbs.privatebrowsingmode; pbs.privatebrowsingenabled = true; /* this is all private */ pbs.privatebrowsingenabled = oldprivatemode; in this example, we save the current state of the private browsing mode setting in the oldprivatemode variable, then turn on private browsing by setting its value to true.
... simply instantiate the helper, then you can use its inprivatebrowsing flag to detect whether or not private browsing is currently enabled, as shown here: var listener = new privatebrowsinglistener(); if (listener.inprivatebrowsing) { // we are in private browsing mode!
Table Layout Regression Tests - Archive of obsolete content
as you will probably run your normal mozilla in parallel with the testing issue then: set moz_no_remote=1 at the command prompt.
... additional notes there is a special type of frame dumps - the printing regression tests, they are invoked by the -prt command line argument to the viewer and include first a display then a frame dump taking into account the printer pages.
TraceVis - Archive of obsolete content
if tracemonkey is built with tracevis, and run with tracevis enabled, then tracemonkey will output a log of all its activity transitions.
...time goes forward down each column of pixels, then to the column on the right.
Treehydra Manual - Archive of obsolete content
for example, if the current abstract value of a variable x is nonzero, and the analysis goes inside an if statement with the condition x == 1, then in the new abstract value of x will be nonzero meet 1.
...for example, if esp reaches a point where two control flow paths merge, and on one side the abstract value of x is 1, and on the other side, the abstract value of x is 2, then the new abstract value of x will be 1 join 2.
URIs and URLs - Archive of obsolete content
noteable differences necko does not support certain deprecated forms of relative urls, based on the following part of rfc 2396: if the scheme component is defined, indicating that the reference starts with a scheme name, then the reference is interpreted as an absolute uri and we are done.
...the parser can then continue with the steps below for the remainder of the reference components.
Using gdb on wimpy computers - Archive of obsolete content
if you don't allow those libraries to be loaded then gdb will not be able to properly debug threads on linux.
...the best way to do this is to set a breakpoint in main, let the program run until main and then turn off automatic library loading.
Venkman Introduction - Archive of obsolete content
you can then access the debugger via a new, dynamically created menuitem in the tools menu of that browser, or else restart the browser with a special debugger option.
...you may then copy the text from the interactive session view.
Venkman - Archive of obsolete content
bandhauer then went on to reflect that api into java, and create his cross platform front end, eventually producing netscape javascript debugger 1.0 and 1.1.
... mailing list newsgroup rss feed irc: #venkman on irc.mozilla.org report a bug in venkman if you find a problem with venkman, please follow directives mentioned at venkman faq section 5.4 and then you may report a bug on javascript debugger component.
Event Handlers - Archive of obsolete content
within an xbl inheritance chain, event handlers always fire first on the derived binding and then on the base binding in the chain.
... a derived handler then has a way of preventing the event from flowing to its base binding handlers.
moveByOffset - Archive of obsolete content
if isselecting is true, then the selection is also adjusted.
... if isselectingrange is also true, then the new item is selected in addition to any currently selected items.
OpenClose - Archive of obsolete content
if you do want to open a submenu, open the parent menu first, and then open the child menu in a popupshown event listener.
...if the open property is set to true, then the menu is open, otherwise the menu is closed.
PopupEvents - Archive of obsolete content
then that menu will be closed and the popuphidden event will be fired.
... this process will then repeat for the next highest level of menu until all the menus are closed.
Bindings - Archive of obsolete content
the ?photo variable is filled in with the known value and then the arc is looked up the datasource, filling in the value for the ?description variable.
... the ?description variable would then be used in the action body.
Multiple Rules - Archive of obsolete content
for instance, if the first rule matched all folders, then the remaining rules can assume that any results that get past the first rule are not folders.
...in this simple example with one rule though, it would likely be simpler and faster to just filter these out using the query xpath expression rather than generating the results then using a condition to filter them.
Static Content - Archive of obsolete content
you might think that the builder would then just create a menupopup, but it doesn't.
...the builder then switches where generated content would be generated to inside to existing menupopup and moves onto the next part of the action, the menuitem.
textbox (Toolkit autocomplete) - Archive of obsolete content
highlightnonmatches new in thunderbird 3 requires seamonkey 2.0 type: boolean if true, then the autocomplete field will be highlighted when no match has been found.
... readonly type: boolean if set to true, then the user cannot change the value of the element.
Textbox (XPFE autocomplete) - Archive of obsolete content
highlightnonmatches new in thunderbird 3 requires seamonkey 2.0 type: boolean if true, then the autocomplete field will be highlighted when no match has been found.
... readonly type: boolean if set to true, then the user cannot change the value of the element.
The Joy of XUL - Archive of obsolete content
these custom components can then be used in xul applications by specifying the custom tag and associated attributes.
... in practical terms, this enables developers to maintain one code stream for a given application, then apply custom branding or include special features for customers with a completely independent code base.
Creating toolbar buttons (Customize Toolbar Window) - Archive of obsolete content
watch for a snippet that you can copy and paste into scratchpad, and then run on gists@github here: _ff-addon-snippet-addtoolbarbuttontopalette.js .
... the advantage to adding the toolbar button to the palette rather than creating an element and then appendchild to the toolbar (document.getelementbyid('nav-bar')) or appendchild to the addon bar (document.getelementbyid('addon-bar')) is that once in the toolbar palette, users can configure it through the customize menu.
Adding Event Handlers to XBL-defined Elements - Archive of obsolete content
this is then assigned to the clipboard field.
... document.getanonymousnodes(this)[0].value='' the text of the textbox is then assigned a value of a null string.
Adding Properties to XBL-defined Elements - Archive of obsolete content
that way, all you need is to get a reference to the element (using document.getelementbyid or a similar function) and then get or set the additional properties and call the methods on it.
...this is convenient because then you can modify the property or the attribute and both will have the same value.
Box Objects - Archive of obsolete content
you will then have to unhide and uncollapse the label for it to appear again.
...if you then press the button labeled one again, its ordinal will increase to 3 and will move to the end.
Commands - Archive of obsolete content
if you did not use commands, you would need to figure out which field has the focus, then check to ensure that the operation is suitable for that element.
...the two are then linked using the command attribute, which has the value of the command's id.
Creating Dialogs - Archive of obsolete content
in a script used by the dialog, we can then refer to the argument using the window's arguments property.
...second, you could pass a function or object as one of the arguments when creating the dialog, then call that function or modify the object in the opened dialog.
Creating a Skin - Archive of obsolete content
we can then refer to it using the url 'chrome://findfile/skin/findfile.css'.
... try moving the css styles from findfile.css into global.css and then look at some of the dialogs in mozilla.
Creating a Wizard - Archive of obsolete content
set it to a script which performs whatever task you want and then returns true.
...if it returns false, then the wizard does not close, which might occur if the function savedoginfo() encountered invalid input, for example.
Document Object Model - Archive of obsolete content
for example, you might get the first child of an element using the firstchild property and then navigate through the children using the nextsibling property.
...we then use a for loop to iterate over the children, accessing each item using an array-like notation.
Features of a Window - Archive of obsolete content
if the name doesn't exist, then a new window is opened and the specified resource is loaded into its browsing context.">window.open() function to open the second window.
...if the name doesn't exist, then a new window is opened and the specified resource is loaded into its browsing context.">window.open() next, we'll look at how to open secondary dialogs.
Modifying a XUL Interface - Archive of obsolete content
you can then set attributes of the element using the setattribute() function and append it to the xul document using the appendchild() function.
... addbutton() then assigns the label 'a new button' to the button using the setattribute() function.
Property Files - Archive of obsolete content
you can then look up a particular property by name.
...var strbundle = document.getelementbyid("strings"); var nofilesfound=strbundle.getstring("notfoundalert"); alert(nofilesfound); this example first gets a reference to the bundle using its id then, it looks up the string 'notfoundalert' in the property file.
Skinning XUL Files by Hand - Archive of obsolete content
for example, when a button is defined as follows: <button class="plain" label="push me" /> then the following very simple style definition applies to that button.
...in general, though, it's better form toimport the global skin into your stylesheet, create your new styles rules, and then load only the new stylesheet to get all styles in both the global skin and in your own stylesheet.
Trees and Templates - Archive of obsolete content
iscontainer if this attribute is set to true, then the rule will match all resources that have children.
... isempty if this attribute is set to true, then the rule will match all resources that have no children.
Using Remote XUL - Archive of obsolete content
for apache, you can do this by adding the following line to your mime.types file: application/vnd.mozilla.xul+xml .xul alternately, add this line to your httpd.conf file or, if the apache server is configured to allow it, to the .htaccess file in the directory from which the xul file is served: addtype application/vnd.mozilla.xul+xml .xul then restart your web server.
...to add items to a menu, we need to first add a menupopup element and then put menuitem elements within it for each item we want to appear on the menu.
XML - Archive of obsolete content
then they insist that their authors use the language to describe the thing it has been created for.
...it will consist of a lexicon of four terms: memo, to, from, body -- all of which fit together into a syntax represented in most xml circles as: <!element memo (from, to, body)> for developers accustomed to reading and using xml, this definition indicates that the root element "memo" is constituted by a "from" element, then a "to" element, then a "body" element.
datepicker - Archive of obsolete content
readonly type: boolean if set to true, then the user cannot change the value of the element.
... readonly type: boolean if set to true, then the user cannot modify the value of the element.
listbox - Archive of obsolete content
if isselecting is true, then the selection is also adjusted.
... if isselectingrange is also true, then the new item is selected in addition to any currently selected items.
notificationbox - Archive of obsolete content
if "" then an icon appropriate for the priority level is used.
... if the return value from this function is not true, then the notification is closed.
preference - Archive of obsolete content
files" orient="horizontal" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> <script type="text/javascript"> function myfunction(e){ /* do something cool here or just say the below */ alert(e.target.nodename); } </script> <textbox id="find-text" onchange="return myfunction(event);"/> </window> readonly type: boolean if set to true, then the user cannot change the value of the element.
... readonly type: boolean if set to true, then the user cannot modify the value of the element.
richlistbox - Archive of obsolete content
if isselecting is true, then the selection is also adjusted.
... if isselectingrange is also true, then the new item is selected in addition to any currently selected items.
textbox - Archive of obsolete content
readonly type: boolean if set to true, then the user cannot change the value of the element.
... readonly type: boolean if set to true, then the user cannot modify the value of the element.
timepicker - Archive of obsolete content
readonly type: boolean if set to true, then the user cannot change the value of the element.
... readonly type: boolean if set to true, then the user cannot modify the value of the element.
Building XULRunner with Python - Archive of obsolete content
the built xulrunner can then be found asc:\projects\obj-xulrunner\dist\bin\xulrunner.exe.
...untill then simply deploy thedist\bin folder and the xul application.
Make your xulrunner app match the system locale - Archive of obsolete content
democracy does this by creating a command line handler called democracyclh, and then creating a new object of our pybridge component.
...then set the locale preference.
xulauncher - Archive of obsolete content
h -e # a simple bash script to create a minimal xulrunner dir structure and # needed meta files in /tmp, copy the xul-file over and start it # usage: # xulauncher xulfile.xul [options] ############################################################################## # check if theres atleast one parameter ############################################################################## if [ $# -lt 1 ] then echo "you need to give the xul file as first parameter" exit fi # check if 1st parameter is a file ############################################################################## if [ !
... -f "$1" ] then echo "\"$1\" is not a file" exit fi # define some variables ############################################################################## wd=/tmp ext=".xul" xulfile=`basename $1` xulname=${xulfile%$ext} xuldir="$wd/$xulname/chrome/$xulname/" xulprefdir="$wd/$xulname/defaults/preferences" xulappini="$wd/$xulname/application.ini" xulmanifest="$wd/$xulname/chrome/chrome.manifest" xulprefs="$wd/$xulname/defaults/preferences/prefs.js" # make minimal directory structure ############################################################################## mkdir -p $xuldir mkdir -p $xulprefdir # create application.ini file ############################################################################## echo " [app] vendor=xulauncher.sh name=$xulname version=0.0.1 buildid=`date +%y%m%d...
mozilla.dev.platform FAQ - Archive of obsolete content
then unpack the xul app into the mac structure with xulrunner -install-app q: can you build xulrunner with newer (>1.5) features, such as storage?
...took an foo.app directory created with xulrunner-bin --install-app and tried to copy (using rsync -rl) the xul.framework directory into a frameworks directory in the .app bundle and then deleting the xul.framework directory from /library/frameworks, my running my app fails silently.
reftest opportunities files - Archive of obsolete content
if you can look at the html in one of these pages, and can see a way to get the same visual ouptut, then that is an obvious reftest opportunity.
... for example, if some html is in an unexpected place and is supposed to be ignored, then we can match against an html file that is missing that extra mark-up.
Extentsions FAQ - Archive of obsolete content
why does his extension not able to read the contents of a folder and then produce a segmentation fault after his extension reads preferences in thunderbird?
... use the debugger by typing in a command like this: /break chrome://myextension/content/myfile.js 123 then i suggest using flat chrome.
NPN_PostURL - Archive of obsolete content
values: true: post the file whose path is specified in buf, then delete the file.
...for protocols in which the headers must be distinguished from the body, such as http, the buffer or file should contain the headers, followed by a blank line, then the body.
The First Install Problem - Archive of obsolete content
the solution suggests that plugin vendors ought to leave dlls on a windows desktop whether or not a netscape gecko browser is detected, and then write keys in the windows registry giving future netscape gecko browsers the path where the plugin resides and meta-information about how to load the plugin.
...if every major plugin vendor complies with the writing of plugin directory information into the registry along with a plid, we can then use the object tag to invoke plugins based on their "classid" (their respective plid, which is a uri, which works well with the w3c spec).
What is RSS - Archive of obsolete content
in fact, back then, rss did not stand for really simple syndication but stood for rich site summary.
... if you don't want any of that done, then don't put it in a non-password-protected rss feed, and, of course, don't make the password public.
Digital Signatures - Archive of obsolete content
tamper detection and related authentication techniques rely on a mathematical function called a one-way hash (also called a message digest).
...it then uses the same hashing algorithm that generated the original hash to generate a new one-way hash of the same data.
Security - Archive of obsolete content
ssl has been universally accepted on the world wide web for authenticated and encrypted communication between clients and servers.nspr release engineering guidethis paper is for engineers performing formal release for the netscape portable runtime (nspr) across all platforms.ssl and tlsthe secure sockets layer (ssl) and transport layer security (tls) protocols are universally accepted standards for authenticated and encrypted communication between clients and se...
...both client and server authentication occur over ssl/tls.
The Basics of Web Services - Archive of obsolete content
an example is, it is easier to send a multi-dimensional array with soap rather then with xml-rpc.
... soap also has more features then xml-rpc, but xml-rpc on its own, has its uses.
Using SSH to connect to CVS - Archive of obsolete content
make sure you have a ~/.ssh/config file that has at least the following directives preferredauthentications hostbased,publickey,password host cvs.mozilla.org proxycommand corkscrew <i>proxyserver.foo.com</i> <i>port</i> %h %p replaceproxyserver.foo.com with the hostname of your proxy server, andport with the numeric tcp port on which the http tunnel is running.
...your private key is then added to ssh-agent using ssh-add at which point you will be prompted for the key's passphrase.
Using the W3C DOM - Archive of obsolete content
the method returns a reference to the uniquely identified element, which can then be used to script the element.
...it then tests for support for textcontent, then innertext and uses which ever is supported.
Using workers in extensions - Archive of obsolete content
how this differs from previous versions this version of the stock ticker extension moves the xmlhttprequest call that fetches updated stock information into a worker thread, which then passes that information back to the main body of the extension's code to update the display in the status bar.
... then it sets the worker's onmessage event handler to a function which looks at the event passed into it, and does one of two things: if there is a data field on the event, the stock symbol being tracked is set to the upper case version of that value.
-ms-hyphenate-limit-lines - Archive of obsolete content
for instance, if 2, then no more than 2 successive lines may end with a hyphenated word.
... if 0 then no lines may end with a hyphenated word.
-ms-scroll-snap-points-x - Archive of obsolete content
if any value is less than -ms-scroll-limit-x-min , then -ms-scroll-limit-x-min is used.
... if any value is greater than -ms-scroll-limit-x-max, then -ms-scroll-limit-x-max is used.
-ms-scroll-snap-points-y - Archive of obsolete content
if any value is less than -ms-scroll-limit-y-min , then -ms-scroll-limit-y-min is used.
... if any value is greater than -ms-scroll-limit-y-max, then -ms-scroll-limit-y-max is used.
ArrayBuffer.transfer() - Archive of obsolete content
the static arraybuffer.transfer() method returns a new arraybuffer whose contents have been taken from the oldbuffer's data and then is either truncated or zero-extended by newbytelength.
... examples var buf1 = new arraybuffer(40); new int32array(buf1)[0] = 42; var buf2 = arraybuffer.transfer(buf1, 80); buf1.bytelength; // 0 but if you use the polyfill then the value is still 40 buf2.bytelength; // 80 new int32array(buf2)[0]; // 42 var buf3 = arraybuffer.transfer(buf2, 0); buf2.bytelength; // 0 but if you use the polyfill then the value is still 80 buf3.bytelength; // 0 polyfill you can partially work around this by inserting the following code at the beginning of your scripts, allowing use of much of the functionality of transfer() in browsers ...
LiveConnect Overview - Archive of obsolete content
in the following example, the forname method creates a wrapper object theclass, which is then passed to the newinstance method to create an array.
...more recently, the classes have been distributed with sun's java runtime; initially in the file "jaws.jar" in the "jre/lib" directory of the runtime distribution (for jre 1.3), then in "plugin.jar" in the same location (jre 1.4 and up).
Properly Using CSS and JavaScript in XHTML Documents - Archive of obsolete content
however when an xhtml page is served with mime type text/xml or application/xhtml+xml, then it should be treated as an xml document which must conform to the strict rules for authoring and displaying xml.
... if you only test your xhtml when it is deployed as text/html, then you may be introducing problems such as described in this article without realizing it.
Back to the Server: Server-Side JavaScript On The Rise - Archive of obsolete content
e remote resource var u = new url( "http://www.mozilla.org/news.rdf" ); var c = u.openconnection(); c.connect(); // read in the raw data var s = new java.io.inputstreamreader( c.getinputstream() ); var b = new java.io.bufferedreader( s ); var l, str = ""; while( ( l = b.readline() ) != null ) { // skip if( l != "" ) { str = str + l + "\n"; } } // define the namespaces, first the default, // then additional namespaces default xml namespace = "http://purl.org/rss/1.0/"; var dc = new namespace( "http://purl.org/dc/elements/1.1/" ); var rdf = new namespace( "http://www.w3.org/1999/02/22-rdf-syntax-ns#" ); // use e4x to process the feed var x = new xml( str ); for each( var i in x..item ) { print( "title: " + i.title + "\n" ); print( "about: " + i.@rdf::about + "\n" ); print( "link: " + i...
... xml processing the final feature we'll explore is xml processing with a particular emphasis first on the capability to create a simple xml service on the server-side, then use the e4x capabilities to processes it.
Developing Mozilla XForms - Archive of obsolete content
then start firefox out of the build directory: cd obj-*/dist/firefox ./firefox -no-remote -jsconsole -p yourprofilename the xforms extension that was built together with firefox should be already installed.
... then open your form that causes problems and have a look on the console.
Troubleshooting XForms Forms - Archive of obsolete content
if the instance is not in the empty namespace (xmlns=""), then all binding expressions must use a prefix bound to the namespace.
...if you are developing on your local machine using apache tomcat for example then add the following regular expression on a new line: ^http://localhost:8080/.* use the xforms buddy to view instance data the xforms buddy extension allows you to dynamically view model instance data while the xforms is running in the firefox browser.
XForms Label Element - Archive of obsolete content
ui behavior accesskey support - if the accesskey attribute is specified on labeled xforms controls or on the label element itself then the label text for the control will contain an indicator as to what the access key is in a standard way.
... focus behavior - when a label element is clicked or its accesskey is activated then the form control that contains the label will be given the focus.
Fixing Table Inheritance in Quirks Mode - Archive of obsolete content
if a css property can be inherited, then table elements and their components (tr, td, etc.) should inherit just as any other element would.
... for example, if an author writes: <style type="text/css"> body {font-size: 11px;} </style> ...then the text inside table cells should also be 11 pixels in size.
The Business Benefits of Web Standards - Archive of obsolete content
the style sheet only needs to load once and then it is cached.
...coding to standards is then the only practical solution.
Using the Right Markup to Invoke Plugins - Archive of obsolete content
if the flash activex control is not installed, ie will then go to the url referenced by the codebase attribute and retrieve the activex control.
...if the user has checkedalways use the netscape plugin finder service to get plugins then whether these attributes are specified or not makes no difference -- the browser willalways consult with the plugin finder service to determine if it has a plugin to handle the missing mime type.
GLSL Shaders - Game development
applying the shaders to actually apply the newly created shaders to the cube, comment out the basicmaterial definition first: // var basicmaterial = new three.meshbasicmaterial({color: 0x0095dd}); then, create the shadermaterial: var shadermaterial = new three.shadermaterial( { vertexshader: document.getelementbyid( 'vertexshader' ).textcontent, fragmentshader: document.getelementbyid( 'fragmentshader' ).textcontent }); this shader material takes the code from the scripts and applies it to the object the material is assigned to.
... then, in the line that defines the cube we need to replace the basicmaterial: var cube = new three.mesh(boxgeometry, basicmaterial); ...with the newly created shadermaterial: var cube = new three.mesh(boxgeometry, shadermaterial); three.js compiles and runs the shaders attached to the mesh to which this material is given.
Mobile touch controls - Game development
chhandler function looks like this: function touchhandler(e) { if(e.touches) { playerx = e.touches[0].pagex - canvas.offsetleft - playerwidth / 2; playery = e.touches[0].pagey - canvas.offsettop - playerheight / 2; output.innerhtml = "touch: "+ " x: " + playerx + ", y: " + playery; e.preventdefault(); } } if the touch occurs (touches object is not empty), then we will have all the info we need in that object.
...they are assigned dynamically, so if you put three fingers on the screen, then, pointer1pointer2, and pointer3 will be active.
Tiles and tilemaps overview - Game development
for instance, a rock that could appear on top of several terrain types (like grass, sand or brick) could be included on it's own separate tile which is then rendered on a new layer, instead of several rock tiles, each with a different background terrain.
... an alternative method would be to split the tilemap into big sections (like a full map split into 10 x 10 chunks of tiles), pre-render each one off-canvas and then treat each rendered section as a "big tile" in combination with one of the algorithms discussed above.
Create the Canvas and draw on it - Game development
then we're creating the ctx variable to store the 2d rendering context — the actual tool we can use to paint on the canvas.
...add this below your previous lines of javascript, then load your index.html in a browser to try it out.
Finishing up - Game development
if there are no lives left, the game is lost; if there are still some lives left, then the position of the ball and the paddle are reset, along with the movement of the ball.
...replace the following line: var interval = setinterval(draw, 10); with simply: draw(); and remove each instance of: clearinterval(interval); // needed for chrome to end game then, at the very bottom of the draw() function (just before the closing curly brace), add in the following line, which causes the draw() function to call itself over and over again: requestanimationframe(draw); the draw() function is now getting executed again and again within a requestanimationframe() loop, but instead of the fixed 10 milliseconds frame rate, we are giving control of the framerate...
Move the ball - Game development
technically, we will be painting the ball on the screen, clearing it and then painting it again in a slightly different position every frame to make the impression of movement — just like how movement works with the movies.
...first, instead of a hardcoded position at (50,50) we will define a starting point at the bottom center part of the canvas in variables called x and y, then use those to define the position the circle is drawn at.
Animations and tweens - Game development
the above array says that we are displaying frame 0, then 1, then 0, etc.
...update the first line inside update() as shown below: function update() { game.physics.arcade.collide(ball, paddle, ballhitpaddle); game.physics.arcade.collide(ball, bricks, ballhitbrick); paddle.x = game.input.x || game.world.width*0.5; } then we can create the ballhitpaddle() function (having ball and paddle as default parameters), playing the wobble animation when it is called.
Extra lives - Game development
if yes, then the player still has some lives left and can continue to play — they will see the life lost message, the ball and paddle positions will be reset on screen and on the next input (click or touch) the message will be hidden and the ball will start to move again.
...the difference is that the add() method binds the given function and causes it to be executed every time the event occurs, while addonce() is useful when you want to have the bound function executed only once and then unbound so it is not executed again.
Player paddle and controls - Game development
rendering the paddle from the framework point of view the paddle is very similar to the ball — we need to add a variable to represent it, load the relevant image asset, and then do the magic.
... loading the paddle first, add the paddle variable we will be using in our game, right after the ball variable: var paddle; then, in the preload function, load the paddle image by adding the following new load.image() call: function preload() { // ...
Win the game - Game development
implementing winning in our game is quite easy: if you happen to destroy all the bricks, then you win.
...if there are no more bricks left alive, then we show a winning message, restarting the game once the alert is dismissed.
Plug-in Development Overview - Gecko Plugin API Reference
this information will then appear in the navigator.mimetypes dom object.
...then the following registry values should be added to the windows registry (the plug-in-identifier should follow the specification): hklm/software/mozillaplugins/plugin-identifier descripton: reg_sz "description of the plugin" path: reg_sz "c:\..path to the plugin.dll" productname: reg_sz "the plugin name" vendor: reg_sz "the plugin author/vendor" version: reg_sz "0.5.whatever plugin version s...
API - MDN Web Docs Glossary: Definitions of Web-related terms
for example: the getusermedia api can be used to grab audio and video from a user's webcam, which can then be used in any way the developer likes, for example, recording video and audio, broadcasting it to another user in a conference call, or capturing image stills from the video.
...gps), which can then be used in conjunction with the google maps apis to for example plot the user's location on a custom map and show them what tourist attractions are in their area.
Call stack - MDN Web Docs Glossary: Definitions of Web-related terms
when a script calls a function, the interpreter adds it to the call stack and then starts carrying out the function.
... call stack list: empty in summary, then, we start with an empty call stack.
Callback function - MDN Web Docs Glossary: Definitions of Web-related terms
a callback function is a function passed into another function as an argument, which is then invoked inside the outer function to complete some kind of routine or action.
...a good example is the callback functions executed inside a .then() block chained onto the end of a promise after that promise fulfills or rejects.
Card sorting - MDN Web Docs Glossary: Definitions of Web-related terms
card sorting is a simple technique used in information architecture whereby people involved in the design of a website (or other type of product) are invited to write down the content / services / features they feel the product should contain, and then organize those features into categories or groupings.
...the name comes from the fact that often card sorting is carried out by literally writing the items to sort onto cards, and then arranging the cards into piles.
Cipher suite - MDN Web Docs Glossary: Definitions of Web-related terms
a cipher suite is a combination of a key exchange algorithm, authentication method, bulk encryption cipher, and message authentication code.
... a typical cipher suite looks like ecdhe_rsa_with_aes_128_gcm_sha256 or ecdhe-rsa-aes128-gcm-sha256, indicating: ecdhe (elliptic curve diffie-hellman ephemeral) for key exchange rsa for authentication aes-128 as the cipher, with galois/counter mode (gcm) as the block cipher mode of operation sha-256 as the hash-based message authentication code (hmac) learn more mozilla recommended cipher suite choices for tls ...
Code splitting - MDN Web Docs Glossary: Definitions of Web-related terms
code splitting is the splitting of code into various bundles or components which can then be loaded on demand or in parallel.
...then features required at page load can be downloaded immediately with additional scripts being lazy loaded after the page or application is interactive, thus improving performance.
Cross Axis - MDN Web Docs Glossary: Definitions of Web-related terms
the cross axis in flexbox runs perpendicular to the main axis, therefore if your flex-direction is either row or row-reverse then the cross axis runs down the columns.
... if your main axis is column or column-reverse then the cross axis runs along the rows.
JavaScript - MDN Web Docs Glossary: Definitions of Web-related terms
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.
...since then, the standardized javascript is called ecmascript and specified under ecma-262, whose latest (tenth, es2019) edition is available as of june 2019.
MVC - MDN Web Docs Glossary: Definitions of Web-related terms
if the state of this data changes, then the model will usually notify the view (so the display can change as needed) and sometimes the controller (if different logic is needed to control the updated view).
...these actions require the model to be updated, so the input is sent to the controller, which then manipulates the model as appropriate, which then sends updated data to the view.
MitM - MDN Web Docs Glossary: Definitions of Web-related terms
they open it, read it, eventually modify it, and then repackage the letter and only then send it to whom you intended to sent the letter for.
... the original recipient would then mail you a letter back, and the mailman would again open the letter, read it, eventually modify it, repackage it, and give it to you.
Mobile First - MDN Web Docs Glossary: Definitions of Web-related terms
the rationale behind the mobile-first approach is to provide users with good user experiences at all screen sizes—by starting with creating a user experience that works well on small screens, and then building on top of that to further enrich the user experience as the screen size increases.
... the mobile-first approach contrasts with the older approach of designing for desktop screen sizes first, and then only later adding some support for small screen sizes.
Prefetch - MDN Web Docs Glossary: Definitions of Web-related terms
<link rel="dns-prefetch" href="https://example.com/"> link prefetching link prefetching is a performance optimization technique that works by assuming which links the user is likely to click, then downloading the content of those links.
... if the user decides to click on one of the links, then the page will be rendered instantly as the content has already been downloaded.
Session Hijacking - MDN Web Docs Glossary: Definitions of Web-related terms
most authentication occurs only at the start of a tcp session.
... protection against session hijacking create a secure communication channel with ssh (secure shell) pass authentication cookies over https connection implement logout functionality so the user can end the session generate the session id after successful login pass encrypted data between the users and the web server use a string or long random number as a session key learn more general knowledge session hijacking on wikipedia ...
Signature (security) - MDN Web Docs Glossary: Definitions of Web-related terms
a signature, or digital signature, is a protocol showing that a message is authentic.
... on receiving the message, the verification process authenticates the sender - uses the sender's public key to decrypt the signature and recover the hash, which can only be created with the sender's private key, and checks message integrity - compares the hash with a newly calculated one from the received document (the two hashes will differ if the document has been tampered with) the system fails if the private key is compromised or the recipient is deceitfully given the wrong public key.
Assessment: Accessibility troubleshooting - Learn web development
note: if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page.
...can you do a test of the current color contrast (text/background), report the results of the test, and then fix it by changing the assigned colors?
CSS and JavaScript accessibility best practices - Learn web development
when the validation has been performed, if the tests pass then the form is submitted.
... if there are errors (if(errorlist.innerhtml !== '')) then we stop the form submitting (using preventdefault()), and display any error messages that have been created (see below).
Creating fancy letterheaded paper - Learn web development
note: if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page.
...older browsers will apply the first declaration and ignore the second one, whereas newer browsers will apply the first one, then override it with the second one.
Handling different text directions - Learn web development
this then dictates the direction text flows in sentences.
...if you are not using multiple writing modes then for now you might prefer to use the physical versions.
Images, media, and form elements - Learn web development
if you are following these lessons in order then you may not have looked at layout yet.
... for consistency it is a good idea to set margins and padding to 0 on all elements, then add these back in when styling particular controls button, input, select, textarea { box-sizing: border-box; padding: 0; margin: 0; } other useful settings in addition to the rules mentioned above, you should also set overflow: auto on <textarea>s to stop ie showing a scrollbar when there is no need for one: textarea { overflow: auto; } putting it all together into a "reset" as a fi...
CSS selectors - Learn web development
selector lists if you have more than one thing which uses the same css then the individual selectors can be combined into a selector list so that the rule is applied to all of the individual selectors.
...for example, ::first-line always selects the first line of text inside an element (a <p> in the below case), acting as if a <span> was wrapped around the first formatted line and then selected.
Test your skills: Multicol - Learn web development
if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page.
... then, add a 5px, grey rule between each column, ensuring there is 10px of space between the edge of the rule and the column content.
Normal Flow - Learn web development
first of all, individual element boxes are laid out by taking the elements' content, then adding any padding, border and margin around them — it's that box model thing again, which we've looked at earlier.
...if there isn't space, then the overflowing text or elements will move down to a new line.
Styling links - Learn web development
we set the path to the image we want to insert, specify no-repeat so we only get one copy inserted, and then specify the position as 100% of the way over to the right of the text content, and 0 pixels from the top.
... we also use background-size to specify the size we want the background image to be shown at — it is useful to have a larger icon and then resize it like this as needed for responsive web design purposes.
What text editors are available? - Learn web development
gedit if you use gnome desktop, kate if you use kde etc.), if not then you should try installing one or more text editors of your choosing.
... so first find out which os you're using, and then check if a given editor supports your os.
How do you host your website on Google App Engine? - Learn web development
if you've not created a project before, you'll need to select whether you want to receive email updates or not, agree to the terms of service, and then you should be able to continue.
... run the following in the command line to select your project: gcloud config set project gaesamplesite then run the following command to go to your app's directory: cd sample-app you are now ready to deploy your application, i.e.
How does the Internet work? - Learn web development
it began in the 1960s as a us-army-funded research project, then evolved into a public infrastructure in the 1980s with the support of many public universities and private companies.
... by connecting computers to routers, then routers to routers, we are able to scale infinitely.
Basic native form controls - Learn web development
then we also have the <button> element itself.
...if this attribute is not specified, the element inherits its setting from the containing element, for example, <fieldset>; if there is no containing element with the disabled attribute set, then the element is enabled.
Other form controls - Learn web development
<select id="simple" name="simple"> <option>banana</option> <option selected>cherry</option> <option>lemon</option> </select> if required, the default value for the select box can be set using the selected attribute on the desired <option> element — this option is then preselected when the page loads.
... the data list is then bound to an <input> element (e.g.
Test your skills: Form validation - Learn web development
if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page.
... remove the length validation from the phone number field if it is present, and set it so that it accepts 10 digits — either 10 digits in a row, or a pattern of three digits, three digits, then four digits, separated by either spaces, dashes, or dots.
HTML basics - Learn web development
in the example above, we opened the <p> element first, then the <strong> element; therefore, we have to close the <strong> element first, then the <p> element.
...if they overlap as shown above, then your web browser will try to make the best guess at what you were trying to say, which can lead to unexpected results.
Debugging HTML - Learn web development
<ul> <li>unclosed elements: if an element is <strong>not closed properly, then its effect can spread to areas you didn't intend <li>badly nested elements: nesting elements properly is also very important for code behaving correctly.
...then try revalidating your html to show what errors are left.
What’s in the head? Metadata in HTML - Learn web development
to do this, either copy and paste the code out of the page and into a new text file in your code editor, then save it in a sensible place.
... you should also try opening the code up in your code editor, editing the contents of these elements, then refreshing the page in your browser.
Images in HTML - Learn web development
so for example, if your image is called dinosaur.jpg, and it sits in the same directory as your html page, you could embed the image like so: <img src="dinosaur.jpg"> if the image was in an images subdirectory, which was inside the same directory as the html page (which google recommends for seo/indexing purposes), then you'd embed it like this: <img src="images/dinosaur.jpg"> and so on.
... set the image's correct width and height (hint: it is 200px wide and 171px high), then experiment with other values to see what the effect is.
Mozilla splash page - Learn web development
then save pattern.png in the same directory (right click on the image to get an option to save it.) access the different images in the originals directory and save them in the same way; you'll want to save them in a different directory for now, as you'll need to manipulate (some of) them using a graphics editor before they're ready to be used.
... note: to properly test the srcset/sizes examples, you'll need to upload your site to a server (using github pages is an easy and free solution), then from there you can test whether they are working properly using browser developer tools such as the firefox network monitor.
Video and audio content - Learn web development
in this article we'll look at doing just that with the <video> and <audio> elements; we'll then finish off by looking at how to add captions/subtitles to your videos.
... if you are unable to source any video or audio, then you can feel free to use our sample audio and video files to carry out this exercise.
HTML table advanced features and accessibility - Learn web development
rather than have a screenreader read out the contents of many cells just to find out what the table is about, he or she can rely on a caption and then decide whether or not to read the table in greater detail.
...how then can you read a table like the above?
Functions — reusable blocks of code - Learn web development
previous overview: building blocks next another essential concept in coding is functions, which allow you to store a piece of code that does a single task inside a defined block, and then call that code whenever you need it using a single short command — rather than having to type out the same code multiple times.
...try editing a() and b() so they look like this: function a() { let y = 2; output(y); } function b() { let z = 3; output(z); } save the code and reload it in your browser, then try calling the a() and b() functions from the javascript console: a(); b(); you should see the y and z values output in the page.
Function return values - Learn web development
ou execute the following: ctx.arc(random(width), random(height), random(50), 0, 2 * math.pi); if the three random() calls returned the values 500, 200, and 35, respectively, the line would actually be run as if it were this: ctx.arc(500, 200, 35, 0, 2 * math.pi); the function calls on the line are run first, and their return values substituted for the function calls, before the line itself is then executed.
...it runs whenever the change event fires on the text input — that is, when a new value is entered into the text input, and submitted (e.g., enter a value, then unfocus the input by pressing tab or return).
Test your skills: Conditionals - Learn web development
if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page.
... to finish off, you should then add another test that checks whether season contains the string "winter", and again assigns an appropriate string to response.
Test your skills: Functions - Learn web development
if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page.
... functions 1 for the first task, you have to create a simple function — choosename() — that prints a random name from the provided array (names) to the provided paragraph (para), and then run it once.
JavaScript building blocks - Learn web development
for example, in a game, if the player's number of lives is 0, then it's game over.
...functions allow you to store a piece of code that does a single task inside a defined block, and then call that code whenever you need it using a single short command — rather than having to type out the same code multiple times.
Manipulating documents - Learn web development
you can then add/remove styles as wished.
... first of all, let's grab a reference to the div, and then grab the width and height of the viewport (the inner window, where your document is displayed) and store them in variables — these two values are handily contained in the window.innerwidth and window.innerheight properties.
Silly story generator - Learn web development
note: if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page.
... if you are unsure whether the javascript is applied to your html properly, try removing everything else from the javascript file temporarily, adding in a simple bit of javascript that you know will create an obvious effect, then saving and refreshing.
Test your skills: Arrays - Learn web development
if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page.
...then add a new item to the beginning of the array.
Test your skills: Math - Learn web development
if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page.
...you will have to create four numeric values, then add the first two together, then subtract the fourth from the third, then multiply the two secondary results together to get a result of 48.
Test your skills: JSON - Learn web development
if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page.
... the values of these variables are then printed to the screen inside paragraphs.
Test your skills: Object-oriented JavaScript - Learn web development
if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page.
... test that it works by creating the square and triangle object instances as before (using new shape() for both), and then calling their calcperimeter() methods.
Introducing JavaScript objects - Learn web development
here we teach object theory and syntax in detail, then look at how to create your own objects.
... object-oriented javascript for beginners with the basics out of the way, we'll now focus on object-oriented javascript (oojs) — this article presents a basic view of object-oriented programming (oop) theory, then explores how javascript emulates object classes via constructor functions, and how to create object instances.
Properly configuring server MIME types - Learn web development
this bypassed the normal download dialog resulting in internet explorer guessing that the content was an executable program and then running it on the user's computer.
... if the media type is displayed using a plug-in in netscape gecko, install the plug-in and then look in the help->about plug-ins menu to see what mime types are associated with the media type.
Website security - Learn web development
a persistent xss vulnerability occurs when the malicious script is stored on the website and then later redisplayed unmodified for other users to execute unwittingly.
...consider two-factor authentication for your site, so that in addition to a password the user must enter another authentication code (usually one that is delivered via some physical hardware that only the user will have, such as a code in an sms sent to their phone).
Server-side website programming - Learn web development
displaying all of these using different static pages would be extremely inefficient, so instead such sites display static templates (built using html, css, and javascript), and then dynamically update the data displayed inside those templates when needed, such as when you want to view a different product on amazon.
...you should start with the first module, then go on to one of the following modules, which show how to work with two very popular server-side languages using appropriate web frameworks.
Getting started with Ember - Learn web development
previous overview: client-side javascript frameworks next in our first ember article we will look at how ember works and what it's useful for, install the ember toolchain locally, create a sample app, and then do some initial setup to get it ready for development.
... developers are then more easily able to switch between projects and applications without having to completely relearn the architecture, patterns, conventions, etc.
Introduction to client-side frameworks - Learn web development
a brief history when javascript debuted in 1996, it added occasional interactivity and excitement to a web that was, up until then, composed of static documents.
...framework authors have devoted immense time and labor to writing javascript that recreates these features, and even then, no framework has done so perfectly.
Accessibility in React - Learn web development
change the import statement at the top of todo.js so that it includes useref: import react, { useref, usestate } from "react"; then, create two new constants beneath the hooks in your todo() function.
... creating our ref import the useref() and useeffect() hooks into app.js — you'll need them both below: import react, { usestate, useref, useeffect } from "react"; then declare a new ref inside the app() function.
Componentizing our React app - Learn web development
the following commands make a components directory and then, within that, a file called todo.js.
... then, update the return statement of app() so that it renders our components.
React resources - Learn web development
for this app, we could have for example written a dedicated form.css file to house the styles of those respective components, then imported the styles into their respective modules like this: import form from './form'; import './form.css' this approach makes it easy to identify and manage the css that belongs to a specific component.
... try installing one of these, then using it to inspect the app you’ve just built!
Beginning our React todo list - Learn web development
then, copy and paste the following commands into your terminal to delete some unneeded files.
... the jsx copy the following snippet to your clipboard, then paste it into app.js so that it replaces the existing app() function: function app(props) { return ( <div classname="todoapp stack-large"> <h1>todomatic</h1> <form> <h2 classname="label-wrapper"> <label htmlfor="new-todo-input" classname="label__lg"> what needs to be done?
Starting our Svelte Todo list app - Learn web development
in this article we will first have a look at the desired functionality of our app, then we'll create a todos.svelte component and put static markup and styles in place, leaving everything ready to start developing our to-do list app features, which we'll go on to in subsequent articles.
... code along with us git clone the github repo (if you haven't already done it) with: git clone https://github.com/opensas/mdn-svelte-tutorial.git then to get to the current app state, run cd mdn-svelte-tutorial/02-starting-our-todo-app or directly download the folder's content: npx degit opensas/mdn-svelte-tutorial/02-starting-our-todo-app remember to run npm install && npm run dev to start your app in development mode.
Dynamic behavior in Svelte: working with variables and props - Learn web development
code along with us git clone the github repo (if you haven't already done it) with: git clone https://github.com/opensas/mdn-svelte-tutorial.git then to get to the current app state, run cd mdn-svelte-tutorial/03-adding-dynamic-behavior or directly download the folder's content: npx degit opensas/mdn-svelte-tutorial/03-adding-dynamic-behavior remember to run npm install && npm run dev to start your app in development mode.
... behind the scenes the svelte compiler will parse and analyze our code to make a dependency tree, then it will generate the javascript code to re-evaluate each reactive statement whenever one of their dependencies is updated.
Creating our first Vue component - Learn web development
you can check if the unique ids are working by temporarily adding more <to-do-item></to-do-item> calls into app.vue, and then checking their rendered output with your browser's devtools.
...in our next artcle we'll look at adding a set of todo item data to our app.vue component, which we'll then loop through and display inside todoitem components using the v-for directive.
Adding a new todo form: Vue events, methods, and models - Learn web development
.once: listens for the event until it's been triggered once, and then no more.
... update your v-model attribute to chain lazy and trim as shown above, and then test your app again.
Rendering a list of Vue components - Learn web development
in this artcle we'll look at adding a set of todo item data to our app.vue component, which we'll then loop through and display inside todoitem components using the v-for directive.
...then we want to pass the data from each to-do item to a todoitem component.
Git and GitHub - Learn web development
different team members will commonly want to create their own separate versions of the code (called branches in git), work on a new feature in that version, and then get it merged in a controlled manner (in github we use pull requests) with the master version when they are done with it.
...you make changes to your own copy, and then push those changes back up to the server, where an administrator will decide whether to merge your changes with the master copy.
Accessibility/LiveRegionDevGuide
the actual object that change can then be found in the event.any_data field.
...this variable can then be used to quickly determine if an event was triggered by the document being loaded.
Theme concepts
these resources are then packed in a zip for publication on addons.mozilla.org (amo) or for self-distribution.
...s the content for the day and night elements of the dynamic theme: const themes = { 'day': { images: { theme_frame: 'sun.jpg', }, colors: { frame: '#cf723f', tab_background_text: '#111', } }, 'night': { images: { theme_frame: 'moon.jpg', }, colors: { frame: '#000', tab_background_text: '#fff', } } }; the theme.theme object is then passed to theme.update() to change the header theme, as in this code snippet from the same example: function settheme(theme) { if (currenttheme === theme) { // no point in changing the theme if it has already been set.
Adding phishing protection data providers
to find an id number to use, you can build a loop that requests the value of browser.safebrowsing.provider.0.name, then browser.safebrowsing.provider.1.name, and so forth until no value is returned.
... then you can use that value.
A bird's-eye view of the Mozilla framework
organization this article first covers some conceptual groundwork, then walks through a user scenario to illustrate how key mozilla architectural components work together to support a simplehelp viewer ui action.
...release() decrements the reference count and then the object becomes a candidate for destruction.
Browser chrome tests
running the browser chrome tests to run mochitest, first build mozilla with your changes; then run ./mach mochitest -f browser this will launch your build and open a "browser chrome tests" window, and report the results in the ui and to stdout.
...if the path points to a directory, then the tests in that directory and all of its subdirectories will be run.
Testopia
if you are on windows or another case insensitive file system you should first rename the folder (testopia-old for example) and then unzip the tarball.
... you can then merge your changes before deleting the old version.
What to do and what not to do in Bugzilla
if you need faster access to get canconfirm or editbugs, especially in order to triage bugs or to participate in a bug day, then you can ask in #bmo on irc, or you may create a bug requesting permissions.
...bugs covered by this exception should not be invalidated by anyone other than the module owner or module peer; for bugs involving modules like layout or content, attach a test case to the bug and then cc one of the owners or peers.
Building SpiderMonkey with UBSan
/bin/sh if [ -z $1 ] ; then echo "usage: $0 <dirname>" elif [ -d $1 ] ; then echo "directory $1 already exists" else autoconf2.13 autoconf213 mkdir $1 cd $1 llvm_root="$home/llvm" sanflag="-fsanitize=undefined -fno-sanitize=alignment,float-cast-overflow,float-divide-by-zero,vptr -dxmalloc=myxmalloc" \ cc="$llvm_root/build/release+asserts/bin/clang" \ cxx="$llvm_root/build/release+asserts/bin/clang++" \ cflags="$sanflag" \ cxxflags="$sanflag" \ moz_llvm_hacks=1 \ ../configure --enable-debug --disable-optimize make -j 8 fi 3.
... (for automated testing outside of gdb, you can instead build with -fsanitize=undefined-trap -fsanitize-undefined-trap-on-error, but then you lose ubsan's diagnostics and the ability to continue past errors.) known bugs.
Chrome registration
platformversion when supporting more then one application, it is often more convenient for an extension to specify which gecko version it is compatible with.
... to indicate that a package is platform-specific, add the "platform" modifier to the "content" line after the path, for example: content global-platform jar:toolkit.jar!/toolkit/content/global-platform/ platform once that is specified in your manifest you then ensure that under the directory global-platform are subdirectories win (windows/os2), mac (os9/osx), or unix (everything else).
HTTP logging
copy and paste the following line into the "run" command window and then press enter: for 32-bit windows: "c:\program files (x86)\mozilla firefox\firefox.exe" -moz_log=timestamp,rotate:200,nshttp:5,cache2:5,nssockettransport:5,nshostresolver:5,cookie:5 -moz_log_file=%temp%\log.txt for 64-bit windows: "c:\program files\mozilla firefox\firefox.exe" -moz_log=timestamp,rotate:200,nshttp:5,cache2:5,nssockettransport:5,nshostresolver:5,cookie:5 -moz_log_file=%temp...
... the append module specified is then ignored.
SVG Guidelines
if saved as a raster image then the work to rasterize the gradients and filters takes place on the authors computer before the result is stored in the raster file.
...on the other hand, if the image is saved as an svg image then all this work needs to be done each time the svg is displayed on someone else's computer.
Performance
if each framescript registers a seperate listener then the observed action will trigger the callbacks in all tabs.
... clean up on addon unload bad: all the previous examples, *even the "better" ones* if your addon is restartless or uses the sdk then updates or the user turning it off and on will load to unload/reload events.
HTMLIFrameElement.getCanGoBack()
syntax instanceofhtmliframeelement.getcangoback() .then(function(result) { ...
... example function canmovebwd() { browser.getcangoback().then(function(result) { if (result) { back.disabled = false; console.log("it's possible to navigate the history backward."); } else { back.disabled = true; console.log("it's not possible to navigate the history backward."); } }); } specification not part of any specification.
HTMLIFrameElement.getCanGoForward()
syntax instanceofhtmliframeelement.getcangoforward() .then(function(result) { ...
... example function canmovefwd() { browser.getcangoforward().then(function(result) { if (result) { fwd.disabled = false; console.log("it's possible to navigate the history forward."); } else { fwd.disabled = true; console.log("it's not possible to navigate the history forward."); } }); } specification not part of any specification.
HTMLIFrameElement.getManifest()
syntax instanceofhtmliframeelement.getmanifest().then(function(json) { ...
... examples var browser = document.queryselector('iframe'); browser.addeventlistener('mozbrowserloadend',function() { var request = browser.getmanifest().then(function(json) { console.log(json); }); }); specification not part of any specification.
HTMLIFrameElement.getMuted()
syntax there are two versions of this method, a callback version: var request = instanceofhtmliframeelement.getmuted(); and a promise version: instanceofhtmliframeelement.getmuted().then(function(muted) { ...
... example callback version: var browser = document.queryselector('iframe'); var request = browser.getmuted(); request.onsuccess = function() { if(request.result) { console.log('the browser is muted.'); } else { console.log('the browser is unmuted.'); } } promise version: var browser = document.queryselector('iframe'); browser.getmuted().then(function(muted) { if(muted) { console.log('the browser is muted.'); } else { console.log('the browser is unmuted.'); } }); specification not part of any specification.
HTMLIFrameElement.getVolume()
syntax there are two versions of this method, a callback version: var request = instanceofhtmliframeelement.getvolume(); and a promise version: instanceofhtmliframeelement.getvolume().then(function(volume) { ...
... example callback version: var browser = document.queryselector('iframe'); var request = browser.getvolume(); request.onsuccess = function() { console.log('the current browser volume is ' + request.result); } promise version: var browser = document.queryselector('iframe'); browser.getvolume().then(function(volume) { console.log('the current browser volume is ' + volume); }); specification not part of any specification.
HTMLIFrameElement.purgeHistory()
syntax there is a domrequest version and a promise version: var mydomrequest = instanceofhtmliframeelement.purgehistory(); instanceofhtmliframeelement.purgehistory().then(function() { ...
... examples domrequest: var browser = document.queryselector('iframe'); var request = browser.purgehistory(); request.onsuccess = function() { console.log('history deleted!'); } request.onerror = function() { console.error(this.error.name); } promise: var browser = document.queryselector('iframe'); browser.purgehistory().then(function() { console.log('history deleted!'); }, function(error) { console.error(this.error.name); }); specification not part of any specification.
Embedding Tips
get thensiwebnavigation interface on your webbrowser and call the loaduri method with the appropriate uri and flags.
...the nsiauthprompt interface allows the networking layer to pose a user / password prompt to obtain the values needed for authentication.
Script security
unprivileged to privileged code if the caller has lower privileges than the target object, then the caller gets an opaque wrapper.
... however, the privileged target is able to copy objects and functions into the less privileged scope using the exportfunction() and cloneinto() functions, and the less privileged scope is then able to use them.
How to get a stacktrace with WinDbg
(you'll want the 32-bit version, even if you are using a 64-bit version of windows) then install it, the standard settings in the installation process are fine.
... .logopen /t c:\temp\firefox-debug.log .childdbg 1 .tlist sxn gp lm if you see firefox.exe listed in the output from .tlist more than once, then you are already running the application and need to close the running instance first before you start debugging, otherwise you won't get useful results.
How to Report a Hung Firefox
then file a bug report with the crash report id.
... then, in a terminal, kill firefox using a command such as this: # replace 31042 with the pid of firefox found above kill -n sigabrt 31042 # on osx kill -s sigabrt 31042 the firefox crash report ui should appear.
Internationalized Domain Names (IDN) Support in Mozilla Browsers
this ip address is then used to connect to the web server in question.
... how mozilla browsers handle non-ascii domain names unicode and nameprep when mozilla receives idn input from the user via the location bar or a request to process non-ascii host name links, it first turns them into unicode, then normalizes the input string to make it conform to general uri requirement.
JavaScript-DOM Prototypes in Mozilla
because of this, the following holds true (assuming img1 and img2 are two different image objects in the same document): img1.__proto__ === img2.__proto__ if img1 would come from one document and img2 from another document, then the above would not be true.
...obj.__proto__.__proto__) has been set up already, if it has, then there's nothing left to do in nsdomclassinfo::postcreate().
OS.File.Info
using os.file.info example: determining if a file is a regular file the following snippet uses the main thread api to determine (asynchronously) whether some path is a regular file, or a directory, or a symbolic link: let promise = os.file.stat(somepath); promise.then( function onsuccess(info) { // |info| is an instance of |os.file.info| if (info.isdir) { // |somepath| represents a directory } else if (info.issymlink) { // |somepath| represents a symbolic link } else { // |somepath| represents a regular file } }, function onfailure(reason) { if (reason instanceof os.file.error && reason.becausenosuchfile) { // ...
...|somepath| does not represent anything } else { // some other error } } ) example: determining the owner of a file let promise = os.file.stat() promise.then( function onsuccess(info) { if ("unixowner" in info) { // info.unixowner holds the owner of the file } else { // information is not available on this platform } } ); evolution of this example bug 802534 will introduce the ability to check whether field unixowner appears in os.file.info.prototype, which will make it possible to write faster code.
Deferred
note: calling this method with a pending promise as the avalue argument, and then calling it again with another value before the promise is resolved or rejected, will have no effect the second time, as the associated promise is already resolved to the pending promise value as its resolution.
...if this value is a promise, then the associated promise will be resolved to the passed promise, and follow the state as the provided promise (including any future transitions).
Sqlite.jsm
examples open, execute, close in this example, we open a connection, execute a simple statement, then close the connection.
...if (callback) { callback(null, accounts); } note: the then parameters can be anonymous functions (i.e.
Using JavaScript code modules
anifest using a line like this: resource aliasname uri/to/files/ for example, if the xpi for your foo extension includes a top-level modules/directory containing the bar.js module (that is, the modules/directory is a sibling to chrome.manifest and install.rdf), you could create an alias to that directory via the instruction: resource foo modules/ (don't forget the trailing slash!) you could then import the module into your javascript code via the statement: components.utils.import("resource://foo/bar.js"); programmatically adding aliases custom aliases to paths that can be represented as an nsilocalfile can be programmatically added as well.
... you can then use that to import commonjs modules.
XPCOMUtils.jsm
a "lazy getter" provides an additional optimization: the value is calculated the first time the getter is called, and is then cached (or memoized), so subsequent accesses return the cached value without recalculating it.
...the returned object should be assigned to the classinfo property of a js object, the queryinterface() function generated by generateqi will return it automatically then.
L10n testing with xcode
a window will then appear showing the diff between the imported xliff file and the existing resources in the project folder.
... in the edit scheme screen, select run from the left pane and then navigate to the options tab.
Localizing with Koala
re-running the comparison a common scheme of working with the compare-locales tools (included in koala) is to incrementally translate and commit the files and then re-run comparison to see what is left to be translated.
...for the purposes of this tutorial, we will switch to the command line every now and then to see what koala does behind the scenes.
Localizing with Mozilla Translator
getting started with mozillatranslator mt uses products as groups of localization files with a common root directory (for instance, you may have a product for thunderbird, other for seamonkey, other for dom, other for toolkit, etc.) you update your repository copy using your favorite repository tool, and then update the product(s) in mt.
... if you are a ''not so good'' mt user, however, you can just create a new product (or several ones; see next recipe to know why), run file -> update on them (you'll get a list of all the strings) and then run edit -> autotranslate.
Release phase
add the following lines to your ~/.ssh/config file, replacing user@host.domain with your mozilla ldap account name: host hg.mozilla.org user user@host.domain if you have already cloned the remote repository using the http protocol using this command: $ hg clone http://hg.mozilla.org/releases/l10n-central/x-testing then you will need to edit the .hg/hgrc file (inside the x-testing local clone) to tell mercurial to push using ssh.
... mercurial will connect to the remote repository, authenticate through ssh and send the changesets.
Translation phase
then you may not be interested in using any of the tools listed above for your localizations.
... if that is the case, then this section is for you!
Localization sign-off reviews
once they are fixed, push your fix to your repo, attach it to the corresponding bug using the same mercurial revision number as before, and then request another review.
... the process is then repeated until the bug is fixed to satisfaction.
Localization technical reviews
once they are fixed, push your fix to your repo, attach it to the corresponding bug using the same mercurial revision number as before, and then request another review.
... the process is then repeated until the bug is fixed to satisfaction.
Uplifting a localization from Central to Aurora
if so, you want to fix those issues on aurora alone, verify them there, and then go back to this page.
...push them to hg.mozilla.org there, verify the builds, and then try to merge l10n-central and aurora again.
Localization formats
you may choose to present just the html for localization: we give an html file which lists several pieces of content like, <h1>getting started</h1> and the localizer translates to <h1>débuter avec firefox</h1> the localizer then submits the translated html or php back to us by either checking in changes to svn or sending us a patch that pascal checks in.
...then, an en-us repository was created holding the translations to all the entity-like values of msgid.
Fonts for Mozilla's MathML engine
open the zip archive, move inside the latinmodern-math-1959 directory and then inside the otf directory.
... extract the zip archive, move inside the latinmodern-math-1959 directory and then inside the otf directory.
DMD
$ killall -34 firefox each one of these steps triggers all the memory reporters and then dmd analyzes the reports, printing commentary like this: dmd[5222] opened /tmp/dmd-1414556492-5222.json.gz for writing dmd[5222] dump 1 { dmd[5222] constructing the heap block list...
... for example, if you have moz_dmd_shutdown_log=~/dmdlogs/ moz_dmd_log_process=tab then dmd logs for content processes will be saved to ~/dmdlogs/.
GC and CC logs
to get cycle collector logs on try server, set moz_cc_log_directory to moz_upload_dir, then set the other variables appropriately to generate cc logs.
...to find the cc logs once the try run has finished, click on the particular job, then click on "job details" in the bottom pane in treeherder, and you should see download links.
Power profiling overview
if all cores are idle then the entire package can also become idle, which reduces power consumption even further.
... if the problem manifests on a particular website, try saving a local copy of the site and then manually removing html elements to see if a particular page feature is causing the problem many power problems are caused by either high cpu usage or high wakeup frequency.
Profiling with Xperf
for 64-bit windows 7 or vista, you'll need to do a registry tweak and then restart to enable stack walking: reg add "hklm\system\currentcontrolset\control\session manager\memory management" -v disablepagingexecutive -d 0x1 -t reg_dword -f symbol server setup with the latest versions of the windows performance toolkit, you can modify the symbol path directly from within the program via the trace menu.
... you'll have to agree to a eula for the microsoft symbols -- if you're not prompted for this, then something isn't configured right in your symbol path.
Reporting a Performance Problem
make sure to choose an appropriate setting for the recording (if you're not sure, choose firefox platform), and then choosing "start recording".
...if you choose custom settings (and then clicking edit settings) for the profiler, you can adjust the size of the buffer (presently defaults to 90 mb) and the time interval between data collection (presently defaults to 1 ms).
about:memory
(the filename will have a .json.gz suffix.) you can then attach or upload the file appropriately.
...if you find any particular tree overwhelming, it can be helpful to collapse all the sub-trees immediately below the root, and then gradually expand the sub-trees of interest.
dtrace
run that command for a few seconds and then hit ctrl + c to interrupt it.
... dtrace will then print to the output file a number of stack traces, along with a wakeup count for each one.
powermetrics
-n 1 tells it to take one sample and then stop.
....68 0.00 com.apple.webkit.plugin.64 67373 55.55 74.38 0.74 0.00 9.51 3.13 0.02 com.apple.terminal 109 6.22 0.40 0.23 0.00 terminal 208 6.25 92.99 0.00 0.00 0.33 0.20 0.00 the rapl output is first, then the powermetrics output.
A guide to searching crash reports
select "new line", and then choose a field ("is garbage collecting") and an operator ("is true").
... grouping by platform for example, if we start with a default search for all firefox crashes in the past week, but then replace the "signature" facet with "platform" and "moz crash reason", we get search results with two facet tabs.
Emscripten
compile the c/c++ runtimes of other languages into javascript, and then run code in those other languages in an indirect way (this has been done for python and lua)!
...read more about emscripten and try some demos, then get started with using it.
NSPR Contributor Guide
should you need to have a similar api, with some slightly different behavior or different function prototype, then suggest a new api with a different name.
...if several platforms cannot be made to implement your api, then it is not a good candidate for inclusion in nspr.
Dynamic Library Linking
you can then call pr_findsymbol on lib to look up other symbols defined in the main program.
...for example, link your executable program a.out without the +s option, then execute the following: chatr +s enable a.out on rhapsody, the environment variable is dyld_library_path.
Introduction to NSPR
it might be viewed as taking the executing thread and adding it to the end of the ready queue for its appropriate priority, then simply running the scheduling algorithm to find the most appropriate thread.
...if the logic of a program allows for timing of waits on conditions, then the clock must be treated as part of the monitored data and the amount of time elapsed re-asserted when the call returns.
PR_CEnterMonitor
description pr_centermonitor uses the value specified in the address parameter to find a monitor in the monitor cache, then enters the lock associated with the monitor.
...if a match is found, then either the calling thread is already in the monitor (and this is a reentrant call) or another thread is holding the monitor's mutex.
PR_CreateThread
description if you want the thread to start up waiting for the creator to do something, enter a lock before creating the thread and then have the thread's root function enter and exit the same lock.
...you can then use pr_jointhread to synchronize the termination of another thread.
PR_NormalizeTime
for example, if you have a ] object that represents the date 3 march 1998 and you want to say "forty days from 3 march 1998", you can simply add 40 to the tm_mday field and then call pr_normalizetime().
...you can set tm_mday to 3, tm_month to 2, and tm_year to 1998, and all the other fields to 0, then call pr_normalizetime() with pr_gmtparameters.
NSS CERTVerify Log
to create a log: #include "secport.h" #include "certt.h" certverifylog *log; arena = port_newarena(512); log = port_arenaznew(arena,log); log->arena = arena; you can then pass this log into your favorite cert verify function.
...when you are through, you will need to walk the list and free all the cert entries, then free the arena.
Cryptography functions
function name/documentation source code nss versions pk11_algtagtomechanism mxr 3.2 and later pk11_authenticate mxr 3.2 and later pk11_blockdata mxr 3.2 and later pk11_changepw mxr 3.2 and later pk11_checkuserpassword mxr 3.2 and later pk11_cipherop mxr 3.2 and later pk11_clonecontext mxr 3.2 and later pk11_configurepkcs11 mxr ...
..._needuserinit mxr 3.2 and later pk11_paramfromiv mxr 3.2 and later pk11_paramfromalgid mxr 3.2 and later pk11_paramtoalgid mxr 3.2 and later pk11_pbekeygen mxr 3.2 and later pk11_privdecryptpkcs1 mxr 3.9.3 and later pk11_protectedauthenticationpath mxr 3.4 and later pk11_pubdecryptraw mxr 3.2 and later pk11_pubderive mxr 3.2 and later pk11_pubderivewithkdf mxr 3.9 and later pk11_pubencryptpkcs1 mxr 3.9.3 and later pk11_pubencryptraw mxr 3.2 and later pk11_pubunwra...
NSS FAQ
MozillaProjectsNSSFAQ
the pkcs #11 interface included in nss means that your application can use hardware accelerators on the server and smart cards for two-factor authentication.
...nss includes detailed documentation of the ssl api and sample code that demonstrates basic ssl functionality (setting up an encrypted session, server authentication, and client authentication) to help jump start the integration process.
NSS Memory allocation
when the arena free list is in use, the first user of an arena will allocate it from the heap, but will then free it to the free list.
...consequently, when the arena free list is in use, the allocation call stacks shown will typically not be the stack of the code that most recently allocated that arena, but rather will be the stack of the code that first allocated that arena from the heap, and then placed it on the free list.
NSS_3.11.10_release_notes.html
bug 387892: add entrust root ca certificate(s) to nss bug 396999: pk11_authenticate bug 397478: lock from ssl_initsymwrapkeyslock not freed on selfserv shutdown.
... bug 398680: assertion botch in ssl3_registerserverhelloextensionsender doing second handshake with ssl_forcehandshake bug 403240: threads hanging in nss_initlock bug 403888: memory leak in trustdomain.c bug 416067: certutil -l -h token doesn't report token authentication failure bug 417637: tstclnt crashes if -p option is not specified bug 421634: don't send an sni client hello extension bearing an ipv6 address bug 422918: add verisign class 3 public primary ca - g5 to nss bug 424152: add thawte primary root ca to nss bug 424169: add geotrust primary certification authority root to nss bug 425469: add multiple new roots: geotrust bug 426568: add comodo certification authority certificate to nss bug 43138...
NSS 3.14.1 release notes
bug 357025 - nss 3.14 added support for tokens that make use of cka_always_authenticate.
... however, when authenticating with such tokens, it was possible for an internal lock to be acquired twice, causing a hang.
NSS 3.14.3 release notes
new pkcs #11 mechanisms ckm_nss_hmac_constant_time - constant-time hmac operation for use when verifying a padded, mac-then-encrypted block of data.
... ckm_nss_ssl3_mac_constant_time - constant-time mac operation for use when verifying a padded, mac-then-encrypted block of data using the sslv3 mac.
NSS 3.15.4 release notes
bug 919877 - (cve-2013-1740) when false start is enabled, libssl will sometimes return unencrypted, unauthenticated data from pr_recv new in nss 3.15.4 new functionality implemented ocsp querying using the http get method, which is the new default, and will fall back to the http post method.
... support sha-1 signatures with tls 1.2 client authentication.
NSS 3.35 release notes
if a master password was set on the dbm database, then the initial migration may be partial, and migration of keys from dbm to sql will be delayed, until this master password is provided to nss.
... the application is then able to examine application-chosen content from the session tickets, or helloretryrequest cookie, and decide whether to proceed with the connection.
NSS 3.43 release notes
new in nss 3.43 new functionality new functions in sechash.h hash_gethashoidtagbyhashtype - convert type hash_hashtype to type secoidtag in sslexp.h ssl_sendcertificaterequest - allow server to request post-handshake client authentication.
...note that while the mechanism is present, post-handshake authentication is currently not tls 1.3 compliant due to bug 1532312 notable changes in nss 3.43 the following ca certificates were added: cn = emsign root ca - g1 sha-256 fingerprint: 40f6af0346a99aa1cd1d555a4e9cce62c7f9634603ee406615833dc8c8d00367 cn = emsign ecc root ca - g3 sha-256 fingerprint: 86a1ecba089c4a8d3bbe2734c612ba341d813e043cf9e8a862cd5c57a36bbe6b cn = emsign root ca - c1 sha-256 fingerprint: 125609aa301da0a249b97a8239cb6a34216f44dcac9f3954b14292f2e8c8608f cn = emsign ecc root ca - c3 sha-256 fingerprint: bc4d809b15189d78db3e1d8cf4f9726a795da1643ca5f1358e1ddb0edc0d7eb3 ...
Overview of NSS
the secure sockets layer (ssl) protocol allows mutual authentication between a client and server and the establishment of an authenticated and encrypted connection.
...itu standard that governs the format of certificates used for authentication in public-key cryptography.
NSS PKCS11 Functions
for example, if you would normally specify tokens=<0x4=[configdir='./mybackup' tokendescription='backup']> to softoken if you at init time, then you could specify "configdir='./mybackup' tokendescription='backup'" as your module spec here to open the database ./mybackup on the fly.
...minpwlen then minimum password length for this token.
Build instructions
you can install the new assembler as root as follows: yum install binutils220 you can then use the new assembler by adding /usr/libexec/binutils220 to the beginning of your build path.
... hg clone https://hg.mozilla.org/projects/nspr hg clone https://hg.mozilla.org/projects/nss if you want to build a releases other than the tips of these repositories, then switch to the release tags: cd nspr hg update nspr_4_9_5_rtm cd ../nss hg update nss_3_14_2_rtm cd ..
FC_SetOperationState
syntax ck_rv fc_setoperationstate( ck_session_handle hsession, ck_byte_ptr poperationstate, ck_ulong uloperationstatelen, ck_object_handle hencryptionkey, ck_object_handle hauthenticationkey ); parameters hsession [in] handle of the open session.
...hauthenticationkey [in] handle of the authentication key to be used in the stored session or zero if none is needed.
NSS functions
function name/documentation source code nss versions pk11_algtagtomechanism mxr 3.2 and later pk11_authenticate mxr 3.2 and later pk11_blockdata mxr 3.2 and later pk11_changepw mxr 3.2 and later pk11_checkuserpassword mxr 3.2 and later pk11_cipherop mxr 3.2 and later pk11_clonecontext mxr 3.2 and later pk11_configurepkcs11 mxr ...
..._needuserinit mxr 3.2 and later pk11_paramfromiv mxr 3.2 and later pk11_paramfromalgid mxr 3.2 and later pk11_paramtoalgid mxr 3.2 and later pk11_pbekeygen mxr 3.2 and later pk11_privdecryptpkcs1 mxr 3.9.3 and later pk11_protectedauthenticationpath mxr 3.4 and later pk11_pubdecryptraw mxr 3.2 and later pk11_pubderive mxr 3.2 and later pk11_pubderivewithkdf mxr 3.9 and later pk11_pubencryptpkcs1 mxr 3.9.3 and later pk11_pubencryptraw mxr 3.2 and later pk11_pubunwra...
NSS tools : modutil
if the prefix sql: is not used, then the tool assumes that the given databases are in the old format.
... if the current platform cannot be found in the list of supported platforms, then the forwardcompatible list is checked for any platforms that have the same os and architecture in an earlier version.
TLS Cipher Suite Discovery
they must agree on these items: key establishment algorithm (such as rsa, dh, or ecdh) peer authentication algorithm (such as rsa, dsa, ecdsa) bulk data encryption algorithm (such as rc4, des, aes) and key size digest algorithm for message authentication checking (sha1, sha256) there are numerous available choices for each of those categories, and the number of possible combinations of all those choices is large.
...the sslciphersuiteinfo structure contains this information, declared in "sslt.h": typedef struct sslciphersuiteinfostr { pruint16 length; pruint16 ciphersuite; /* cipher suite name */ const char * ciphersuitename; /* server authentication info */ const char * authalgorithmname; sslauthtype authalgorithm; /* key exchange algorithm info */ const char * keatypename; sslkeatype keatype; /* symmetric encryption info */ const char * symciphername; sslcipheralgorithm symcipher; pruint16 symkeybits; pruint16 sym...
NSS tools : modutil
MozillaProjectsNSStoolsmodutil
if the prefix sql: is not used, then the tool assumes that the given databases are in the old format.
... if the current platform cannot be found in the list of supported platforms, then the forwardcompatible list is checked for any platforms that have the same os and architecture in an earlier version.
Necko Architecture
however, you can certainly ask the nsiioservice for the protocol handler for the uri you have, then ask the protocol handler for a channel on that uri.
...it does this by looking up the protocol handler for the scheme of the url, then asking the protocol handler to create the url.
Rhino Examples
the control class control.java is a program that executes a simple script and then manipulates the result.
...multithreaded script execution dynamicscopes.java is a program that creates a single global scope object and then shares it across multiple threads.
Small Footprint
class generation library if you do not include optimizer or javaadapter, nor do you use policysecuritycontroller then you do not need rhino library for class file generation and you can remove all the classes from in org.mozilla.classfile package.
...to build such minimalist jar without debug information, run the following command from the top directory of rhino distribution: ant clean ant -ddebug=off -dno-regexp=true -dno-e4x=true smalljar if you omit -dno-regexp=true, then the resulting smalljs.jar will include regular expression support.
SpiderMonkey Build Documentation
refer the release notes under command line tools -> new features the release notes also states that this compatibility package will no longer be provided in the near future, so the build system on macos will have to be adapted to look for headers in the sdk until then, the following should help, open /library/developer/commandlinetools/packages/macos_sdk_headers_for_macos_10.14.pk this builds an executable named js in the directory build-release/dist/bin.
...then you can use those macros in gdb commands: $ cxxflags=-g3 $src/configure ...
Bytecodes
the javascript frontend constructs an ast from the source text, then emits stack-based bytecodes from that ast as a part of the jsscript data structure.
...for example, in (a + b) + c you would push a, then push b, then add, then push c, then add, which requires a maximum depth of two expression slots.
Functions
if the function does not assign to any closed-on vars/args, and it only reads closed-on local variables and arguments that never change value after the function is created, then the function can be implemented as a flat closure.
...outside all functions, if a name definitely refers to a global for which we have seen a var, const, or function declaration, then we emit a js_defvar instruction in the script prelude and access the global using jsop_{get,set,call}gvar.
JSAPI Cookbook
/* jsapi */ assert(y.isobject()); js::rootedobject yobj(cx, &y.toobject()); if (!js_setproperty(cx, yobj, "myprop", &x)) return false; checking for a property // javascript if ("myprop" in y) { // then do something } see "getting a property", above, concerning the case where y is not an object.
... /* jsapi */ bool found; assert(y.isobject()); js::rootedobject yobj(cx, &y.toobject()); if (!js_hasproperty(cx, yobj, "myprop", &found)) return false; if (found) { // then do something } defining a constant property this is the first of three examples involving the built-in function object.defineproperty(), which gives javascript code fine-grained control over the behavior of individual properties of any object.
JS::Add*Root
if js::add*root succeeds, then as long as this variable points to a javascript value or pointer to gc-thing, that value/gc-thing is protected from garbage collection.
... if the variable points to an object, then any memory reachable from its properties is automatically protected from garbage collection, too.
JS::CompileOptions
for example, js::compileoffthread needs to save compilation options where a worker thread can find them, and then return immediately.
...thus, instances of this type can't be owned, directly or indirectly, by a javascript object: if any value that this roots ever comes to refer to the object that owns this, then the whole cycle, and anything else it entrains, will never be freed.
JSExtendedClass.wrappedObject
description if a class has the jsclass_is_extended bit set in its jsclass.flags and has a non-null jsextendedclass.wrappedobject, then objects of that class may be wrappers.
...if it returns null or obj, then the js engine treats the object as though it were not a wrapper.
JSGetObjectOps
further extension to preserve api compatibility: if this function returns a pointer to jsxmlobjectops.base, not to jsobjectops, then the engine calls extended hooks needed for e4x.
...it returns a pointer to a jsobjectops which is then used as a virtual table for operations on the new object.
JS_Add*Root
if js_add*root succeeds, then as long as this variable points to a javascript value or pointer to gc-thing, that value/gc-thing is protected from garbage collection.
... if the variable points to an object, then any memory reachable from its properties is automatically protected from garbage collection, too.
JS_CheckAccess
otherwise, if obj's class has a non-null jsclass.checkaccess callback, then it is called to perform the check.
... otherwise, if a runtime-wide check-object-access callback has been installed by calling js_setcheckobjectaccesscallback, then that is called to perform the check.
JS_DeleteProperty2
then one of the following cases applies: if obj has no property with the given name or id, or if obj inherits the specified property from its prototype, then *succeeded is set to true and obj's jsclass.delproperty hook is called (which may change *succeeded).
... if obj has the specified property but it is permanent, then *succeeded receives false.
JS_ExecuteScript
instead: the scope chain is initialized to contain obj, followed by its parent, then its parent's parent, etc.
...if the jsoption_varobjfix option is in effect (recommended), then the last object in the scope chain is used as the variable object.
JS_ExecuteScriptVersion
instead: the scope chain is initialized to contain obj, followed by its parent, then its parent's parent, etc.
...if the jsoption_varobjfix option is in effect (recommended), then the last object in the scope chain is used as the variable object.
JS_GetParent
if there is no enclosing function, with statement, or block scope, then the function's parent is the global object.
...if the jsapi function creating the object has a parent parameter, and the application passes a non-null value to it, then that object becomes the new object's parent.
JS_GetPropertyAttributes
if obj does not have the specified property, or if it inherits it from some other object (on its prototype chain, for example), then *foundp is set to js_false.
... if the property exists and belongs to obj, then *foundp is set to js_true, *attrsp is set to the logical or of zero or more property attributes flags, and the function returns js_true.
JS_GetScopeChain
when you only used this function to retrieve the scope chain's global, then you can use the function js_getglobalforscopechain.
...if the currently executing function was created in the scope of a different global object, then that object will be the last object in the current scope chain.
JS_NewArrayObject
if vector is non-null, then for each index i from 0 to length - 1, js_newarrayobject defines an enumerable array element with the value vector[i] on the new array.
...the new array has the specified length, but it doesn't have any elements.) it is often better to call js_newarrayobject(cx, 0, null), store the returned object in a gc root, and then populate its elements with js_setelement or js_defineelement.
JS_NewObject
if the new object's class (here, clasp) is a built-in class, then its associated prototype is used as the new object's prototype.
... if the global object's class's flags include jsclass_global_flags, then the global object always retains the original constructors for each standard class; we use these original constructors when they are available.
JS_ReportErrorNumber
otherwise, if the jserrorformatstring returned by the jserrorcallback has .exntype == jsexn_none, then the error reporter, if any, is called, and no error object is created.
...the source code seems to say we ignore the .exntype, actually, but surely i'm just missing something.) otherwise, if any javascript code is running in cx (for example, if the caller is a jsnative that was called from a script), then an error object is created and becomes the pending exception.
JS_SetBranchCallback
if the callback raises an exception using js_setpendingexception() and returns js_false, then the javascript engine propagates the exception to the script that was executing at the time.
... if the callback returns js_false without raising an exception, then the javascript engine immediately stops running the script with an uncatchable error.
JS_ValueToECMAInt32
all three functions first convert v to a floating-point number as if by calling js_valuetonumber; nan values are then converted to zero.
... if that succeeds, the result is then converted to the target integer type.
JSAPI reference
s_evaluatescript obsolete since jsapi 36 js_evaluateucscript obsolete since jsapi 36 js_evaluatescriptforprincipals obsolete since jsapi 30 js_evaluateucscriptforprincipals obsolete since jsapi 30 js_evaluatescriptforprincipalsversion obsolete since jsapi 30 js_evaluateucscriptforprincipalsversion obsolete since jsapi 30 you can instead compile javascript code into a jsscript which you can then execute multiple times.
... if a variable is a root, then anything it points to will not be freed by the garbage collector.
Parser API
if the qualified identifier has a computed name (i.e., the id::[expr] form), then computed is true and the right property is an expression.
... if the loc option is enabled (see the reflect.parse() options above), then each callback is provided with the source location information of the parsed node as an extra parameter.
WebReplayRoadmap
the bug only needs to be reproduced in a recording tab once, and then console logs can be added which apply throughout the entire recording.
... if the debugger could perform this analysis then it could show this information to developers and help them understand the app even when they are not actively debugging a particular recording.
Zest usecase: Reporting Security Vulnerabilities to Developers
while it will still be necessary to describe vulnerabilities, zest allows security teams to create reproducible test cases which they can then share with the developers.
...the problem they hand the script over to the developer the developer adjusts the script to match their local environment they run the script and see the vulnerability they fix the vulnerability they rerun the script to check that the vulnerability is fixed the fix is applied to the system that the security team is testing the security team rerun the script as an initial check they then perform any manual testing they think is necessary note that the developers could also include the script in the regression tests to make sure that it doesnt reoccur.
Secure Development Guidelines
hadow", o_rdwr); setreuid(getuid(), getuid()); excve("/bin/sh", argv, envp); } suid root applications file i/o: file descriptors and handles potential overflows when using select fd_set struct, static length, holds a bitmask of fds manipulated with fd_set, fd_isset, fd_clr and fd_zero macros fd_set’s size depends on the operating system if the os allows opening more fds, then fd_set can hold could overflow fd_set file i/o: file descriptors and handles good solution: dynamically allocate fd_set structs int main(void) { int i, fd; fd_set fdset; for( i = 0; i < 2000; i++) { fd = open("/dev/null", o_rdwr); } fd_set(fd, &fdset); } file i/o: race conditions operating on files can often lead to race conditions since the file system...
...api failure for example: close() can fail and leak file descriptor setuid() can fail and privileges don’t get dropped snprintf() can fail and result in return value -1 tmp = realloc(tmp, size) — realloc could fail and leak tmp writing secure code: exception handling double freeing pointers double frees can occur in exception handling they free data in try block and then free it again in the catch block this is a common issue double freeing pointers char *ptr1 = null, *ptr2 = null; try { ptr1 = new char[1024]; do_something(); delete ptr1; do_something_else(); ptr2 = new char[-1] // oom } catch (...) { delete ptr1; delete ptr2; } new will throw an exception — ptr1 is already freed in the try block then freed again in ...
Animated PNG graphics
MozillaTechAPNG
if the denominator is 0, it is to be treated as if it were 100 (that is, delay_num then specifies 1/100ths of a second).
...the compressed datastream is then the concatenation of the contents of the data fields of all the 'fdat' chunks within a frame.
XForms Accessibility
build it yourself if you would like to build firefox/seamonkey yourself then please ensure your .mozconfig file has the following option: ac_add_options --enable-extensions=default,xforms,schema-validation how to test there are two approaches to test xforms accessibility.
... therefore since mozilla xforms works in xhtml (1.x) or xul documents only then we use tabindex instead.
History Service Design
if a page can be added we first check if it exists already, then it is added or updated accordingly to the previous check, and common attributes are set based on concurrent visit properties.
... an implementer working on a ui can then associate a viewer with the result, so that it will be notified when the result tree changes.
Manipulating bookmarks using Places
for example, to create a new folder in the bookmarks menu: var menufolder = bmsvc.bookmarksmenufolder; // bookmarks menu folder var newfolderid = bmsvc.createfolder(menufolder, "folder name here", bmsvc.default_index); this code locates the bookmarks menu's folder, then creates a new folder named "folder name here" in it.
... var ios = components.classes["@mozilla.org/network/io-service;1"] .getservice(components.interfaces.nsiioservice); var uri = ios.newuri("http://google.com/", null, null); var newbkmkid = bmsvc.insertbookmark(newfolderid, uri, bmsvc.default_index, ""); this example instantiates the nsiioservice and uses it to create an nsiuri referring to the google web site, then calls nsinavbookmarksservice.insertbookmark() to create a new bookmark to google, placing it at the end of the bookmarks folder referenced by newbkmkid.
Fun With XBL and XPConnect
implementing a widget interface the next thing i needed to do was to implement an interface on the widget which i could then pass into the auto complete session.
... ({ onautocompleteresult: function(aitem, aoriginalstring, amatch) { if ( aitem ) { anonymouscontent[0].value = amatch; } } }) ]]> </property> as long as the js for the value of autocompletelistener evaluates to an object (and wrapping the expression with a set of parens like i did, does this), then the value of autocompletelistener is an object that implements my interface.
XPCOM glue
MozillaTechXPCOMGlue
then, the code must call xpcomgluestartup, which will dynamically link against the xpcom runtime.
... only then can the embedding application initialize and use xpcom.
Preface
if you already have a mozilla build or the source from mozilla 1.2 or later, then you can use the xpcom framework available there.
... if you don't already have the mozilla source, then an even easier way to get and use xpcom is to download the gecko sdk, which is a collection of libraries and tools that features the xpcom component framework.
Using XPCOM Utilities to Make Things Easier
using these declaration macros not only saves a tremendous amount of time when you're writing the code, it can also save time if you make changes to your idl file, since the c++ header file will then automatically include the updated list of methods to be supported.
...this raw pointer can then be assigned to a variable and have its reference updated by ns_if_addref.
Receiving startup notifications
this gets enough of xpcom and the application loaded and running that the extension manager can then be loaded and handle installing, uninstalling, and updating any installed extensions.
... once that process is completed, extensions can then be loaded by simply reading their manifests, loading their components, and continuing with application startup, all without having to restart the browser.
How to build a binary XPCOM component using Visual Studio
then make the following tweaks: add "..\gecko-sdk\include" to additional include directories add "..\gecko-sdk\lib" to additional library directories add "nspr4.lib xpcom.lib xpcomglue_s.lib" to additional dependencies add "xp_win;xp_win32″ to preprocessor definitions turn off precompiled headers (just to keep it simple) use a custom build step for the xpcom idl file (spawns xpidl-build.bat t...
...ok then, on with the basic, oversimplified example.
Components.Constructor
the component is then returned immediately, with only the base interface nsisupports available on it; you must call nsisupports.queryinterface() on it to call methods on the object.
...rgument: var binaryinputstream = components.constructor("@mozilla.org/binaryinputstream;1", "nsibinaryinputstream"); var bis = new binaryinputstream(); print(bis.tostring()); // "[xpconnect wrapped nsibinaryinputstream]" // someinputstream is an existing nsiinputstream bis.setinputstream(someinputstream); // succeeds if three arguments are given, then in addition to being nsisupports.queryinterface()'d, the instance will also have had an initialization method called on it.
Components.utils.Sandbox
you can then use it with evalinsandbox() to make it the global scope object for the specified script.
... wantexporthelpers a boolean: if true, then createobjectin(), evalinwindow(), and exportfunction() are available in the sandbox.
Components.utils.exportFunction
allowcrossoriginarguments: do not check that arguments to the exported function are subsumed by the caller: this allows the caller to pass objects with a different origin into the exported function, which can then use its privileged status to make cross-origin requests with them.
... example export to global scope this add-on script defines a function, then exports it to a content window: // addon-script.js var salutation = "hello "; function greetme(user) { return salutation + user; } components.utils.exportfunction(greetme, contentwindow, {defineas: "foo"}); instead of using defineas, the script can assign the result of exportfunction to an object in the target scope: // addon-script.js var salutation = "hello "; function greetme(user) ...
Profiling XPCShell
but then, you can't use the venkman ui.
...then, the next lines shows the amount of time spend in the functions in that file.
Append
if equal to pr_uint32_max, then adata is assumed to be null-terminated.
... remarks if insufficient memory is available to perform the assignment, then the string's internal buffer will point to a static empty (zero-length) buffer.
Assign
if equal to pr_uint32_max, then adata is assumed to be null-terminated.
... remarks if insufficient memory is available to perform the assignment, then the string's internal buffer will point to a static empty (zero-length) buffer.
Insert
if equal to pr_uint32_max, then adata is assumed to be null-terminated.
... remarks if insufficient memory is available to perform the assignment, then the string's internal buffer will point to a static empty (zero-length) buffer.
Replace
if equal to pr_uint32_max, then adata is assumed to be null-terminated.
... remarks if insufficient memory is available to perform the assignment, then the string's internal buffer will point to a static empty (zero-length) buffer.
Append
if equal to pr_uint32_max, then adata is assumed to be null-terminated.
... remarks if insufficient memory is available to perform the assignment, then the string's internal buffer will point to a static empty (zero-length) buffer.
Assign
if equal to pr_uint32_max, then adata is assumed to be null-terminated.
... remarks if insufficient memory is available to perform the assignment, then the string's internal buffer will point to a static empty (zero-length) buffer.
Insert
if equal to pr_uint32_max, then adata is assumed to be null-terminated.
... remarks if insufficient memory is available to perform the assignment, then the string's internal buffer will point to a static empty (zero-length) buffer.
Replace
if equal to pr_uint32_max, then adata is assumed to be null-terminated.
... remarks if insufficient memory is available to perform the assignment, then the string's internal buffer will point to a static empty (zero-length) buffer.
IAccessibleHypertext
if the index is invalid then a null pointer is returned.
...if iaccessibletext is used to represent the text containing the link, then the character index is only valid if it is greater than or equal to zero and lower than the number of characters in the text.
inIDOMUtils
if you have requested anonymous content, then if the element has an xbl binding then this will be the binding's anonymous nodes, otherwise if the element is itself an anonymous node containing an insertion point then this will be a list combining the element's explicit children from its binding parent's anonymous nodes and any children inserted as a result of the insertion point.
...if you have requested anonymous content and the element's parent has an xbl binding then the element containing the insertion point is returned instead.
mozIStorageStatement
step() identical to calling executestep(), and then calling reset() when no more rows are returned.
...this is accomplished by calling executestep(), and then calling reset().
mozIThirdPartyUtil
this is done as follows: if achannel is an nsihttpchannel and has the 'forceallowthirdpartycookie' property set, then: if auri is null, return false.
...then: if the parent is the same as the bottommost window, and the channel has the load_document_uri flag set, return false.
GetChildAt
if child index is less than zero then returns last child.
... if child index is greater than children count then returns null.
nsIAccessibleSelectable
if the specified object is already selected, then it does nothing.
...if the specified object was not selected, then it does nothing.
nsIAnnotationObserver
if aname is empty, then all annotations for the given item have been deleted.
...if aname is empty, then all annotations for the given uri have been deleted.
nsIAppStartup
eattemptquit 0x02 try to close all windows, then quit if successful.
... eforcequit 0x03 force all windows to close, then quit.
nsIAuthPromptCallback
method overview void onauthavailable(in nsisupports acontext, in nsiauthinformation aauthinfo); void onauthcancelled(in nsisupports acontext, in boolean usercancel); methods onauthavailable() authentication information is available.
... aauthinfo authentication information.
nsIAuthPromptProvider
prompt_proxy 1 proxy authentication request.
...void getauthprompt( in pruint32 apromptreason, in nsiidref iid, [iid_is(iid),retval] out nsqiresult result ); parameters apromptreason the reason for the authentication prompt, one of the prompt_* constants.
nsICachingChannel
if this attribute is set to true, then the document will not be loaded from the cache.
...if this flag has been set, and the request can be satisfied via the cache, then the ondataavailable events will be skipped.
nsICategoryManager
note: if the category does not exist, then this method does nothing.
... note: if the category does not exist, then this method does nothing.
nsICompositionStringSynthesizer
to create an instance for this: var domwindowutils = window.windowutils; var compositionstringsynthesizer = domwindowutils.createcompositionstringsynthesizer(); for example, when you create a composition whose composing string is "foo-bar-buzz" and "bar" is selected to convert, then, first, you need to start composition: domwindowutils.sendcompositionevent("compositionstart", "", ""); next, dispatch composition string with crause information and caret information (optional): // set new composition string with .setstring().
....attr_convertedtext); compositionstringsynthesizer.setcaret("foo-bar".length, 0); compositionstringsynthesizer.dispatchevent(); finally, when you commits composition with the last composition string "foo-bar-buzz": // deprecated in 36, first, dispatch commit string without clause information compositionstringsynthesizer.setstring("foo-bar-buzz"); compositionstringsynthesizer.dispatchevent(); // then, dispatch compositionend with the commit string domwindowutils.sendcompositionevent("compositionend", "foo-bar-buzz", ""); starting gecko 36, you can do it simpler: domwindowutils.sendcompositionevent("compositioncommitasis", "", ""); if you need to commit composition with different commit string gecko 36 or later, you can use "compositioncommit": domwindowutils.sendcompositionevent("compo...
nsIContentViewManager
once you have the view manager, you can call getcontentviewsin() to get a list of the content views for a given portion of the browser display, then use those nsicontentview objects to manipulate the content views.
... note: the rectangle is specified using an anchor point, then four distances to indicate how far in each direction to expand the rectangle.
nsIContentViewer
if this is null, then destroy() will be called on the document by close().
... note: if this container is the root of a view manager hierarchy (that is, this method returns null), and mparentwidget is also null, then this document should not even be displayed.
nsICryptoHMAC
acstring finish( in prbool aascii ); parameters aascii if true then the returned value is a base-64 encoded string.
... if false, then the returned value is binary data.
nsIDOMClientRect
see also cssom view module : the clientrect interfacewd this object was renamed a few times: initial name was textrectangle, then clientrect, then domrect.
... initially it had just the top/left/right/bottom attributes, then width/height/x/y were added.
nsIDOMMozNetworkStatsManager
if network stats are not available for some dates, then rxbytes and txbytes are undefined for those dates.
...if an alarmid is provided, then only that alarm is removed.
nsIDOMWindowInternal
if the name doesn't exist, then a new window is opened and the specified resource is loaded into its browsing context.">open(in domstring url, in domstring name, in domstring options) nsidomwindow nsisupports aextraargument) void close() void updatecommands(in domstring action) boolean find([optional] in domstring str,[optional] in boolean casesensitive, [optional] in boolean backwards, [opt...
... crypto nsidomcrypto readonly: returns the browser crypto object, which can then be used to manipulate various browser security features.
nsIINIParserWriter
ini files contain zero or more sections, denoted by a name in square brackets, followed by zero or more lines of text with a property name on the left, then an equals sign ("="), then the value of the property.
... to create an nsiiniparserwriter object, you use the nsiiniparserfactory interface to create a parser, then nsisupports.queryinterface() that to get an nsiiniparserwriter, like this: let writer = components.classes["@mozilla.org/xpcom/ini-processor-factory;1"].
nsIJumpListBuilder
1.0 66 introduced gecko 2.0 inherits from: nsisupports last changed in gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) jump lists are built and then applied.
...callers should begin the creation of a new jump list using initlistbuild(), add sub lists using addlisttobuild(), then commit the jump list using commitlistbuild().
nsILoginInfo
this field is null for logins attained from protocol authentications and "" means to match against any form action.
...when an http server sends a 401 result, the www-authenticate header includes a realm to identify the "protection space." see rfc 2617.
nsIMacDockSupport
if permanent private browsing mode is enabled then the "new private window" menu item is hidden.
...notice the activateapplication(true), if this is not done then firefox will not be activated.
nsIMsgDBView
aaugment if true then add to current selection.
... if false then replace current selection.
nsIMsgHeaderParser
if any of the addresses doesn't have a mailbox, then the user name is used instead.
... if any of the addresses doesn't have a name, then the mailbox is used instead.
nsIMutableArray
conversely, if insertelementat() is never used, and null elements are never explicitly added to the array, then it is guaranteed that nsiarray.queryelementat() will never return a null value.
...to remove a specific element, use nsiarray.indexof() to find the index first, then call removeelementat.
nsINavHistoryQueryOptions
the query is exeucted, the results are sorted, and then the top maxresults results are taken and returned.
...instead, we get the result ordered by date, pick the maxresult most recent ones, and then sort by title.
nsIPipe
for example, if you try to read from an empty pipe that has not yet been closed, then if that pipe's input end is non-blocking, then the read call will fail immediately with ns_base_stream_would_block as the error condition.
... however, if that pipe's input end is blocking, then the read call will not return until the pipe has data or until the pipe is closed.
nsIPluginHost
void newpluginnativewindow( out nspluginnativewindowptr apluginnativewindow ); parameters apluginnativewindow native code only!parsepostbuffertofixheaders this method parses post buffer to find out case insensitive "content-length" string and cr or lf some where after that, then it assumes there is http headers in the input buffer and continue to search for end of headers (crlfcrlf or lflf).
...then using nsihandlerservice it gets the handler info.
nsIProgressEventSink
acontext if arequest is a channel, then this parameter is the listener context passed to nsichannel.asyncopen().
... acontext if arequest is a channel, then this parameter is the listener context passed to nsichannel.asyncopen().
nsIScriptableIO
the file does not have to exist already; this method simply creates the file reference which may then be passed to the newinputstream() or newoutputstream() method to open the file for reading or writing.
...if you need to select a file in a subdirectory, you should get a reference to the directory, then use the file's append() method to navigate through the directory hierarchy to the file you really want.
nsISocketTransportService
notifywhencanattachsocket if the number of sockets reaches the limit, then consumers can be notified when the number of sockets becomes less than the limit.
...then it is time to create the transport.
nsISound
event_prompt_dialog_open 3 a prompt dialog (one that allows the user to enter data, such as an authentication dialog) is opened.
... _moz_promptdialog the system sound when a prompt dialog (one that allows the user to enter data, such as an authentication dialog) is opened.
nsIStandardURL
adefaultport if the port parsed from the url string matches this port, then the port will be removed from the canonical form of the url.
...if null, then provide abaseuri implements this interface, the origin charset of abaseuri will be assumed, otherwise defaulting to utf-8 (that is, no charset transformation from aspec).
nsITextInputProcessor
tip.appendclausetopendingcomposition("foo-".length, tip.attr_converted_clause); tip.appendclausetopendingcomposition("bar".length, tip.attr_selected_clause); tip.appendclausetopendingcomposition("-buzz".length, tip.attr_converted_clause); // then, sets the caret if you need tip.setcaretinpendingcomposition("foo-bar".length); // finally, flush the pending composition on the focused editor if (!tip.flushpendingcomposition()) { return; // composition is not started } if there is no composition, flushpendingcomposition() starts composition with dispatching compositionstart event automatically.
...for example, ctrl+c should be "c", ctrl+shift+cshould be "c", altgr+c may be "©" and then, ctrl+altgr+c should be "©".
nsITransferable
kfilemime application/x-moz-file an arbitrary file (is this an nsifile?) kurlmime text/x-moz-url a mozilla url object; this is a text string containing the url, a newline (\n), then the title of the page.
... to get the appropriate load context in javascript callers, one needs to get to the document that the transferable corresponds to, and then get the load context from the document like this: var loadcontext = doc.defaultview.queryinterface(ci.nsiinterfacerequestor) .getinterface(ci.nsiwebnavigation) .queryinterface(ci.nsiloadcontext); in c++ callers, if you have the corresponding document, you can just call nsidocument.getloadcontext() to get to the load context object.
nsITreeView
if a column consists only of an image, then the empty string is returned.
...to add properties for a particular row, you must use the nsiatomservice to create an nsiatom string, which can then be appended to the array to alter the style (see also styling a tree) getrowproperties: function(index, properties) { var atomservice = components.classes["@mozilla.org/atom-service;1"].getservice(components.interfaces.nsiatomservice); var atom = atomservice.getatom("dummy"); properties.appendelement(atom); } hasnextsibling() used to determine if the row at rowindex has a nextsibling th...
nsIURI
if this value is something other than utf-8 then the uri components (for example spec, prepath, username, and so on) are all fully url-escaped.
... this is useful for authentication, managing sessions, or for checking the origin of an uri to prevent cross-site scripting attacks while using methods such as window.postmessage().
nsIVersionComparator
for additional backwards compatibility, if "string-b" is "+" then "number-a" is incremented by 1 and "string-b" becomes "pre".
... return value if a and b are two version being compared, and the return value is smaller than 0, then a < b equals 0 then version, then a==b is bigger than 0, then a > b example function compareversions(a,b) { var x = services.vc.compare(a,b); if(x == 0) return a + "==" + b; else if(x > 0) return a + ">" + b; return a + "<" + b; } dump(compareversions("1.0pre", "1.0")); example - compare current browser version this example here uses nsixulappinfo component to get the version of the...
nsIWebContentHandlerRegistrar
if it does not find anything with host name of mail.live.com then it aborts.
... permission denied to add http://mail.live.com/secure/start?action=compose&to=%s as a content or protocol handler'permission denied to add http://mail.live.com/secure/start?action=compose&to=%s as a content or protocol handler' when calling method: [nsiwebcontenthandlerregistrar::registerprotocolhandler] if the host names do match then a confirmation like this will be seen: this domain check can be bypassed by setting the preference of gecko.handlerservice.allowregisterfromdifferenthost to true as in this code here: var {classes: cc, interfaces: ci, utils: cu} = components; cu.import("resource://gre/modules/services.jsm"); var nsiwchr = cc["@mozilla.org/embeddor.implemented/web-content-handler-registrar;1"] ...
nsIWindowWatcher
if the name doesn't exist, then a new window is opened and the specified resource is loaded into its browsing context.">window.open.
...if the name doesn't exist, then a new window is opened and the specified resource is loaded into its browsing context.">window.open for details.
nsIWindowsRegKey
if the key is already closed, then this method does nothing.
...if recurse is true, then this key and any of its descendant keys are watched.
nsIXMLHttpRequest
and then think twice about it.
...ad and make a nsiarraybufferinputstream out of it or something xhr.send(null); } xhr('https://www.gravatar.com/avatar/eb9895ade1bd6627e054429d1e18b576?s=24&d=identicon&r=pg&f=1', data => { services.prompt.alert(null, 'xhr success', data); var file = os.path.join(os.constants.path.desktopdir, "test.png"); var promised = os.file.writeatomic(file, new uint8array(data)); promised.then( function() { alert('succesfully saved image to desktop') }, function(ex) { alert('failed in saving image to desktop') } ); }); ...
nsIXULTemplateBuilder
the template builder then generates output for each result based on the <rule> elements.
...if a different query would then match instead, it will become the active match.
nsIXULWindow
if arelative is null then relative to the screen of the opener window if it was initialized by passing it to nswebshellwindow::initialize.
...you can then load a document into the window's primary content shell.
NS_CStringContainerInit2
if adata is null, then this parameter is ignored.
...if this value is zero, then the array referenced by adata (if any) will be copied.
NS_CStringGetMutableData
adata [out] upon return, if the function was successful, then *adata references the string's internal buffer.
...if astring is a reference to a nscstringcontainer, then its data will be null-terminated by this function.
nsIAbCard/Thunderbird3
ismaillist boolean if ismaillist is true then maillisturi will contain the uri of the associated mail list.
... maillisturi string if ismaillist is true then maillisturi will contain the uri of the associated mail list.
Performance
for example sqlite> explain query plan select * from moz_historyvisit v join moz_history h on v.page_id = h.id where v.visit_date > 1000000000; 0|0|table moz_historyvisit as v with index moz_historyvisit_dateindex 1|1|table moz_history as h using primary key this tells us that it will first look up in moz_historyvisit using an index, and will then look up in moz_history using the primary key.
...some features (virtual tables, full text indexes) are not compatible with shared cache - then you need to use services.storage.openunshareddatabase(file), which doesn't share the cache.
Storage
you can then execute the statement asynchronously, and the statement will get each set of bindings bound to it before execution asynchronously.
...this is equivalent to calling mozistoragestatement.executestep() and then mozistoragestatement.reset().
Troubleshooting XPCOM components registration
double check your guids in your install.rdf with your sourcecode, and then check them again.
...it may then be necessary for the stub to locate the newer runtime libraries for the other files it loads.
Getting Started Guide
if you're already familiar with nscomptrs, then you might want to skip ahead to the reference manual or the faq.
...the caller can then hold onto the reference indefinitely, calling release when it no longer needs it.
Reference Manual
the nscomptr releases its old value, if any, and then assigns in the new value, addrefing it and/or calling queryinterface as you direct by "annotating" the assignment with directives like dont_addref.
...the nscomptr releases its old value, if any, and then assigns in the new value, addrefing, and/or calling queryinterface as you specified with the directives described above.
Weak reference
if, for instance, this owning reference is part of a cycle of owning references (e.g., if the referenced object also holds a owning reference back to you), then none of the objects in the cycle can be reclaimed without taking special measures.
... what is actually needed in this case, is either out-of-band signaling, where when the observer wants to go away, it unregisters itself from the observable, which then releases its owning reference, allowing the observer to die, or else a new kind of reference.
Xptcall Porting Guide
the platform specific code then builds a call frame and invokes the method indicated by the index methodindex on the xpcom interface that.
...objects of this class can then be built to impersonate any xpcom object.
Xptcall Porting Status
if some knows how to do that then those last 2 files won't be needed.
...if you would like to contribute then let me know.
Filelink Providers
that url is then loaded into an iframe directly beneath the provider menulist.
... for example, the hightail implementation provides the following function: function extraargs() { var usernamevalue = document.getelementbyid("username").value; return { "username": {type: "char", value: usernamevalue}, }; } in this example, the username value is read from the input, and then the specially-crafted object is returned.
Index
we could just hide it on send, and then show it on the next compose.
...filter execution is done by evaluating the search terms using the core mailnews/base/search code, and then applying the filter hits when the search terms match.
MailNews Filters
filter execution is done by evaluating the search terms using the core mailnews/base/search code, and then applying the filter hits when the search terms match.
...the protocol specific code will then apply all of the actions of the filter to the current msg header.
The libmime module
}; then, in the corresponding .c file, the following structure is used: class definition first we pull in the appropriate include file (which includes all necessary include files for the parent classes) and then we define the class object using the mimedefclass macro: #include "foobar.h" #define mime_superclass parentlclass mimedefclass(foobar, foobarclass, foobarclass, &mime_superclass)...
... if you use the mime_superclass idiom, then a textual change is required in only one place if this class's superclass changes.
Building a Thunderbird extension 6: Adding JavaScript
the event listener then calls our startup function which gets our <statusbarpanel>-element with the id my-panel from the document's dom tree.
... it then uses javascript's date class to get the current date, which it converts into a string that has the format of yyyy.mm.dd.
Demo Addon
then we store the folder name in a string to display it later on the screen and mark it with an * if it is the inbox.
...we then go into each subfolder and start over.
Using popup notifications
in addition, notifications can be dismissed and recalled by clicking anywhere outside the notification, then clicking on the notification icon to bring it back again.
... then you can create the popup notification at the appropriate time like this: popupnotifications.show(gbrowser.selectedbrowser, "sample-popup", "this is a sample popup notification.", null, /* anchor id */ { label: "do something", accesskey: "d", callback: function() { alert("doing something awesome!"); } }, null ...
Using tab-modal prompts
from then on, you can use the nsiprompt object, prompt, as usual.
...then apply it, like in the example below, here we apply the prompt with a checkbox: var window = gbrowser.contentwindow; var promptfact = components.classes['@mozilla.org/prompter;1'].getservice(components.interfaces.nsipromptfactory); var prompt = promptfact.getprompt(window, components.interfaces.nsiprompt); var promptbag = prompt.queryinterface(components.interfaces.nsiwritablepropertybag2); promp...
Using the Mozilla source server
if you click "yes", windbg will display *busy* in the status bar while it downloads the source, and then it will automatically open the file and highlight the current line.
...symbols will load and then, if you're using a cvs build, when you try to step into or step over a confirmation window will appear asking if you trust the cvs command that source server is trying to run.
Working with windows in chrome code
window.opendialog( "chrome://test/content/progress.xul", "myprogress", "chrome,centerscreen", {status: "reading remote data", maxprogress: 50, progress: 10}, oncancel ); the progress dialog can then run the callback like this: <button label="cancel" oncommand="window.arguments[1](); close();" /> example 3: using nsiwindowmediator when opener is not enough the window.opener property is very easy to use, but it's only useful when you're sure that your window was opened from one of a few well-known places.
...the opened window can then just get at the underlying javascript object using wrappedjsobject.
Using COM from js-ctypes
speech synthesis example let's start with following c++ code, which invokes microsoft speech api and says "hello, firefox!" with system default voice, then wait until the speaking done.
...if this code were used in a production add-on, then to avoid firefox locking up, run this code from a chromeworker.
Using Objective-C from js-ctypes
we can then convert it straight to js-ctypes code.
...if this code were to be used in a production add-on, then to avoid firefox locking up, run this code from a chromeworker.
Declaring and Calling Functions
example: no input parameters in this example, we declare the libc clock() function, which returns the elapsed time since system startup, then fetch and output that value.
... returned values if the return type can fit into a javascript number without loss (that is, it's a number 32 bits or smaller, or is a double or float), then the function just return a javascript number.
Using js-ctypes
instead, you'll need to create a shim library that uses c functions that then call into the c++ library for you.
... after that, we simply set up our parameters by using makestr() to generate the two str255 strings we need, then call stdalert(), which produces the following alert window: the last thing we do is call carbon.close() to close the library when we're done using it.
Flash Activation: Browser Comparison - Plugins
that function can then issue the call into the plugin, knowing that everything is set up and ready to go.
... first, set your up your html with a callback that calls the javascript function plugincreated(), like this: <object type="application/x-my-plugin" data="somedata.mytype" id="myplugin"> <param name="callback" value="plugincreated()"> </object> the plugincreated() function is then responsible for the setup of your script and any calls back into the plugin that you need to make: function plugincreated() { document.getelementbyid('myplugin').callpluginmethod(); } ...
Plug-in Development Overview - Plugins
this information will then appear in the navigator.mimetypes dom object.
...then the following registry values should be added to the windows registry (the plug-in-identifier should follow the specification): hklm/software/mozillaplugins/plugin-identifier descripton: reg_sz "description of the plugin" path: reg_sz "c:\..path to the plugin.dll" productname: reg_sz "the plugin name" vendor: reg_sz "the plugin author/vendor" version: reg_sz "0.5.whatever plugin version s...
Accessibility Inspector - Firefox Developer Tools
the accessibility tab element picker looks slightly different from the page inspector html pane picker, as shown below: when you "perform a pick", you see the accessibility object highlighted in the accessibility tree, and the picker is then deactivated.
... note, however, that if you hold the shift key down when "performing a pick", you can "preview" the accessibility object in the tree (and its properties in the right-hand pane), but then continue picking as many times as you like (the picker does not get cancelled) until you release the shift key.
DOM Inspector FAQ - Firefox Developer Tools
instead, get the xul document to load as you normally would (e.g., by invoking commands or opening windows via standard application use), then locate it in the inspect chrome document menu.
...scroll the node into view, choose the select-by-click toolbar button, and then click on the element you wish to inspect.
DOM Inspector internals - Firefox Developer Tools
initially, we will begin by focusing on inspector.xul and its entry point, and then expand our focus later to explain how these other inspectors differ.
...another convenient consequence of this is that if you use a properly set up development profile, then for the most part, the effects of development changes can be seen by simply switching away from the current viewer and back.
Browser Console - Firefox Developer Tools
here's an example add-on that just logs an error when the user clicks a widget: widget = require("sdk/widget").widget({ id: "an-error-happened", label: "error!", width: 40, content: "error!", onclick: logerror }); function logerror() { console.error("something went wrong!"); } if you build this as an xpi file, then open the browser console, then open the xpi file in firefox and install it, you'll see a widget labeled "error!" in the add-on bar: click the icon.
...e, use shift+enter): var newtabbrowser = gbrowser.getbrowserfortab(gbrowser.selectedtab); newtabbrowser.addeventlistener("load", function() { newtabbrowser.contentdocument.body.innerhtml = "<h1>this page has been eaten</h1>"; }, true); newtabbrowser.contentdocument.location.href = "https://mozilla.org/"; it adds a listener to the currently selected tab's load event that will eat the new page, then loads a new page.
Use watchpoints - Firefox Developer Tools
set a watchpoint run and then pause the debugger.
... choose break on, and then one of property set property get property get or set a watchpoint icon appears to the right of the property in the scopes pane.
Using the Debugger map scopes feature - Firefox Developer Tools
open the example page and then open the debugger using tools > web developer > debugger (or press ctrl + i and then select the debugger).
... select the "bundle.js" file in the sources panel on the left and then set a breakpoint at line 102 in the increment function.
Debugger.Environment - Firefox Developer Tools
this allows the code using each debugger instance to place whatever properties it likes on its own debugger.object instances, without worrying about interfering with other debuggers.) if a debugger.environment instance’s referent is not a debuggee environment, then attempting to access its properties (other than inspectable) or call any its methods throws an instance of error.
... callee if this environment represents the variable environment (the top-level environment within the function, which receives var definitions) for a call to a functionf, then this property’s value is a debugger.object instance referring tof.
Aggregate view - Firefox Developer Tools
you'll then see a list of all the functions that allocated objects, ordered by the size of the allocations they made: the structure of this view is very much like the structure of the call tree, only it shows allocations rather than processor samples.
...the disclosure arrow then walks you back up the call tree towards the top level.
Basic operations - Firefox Developer Tools
to create a diff, click the button that looks like a venn diagram next to the camera icon (before firefox 47, this looked like a "+/-" icon): you'll be prompted to select the snapshot to use as a baseline, then the snapshot to compare.
... the tool then shows you the differences between the two snapshots: when you're looking at a comparison, you can't use the dominators view or the tree map view.
Dominators view - Firefox Developer Tools
then take a snapshot, then select "call stack" in the "label by" drop-down.
...if one were removed, then the documentprototype would still not be garbage-collected, because it's still retained by the other two path.
Migrating from Firebug - Firefox Developer Tools
then a dialog pops up allowing you to edit the data of the cookie and save it.
...then an inline editor allows you to edit the value.
Network request list - Firefox Developer Tools
if the resource was fetched from a service worker cache, then this cell displays "service worker".
...you can focus it by clicking in the filter box, or by pressing ctrl + f (or cmd + f on a mac); then start typing.
Network Monitor - Firefox Developer Tools
click the wrench icon (), which is in the main toolbar or under the hamburger menu (), then select "network".
...this means you can start debugging a page in, for example, the web console, then switch to the network monitor to see network activity without having to reload the page.
Frame rate - Firefox Developer Tools
for example, if moving the mouse over some page element triggers some javascript that changes the element's appearance, and that triggers a reflow and a repaint, then all this work needs to be completed in that frame.
... if it takes too long for the browser to process the frame, then the browser will appear momentarily unresponsive (janky).
Animating CSS properties - Firefox Developer Tools
one last step is not shown in this sequence: the page may be split into layers, which are painted independently and then combined in a process called "composition".
...in each animation frame, we recalculate styles for every element, then perform a single layout, then a repaint.
Intensive JavaScript - Firefox Developer Tools
then there are three solid blocks of orange, representing javascript execution, one for each time we pressed the button.
... then we need a new file "calculate.js", that looks like this: self.addeventlistener("message", go); function go(message) { var iterations = message.data.iterations; var multiplier = message.data.multiplier; primes = calculateprimes(iterations, multiplier); self.postmessage({ "command":"done", "primes": primes }); } function calculateprimes(iterations, multiplier) { var primes =...
Responsive Design Mode - Firefox Developer Tools
if you checked "screenshot to clipboard" in the developer tools settings page, then the screenshot will be copied to the system clipboard.
...for example, if you've selected an iphone, then firefox identifies itself as safari.
Settings - Firefox Developer Tools
to see the settings, open any of the developer tools, and then: click the "settings" command in the menu: or press f1 to toggle between the active tool and the settings pane the settings pane looks something like this: categories default firefox developer tools this group of checkboxes determines which tools are enabled in the toolbox.
... if common preferences is not included in the settings, web console logs can be persisted by using the 'about:config' url in browser address bar, searching for: 'devtools.webconsole.persistlog' then toggling this value to true inspector show browser styles a setting to control whether styles applied by the browser (user-agent styles) should be displayed in the inspector's rules view.
Taking screenshots - Firefox Developer Tools
tip: you could type :s and then hit tab to autocomplete :screenshot.
... note: if you capture an image to a filename like test.png, and then you capture to that same filename, the new image will overwrite the old image.
Toolbox - Firefox Developer Tools
there are a few different ways to open the toolbox: select "toggle tools" from the web developer menu (under "tools" on os x and linux, or "firefox" on windows) click the wrench icon (), which is in the main toolbar or under the hamburger menu (), then select "toggle tools" activate any tool hosted in the toolbox (for example, the javascript debugger or the page inspector) press ctrl + shift + i on windows and linux, or cmd + opt + i on os x.
... toolbox-hosted tools then there is an array of labeled buttons which enables you to switch between the different tools hosted by the toolbox.
AbortController.AbortController() - Web APIs
we first create a controller using the abortcontroller() constructor, then grab a reference to its associated abortsignal object using the abortcontroller.signal property.
... fetch(url, {signal}).then(function(response) { ...
AbortController.abort() - Web APIs
we first create a controller using the abortcontroller() constructor, then grab a reference to its associated abortsignal object using the abortcontroller.signal property.
... fetch(url, {signal}).then(function(response) { ...
AbortController.signal - Web APIs
we first create a controller using the abortcontroller() constructor, then grab a reference to its associated abortsignal object using the abortcontroller.signal property.
... fetch(url, {signal}).then(function(response) { ...
AbortController - Web APIs
we first create a controller using the abortcontroller() constructor, then grab a reference to its associated abortsignal object using the abortcontroller.signal property.
... fetch(url, {signal}).then(function(response) { ...
AbortSignal - Web APIs
we first create a controller using the abortcontroller() constructor, then grab a reference to its associated abortsignal object using the abortcontroller.signal property.
... fetch(url, {signal}).then(function(response) { ...
AesCtrParams - Web APIs
for example, if length is set to 64, then the first half of counter is the nonce and the second half is used for the counter.
...the counter must be big enough that it doesn't wrap: if the message is n blocks and the counter is m bits long, then the following must be true: n <= 2m.
Animation.ready - Web APIs
WebAPIAnimationready
you'll typically use a construct similar to this when using the ready promise: animation.ready.then(function() { // do whatever needs to be done when // the animation is ready to run }); example in the following example, the state of the animation will be running when the current ready promise is resolved because the animation does not leave the pending play state in between the calls to pause and play and hence the current ready promise does not change.
... animation.pause(); animation.ready.then(function() { // displays 'running' alert(animation.playstate); }); animation.play(); specifications specification status comment web animationsthe definition of 'animation.ready' in that specification.
AudioBufferSourceNode.loopEnd - Web APIs
for example, if you set their values to 20 and 25, respectively, then begin playback, the sound will play normally until it reaches the 25 second mark.
... then the current play position will loop back to the 20 second mark and continue playing until the 25 second mark, ad infinitum (or at least until stop() is called).
AudioContext.close() - Web APIs
syntax var audioctx = new audiocontext(); audioctx.close().then(function() { ...
... stopbtn.onclick = function() { audioctx.close().then(function() { startbtn.removeattribute('disabled'); susresbtn.setattribute('disabled', 'disabled'); stopbtn.setattribute('disabled', 'disabled'); }); } specifications specification status comment web audio apithe definition of 'close()' in that specification.
AudioContext.suspend() - Web APIs
syntax var audioctx = new audiocontext(); audioctx.suspend().then(function() { ...
... susresbtn.onclick = function() { if(audioctx.state === 'running') { audioctx.suspend().then(function() { susresbtn.textcontent = 'resume context'; }); } else if(audioctx.state === 'suspended') { audioctx.resume().then(function() { susresbtn.textcontent = 'suspend context'; }); } } specifications specification status comment web audio apithe definition of 'close()' in that specification.
AudioListener.dopplerFactor - Web APIs
generally you will define the position in 3d space that your audio listener and panner (source) occupy initially, and then update the position of one or both of these as the application is used.
... to see a complete implementation, check out our panner-node example (view the source code) — this demo transports you to the 2.5d "room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes!
AudioListener.forwardX - Web APIs
generally you will define the position in 3d space that your audio listener and panner (source) occupy initially, and then update the position of one or both of these as the application is used.
... to see a complete implementation, check out our panner-node example (view the source code) — this demo transports you to the 2.5d "room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes!
AudioListener.forwardY - Web APIs
generally you will define the position in 3d space that your audio listener and panner (source) occupy initially, and then update the position of one or both of these as the application is used.
... to see a complete implementation, check out our panner-node example (view the source code) — this demo transports you to the 2.5d "room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes!
AudioListener.forwardZ - Web APIs
generally you will define the position in 3d space that your audio listener and panner (source) occupy initially, and then update the position of one or both of these as the application is used.
... to see a complete implementation, check out our panner-node example (view the source code) — this demo transports you to the 2.5d "room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes!
AudioListener.positionX - Web APIs
generally you will define the position in 3d space that your audio listener and panner (source) occupy initially, and then update the position of one or both of these as the application is used.
... to see a complete implementation, check out our panner-node example (view the source code) — this demo transports you to the 2.5d "room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes!
AudioListener.positionY - Web APIs
generally you will define the position in 3d space that your audio listener and panner (source) occupy initially, and then update the position of one or both of these as the application is used.
... to see a complete implementation, check out our panner-node example (view the source code) — this demo transports you to the 2.5d "room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes!
AudioListener.positionZ - Web APIs
generally you will define the position in 3d space that your audio listener and panner (source) occupy initially, and then update the position of one or both of these as the application is used.
... to see a complete implementation, check out our panner-node example (view the source code) — this demo transports you to the 2.5d "room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes!
AudioListener.setOrientation() - Web APIs
generally you will define the position in 3d space that your audio listener and panner (source) occupy initially, and then update the position of one or both of these as the application is used.
... to see a complete implementation, check out our panner-node example (view the source code) — this demo transports you to the 2.5d "room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes!
AudioListener.setPosition() - Web APIs
generally you will define the position in 3d space that your audio listener and panner (source) occupy initially, and then update the position of one or both of these as the application is used.
... to see a complete implementation, check out our panner-node example (view the source code) — this demo transports you to the 2.5d "room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes!
AudioListener.speedOfSound - Web APIs
generally you will define the position in 3d space that your audio listener and panner (source) occupy initially, and then update the position of one or both of these as the application is used.
... to see a complete implementation, check out our panner-node example (view the source code) — this demo transports you to the 2.5d "room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes!
AudioListener.upX - Web APIs
WebAPIAudioListenerupX
generally you will define the position in 3d space that your audio listener and panner (source) occupy initially, and then update the position of one or both of these as the application is used.
... to see a complete implementation, check out our panner-node example (view the source code) — this demo transports you to the 2.5d "room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes!
AudioListener.upY - Web APIs
WebAPIAudioListenerupY
generally you will define the position in 3d space that your audio listener and panner (source) occupy initially, and then update the position of one or both of these as the application is used.
... to see a complete implementation, check out our panner-node example (view the source code) — this demo transports you to the 2.5d "room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes!
AudioListener.upZ - Web APIs
WebAPIAudioListenerupZ
generally you will define the position in 3d space that your audio listener and panner (source) occupy initially, and then update the position of one or both of these as the application is used.
... to see a complete implementation, check out our panner-node example (view the source code) — this demo transports you to the 2.5d "room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes!
AudioListener - Web APIs
generally you will define the position in 3d space that your audio listener and panner (source) occupy initially, and then update the position of one or both of these as the application is used.
... to see a complete implementation, check out our panner-node example (view the source code) — this demo transports you to the 2.5d "room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes!
AudioNode.connect() - Web APIs
WebAPIAudioNodeconnect
for example, you might send the audio from a mediaelementaudiosourcenode—that is, the audio from an html5 media element such as <audio>—through a band pass filter implemented using a biquadfilternode to reduce noise before then sending the audio along to the speakers.
... this example creates an oscillator, then links it to a gain node, so that the gain node controls the volume of the oscillator node.
AudioTrackList.getTrackById() - Web APIs
function disablecharacter(videoelem, charactername) { videoelem.audiotracks.gettrackbyid(charactername).enabled = false; } this short function gets the audiotracklist containing the video's audio tracks using htmlmediaelement.audiotracks, then calls gettrackbyid() on it, specifying the character's name.
... the resulting track's audio is then disabled by setting its enabled flag to false.
BaseAudioContext.createPanner() - Web APIs
generally you will define the position in 3d space that your audio listener and panner (source) occupy initially, and then update the position of one or both of these as the application is used.
... to see a complete implementation, check out our panner-node example (view the source code) — this demo transports you to the 2.5d "room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes!
Blob - Web APIs
WebAPIBlob
it then calls url.createobjecturl() to convert the blob into a url.
... html <p>this example creates a typed array containing the ascii codes for the space character through the letter z, then converts it to an object url.
Bluetooth.requestDevice() - Web APIs
syntax bluetooth.requestdevice([options]) .then(function(bluetoothdevice) { ...
...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.
BluetoothCharacteristicProperties - Web APIs
properties authenticatedsignedwritesread only returns a boolean that is true if signed writing to the characteristic value is permitted.
... nochrome android full support 56firefox android no support noopera android full support yessafari ios no support nosamsung internet android full support 6.0authenticatedsignedwrites experimentalchrome full support 56notes full support 56notes notes chromeos and macos only.
Body.formData() - Web APIs
WebAPIBodyformData
if a user submits a form and a service worker intercepts the request, you could for example call formdata() on it to obtain a key-value map, modify some fields, then send the form onwards to the server (or use it locally).
... syntax response.formdata() .then(function(formdata) { // do something with your formdata }); parameters none.
CSSStyleDeclaration.setProperty() - Web APIs
we then loop through the different rules contained inside the stylesheet, which are contained in the array found at stylesheet.cssrules; for each one, we check whether its cssstylerule.selectortext property is equal to the selector .box p, which indicates it is the one we want.
...we then use three functions to generate random values for the properties in question, and update the rule with these values.
Cache.delete() - Web APIs
WebAPICachedelete
syntax cache.delete(request, {options}).then(function(found) { // your cache entry has been deleted if found }); parameters request the request you are looking to delete.
... examples caches.open('v1').then(function(cache) { cache.delete('/images/image.png').then(function(response) { someuiupdatefunction(); }); }) specifications specification status comment service workersthe definition of 'cache: delete' in that specification.
Cache.keys() - Web APIs
WebAPICachekeys
syntax cache.keys(request, {options}).then(function(keys) { // do something with your array of requests }); parameters request optional the request want to return, if a specific key is desired.
... examples caches.open('v1').then(function(cache) { cache.keys().then(function(keys) { keys.foreach(function(request, index, array) { cache.delete(request); }); }); }) specifications specification status comment service workersthe definition of 'cache: keys' in that specification.
Cache.matchAll() - Web APIs
WebAPICachematchAll
syntax cache.matchall(request, {options}).then(function(response) { // do something with the response array }); parameters request optional the request for which you are attempting to find responses in the cache.
... examples caches.open('v1').then(function(cache) { cache.matchall('/images/').then(function(response) { response.foreach(function(element, index, array) { cache.delete(element); }); }); }) specifications specification status comment service workersthe definition of 'cache: matchall' in that specification.
CanvasRenderingContext2D.clip() - Web APIs
two rectangles are then drawn; only those parts within the clipping region are rendered.
... canvas.getcontext('2d'); // create circular clipping region ctx.beginpath(); ctx.arc(100, 75, 50, 0, math.pi * 2); ctx.clip(); // draw stuff that gets clipped ctx.fillstyle = 'blue'; ctx.fillrect(0, 0, canvas.width, canvas.height); ctx.fillstyle = 'orange'; ctx.fillrect(0, 0, 100, 100); result specifying a path and a fillrule this example saves two rectangles to a path2d object, which is then made the current clipping region using the clip() method.
CanvasRenderingContext2D.fillText() - Web APIs
const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); ctx.font = '50px serif'; ctx.filltext('hello world', 50, 90); this code obtains a reference to the <canvas>, then gets a reference to its 2d graphics context.
... with that in hand, we set the font to 50-pixel-tall "serif" (the user's default serif font), then call filltext() to draw the text "hello world," starting at the coordinates (50, 90).
CanvasRenderingContext2D.getTransform() - Web APIs
we apply a transform to the first one's context using canvasrenderingcontext2d.settransform() and draw a square on it, then retrieve the matrix from it using gettransform().
... we then apply the retrieved matrix directly to the second canvas context by passing the dommatrix object directly to settransform(), and draw a circle on it.
CanvasRenderingContext2D.strokeText() - Web APIs
const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); ctx.font = '50px serif'; ctx.stroketext('hello world', 50, 90); this code obtains a reference to the <canvas>, then gets a reference to its 2d graphics context.
... with that in hand, we set the font to 50-pixel-tall "serif" (the user's default serif font), then call stroketext() to draw the text "hello world," starting at the coordinates (50, 90).
A basic ray-caster - Web APIs
if you have, then the canvas is cleared, the ground and sky are drawn, the camera position and/or orientation are updated, and the rays are cast out.
... as the rays intersect walls, then they render a vertical sliver of canvas in the color of the wall they've hit, blended with a darker version of the color according to the distance to the wall.
Using images - Web APIs
it lets us cut out a section of the source image, then scale and draw it on our canvas.
...we then simply use drawimage() to slice the rhino out of the first image and scale him onto the canvas, then draw the frame on top using a second drawimage() call.
Clients.get() - Web APIs
WebAPIClientsget
syntax self.clients.get(id).then(function(client) { // do something with your returned client }); parameters id a domstring representing the id of the client you want to get.
... examples self.clients.get(id).then(function(client) { self.clients.openwindow(client.url); }); specifications specification status comment service workersthe definition of 'get()' in that specification.
Clients.matchAll() - Web APIs
WebAPIClientsmatchAll
syntax self.clients.matchall(options).then(function(clients) { // do something with your clients list }); parameters options optional an options object allowing you to set options for the matching operation.
... examples clients.matchall(options).then(function(clientlist) { for (var i = 0 ; i < clientlist.length ; i++) { if (clientlist[i].url === 'index.html') { clients.openwindow(clientlist[i]); // or do something else involving the matching client } } }); specifications specification status comment service workersthe definition of 'clients: matchall' in that specification.
Clipboard.read() - Web APIs
WebAPIClipboardread
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.
console - Web APIs
WebAPIConsole
there are two ways to use each of the output methods; you can simply pass in a list of objects whose string representations get concatenated into one string, then output to the console, or you can pass in a string containing zero or more substitution strings followed by a list of objects to replace them.
... for example, given this code: console.time("answer time"); alert("click to continue"); console.timelog("answer time"); alert("do a bunch of other stuff..."); console.timeend("answer time"); will log the time needed by the user to dismiss the alert box, log the time to the console, wait for the user to dismiss the second alert, and then log the ending time to the console: notice that the timer's name is displayed both when the timer is started and when it's stopped.
ConstantSourceNode.offset - Web APIs
then we create a new constantsourcenode and make it the source for the two gain nodes' gainnode.gain values.
...with the linkage above in place, that can be done using this simple event handler: function handleclickevent(event) { volumeslidercontrol.value = constantsource.offset.value; } all this function has to do is fetch the current value of the slider control we're using to control the paired nodes' gains, then store that value into the constantsourcenode's offset parameter.
Credential Management API - Web APIs
federatedcredential provides information about credentials from a federated identity provider, which is an entity that a website trusts to correctly authenticate a user, and which provides an api for that purpose.
... web authentication: an api for accessing public key credentials level 1 recommendation initial definition.
CredentialsContainer - Web APIs
credentialscontainer.preventsilentaccess()secure context sets a flag that specifies whether automatic log in is allowed for future visits to the current origin, then returns an empty promise.
... web authentication: an api for accessing public key credentials level 1 recommendation initial definition.
DOMMatrixReadOnly - Web APIs
(in other words, down the first column from top to bottom, then the second column, and so forth.) dommatrixreadonly.tofloat64array() returns a new float64array containing all 16 elements (m11, m12, m13, m14, m21, m22, m23, m24, m31, m32, m33, m34, m41, m42, m43, m44) which comprise the matrix.
...(in other words, down the first column from top to bottom, then the second column, and so forth.) dommatrixreadonly.tojson() returns a json representation of the dommatrixreadonly object.
DataTransfer.mozClearDataAt() - Web APIs
if the format argument is not provided, then the data associated with all formats is removed.
... if the format is not found, then this method has no effect.
DataTransfer.setDragImage() - Web APIs
if element is an img element, then set the drag data store bitmap to the element's image (at its intrinsic size); otherwise, set the drag data store bitmap to an image generated from the given element (the exact mechanism for doing so is not currently specified).
...rop"); ev.preventdefault(); // get the data, which is the id of the drop target var data = ev.datatransfer.getdata("text"); ev.target.appendchild(document.getelementbyid(data)); } </script> <body> <h1>example of <code>datatransfer.setdragimage()</code></h1> <div> <p id="source" ondragstart="dragstart_handler(event);" draggable="true"> select this element, drag it to the drop zone and then release the selection to move the element.</p> </div> <div id="target" ondrop="drop_handler(event);" ondragover="dragover_handler(event);">drop zone</div> </body> </html> specifications specification status comment html living standardthe definition of 'setdragimage()' in that specification.
DeprecationReportBody - Web APIs
examples in our deprecation_report.html example, we create a simple reporting observer to observe usage of deprecated features on our web page: let options = { types: ['deprecation'], buffered: true } let observer = new reportingobserver(function(reports, observer) { reportbtn.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(); because of the event handler we set up inside the reportingobserver() constructor, we can now click the button to display the report details.
...we loop over each report using a basic for loop, then iterate over each entry of in the report's body (a deprecationreportbody instance) using a for...in structure, displaying each key/value pair inside a list item.
Document.createDocumentFragment() - Web APIs
the usual use case is to create the document fragment, append elements to the document fragment and then append the document fragment to the dom tree.
... you can also use the documentfragment constructor to create a new fragment: let fragment = new documentfragment(); example this example creates a list of major web browsers in a documentfragment, then adds the new dom subtree to the document to be displayed.
Document: fullscreenchange event - Web APIs
bubbles yes cancelable no interface event event handler property onfullscreenchange the event is sent to the element that is transitioning into or out of full-screen mode, and this event then bubbles up to the document.
... to find out whether the element is entering or exiting full-screen mode, check the value of documentorshadowroot.fullscreenelement: if this value is null then the element is exiting full-screen mode, otherwise it is entering full-screen mode.
Document.importNode() - Web APIs
if deep is set to true, then externalnode and all of its descendants are copied.
... if deep is set to false, then only externalnode is imported — the new node has no children.
DocumentOrShadowRoot.elementFromPoint() - Web APIs
if the element at the given point is anonymous or xbl generated content, such as a textbox's scroll bars, then the first non-anonymous ancestor element (for example, the textbox) is returned.
... javascript function changecolor(newcolor) { elem = document.elementfrompoint(2, 2); elem.style.color = newcolor; } the changecolor() method simply obtains the element located at the specified point, then sets that element's current foreground color property to the color specified by the newcolor parameter.
EffectTiming.direction - Web APIs
"reverse" the animation runs backwards, or "rewinds." "alternate" the animation switches direction after each iteration, going forward through the animation sequence the first iteration, then backward through the sequence the second iteration, and so forth.
... "alternate-reverse" similar to "alternate", except the animation playback starts by going from the end of the animation sequence toward the beginning the first iteration, then goes forward during the second, and so forth.
Element.getElementsByClassName() - Web APIs
st.remove('colorbox'); matches.item(i).classlist.add('hueframe'); } instead, use another method, such as: var matches = element.getelementsbyclassname('colorbox'); while (matches.length > 0) { matches.item(0).classlist.add('hueframe'); matches[0].classlist.remove('colorbox'); } this code finds descendant elements with the "colorbox" class, adds the class "hueframe", by calling item(0), then removes "colorbox" (using array notation).
... another element (if any are left) will then become item(0).
Element: mousedown event - Web APIs
first we store the x and y coordinates of the mouse pointer in the variables x and y, and then set isdrawing to true.
... when the drawline() function returns, we adjust the coordinates and then save them in x and y.
Element: mouseenter event - Web APIs
a single mouseover event is sent to the deepest element of the dom tree, then it bubbles up the hierarchy until it is canceled by a handler or reaches the root.
...it then adds an item to the list with the number of the mouseenter or mouseleave event.
Element: mouseleave event - Web APIs
one single mouseout event is sent to the deepest element of the dom tree, then it bubbles up the hierarchy until it is canceled by a handler or reaches the root.
...it then adds an item to the list with the number of the mouseenter or mouseleave event.
Element: mousemove event - Web APIs
first we store the x and y coordinates of the mouse pointer in the variables x and y, and then set isdrawing to true.
... when the drawline() function returns, we adjust the coordinates and then save them in x and y.
Element: mouseup event - Web APIs
first we store the x and y coordinates of the mouse pointer in the variables x and y, and then set isdrawing to true.
... when the drawline() function returns, we adjust the coordinates and then save them in x and y.
Element.onfullscreenchange - Web APIs
this function determines which element it was called on by checking the value of event.target, then compares the document's fullscreenelement value to the element to see if they're the same node.
... function togglefullscreen() { let elem = document.queryselector("video"); elem.onfullscreenchange = handlefullscreenchange; if (!document.fullscreenelement) { elem.requestfullscreen().then({}).catch(err => { alert(`error attempting to enable full-screen mode: ${err.message} (${err.name})`); }); } else { document.exitfullscreen(); } } function handlefullscreenchange(event) { let elem = event.target; let isfullscreen = document.fullscreenelement === elem; adjustmycontrols(isfullscreen); } specifications specification status comment ...
Element: paste event - Web APIs
bubbles yes cancelable yes interface clipboardevent event handler property onpaste if the cursor is in an editable context (for example, in a <textarea> or an element with contenteditable attribute set to true) then the default action is to insert the contents of the clipboard into the document at the cursor position.
... to override the default behavior (for example to insert some different data or a transformation of the clipboard contents) an event handler must cancel the default action using event.preventdefault(), and then insert its desired data manually.
Element.slot - Web APIs
WebAPIElementslot
examples in our simple-template example (see it live), we create a trivial custom element example called <my-paragraph> in which a shadow root is attached and then populated using the contents of a template that contains a slot named my-text.
...here is one such example: <my-paragraph> <span slot="my-text">let's have some different text!</span> </my-paragraph> in our javascript file we get a reference to the <span> shown above, then log a reference to the name of the corresponding <slot> element.
Event.composed - Web APIs
WebAPIEventcomposed
the first definition looks like this, for example: customelements.define('open-shadow', class extends htmlelement { constructor() { super(); let pelem = document.createelement('p'); pelem.textcontent = this.getattribute('text'); let shadowroot = this.attachshadow({mode: 'open'}) .appendchild(pelem); } }); we then insert one of each element into our page: <open-shadow text="i have an open shadow root"></open-shadow> <closed-shadow text="i have a closed shadow root"></closed-shadow> then include a click event listener on the <html> element: document.queryselector('html').addeventlistener('click',function(e) { console.log(e.composed); console.log(e.composedpath()); }); when you click on the <open-sha...
...dow> element and then the <closed-shadow> element, you'll notice two things.
Event.composedPath() - Web APIs
the first definition looks like this, for example: customelements.define('open-shadow', class extends htmlelement { constructor() { super(); let pelem = document.createelement('p'); pelem.textcontent = this.getattribute('text'); let shadowroot = this.attachshadow({mode: 'open'}) .appendchild(pelem); } }); we then insert one of each element into our page: <open-shadow text="i have an open shadow root"></open-shadow> <closed-shadow text="i have a closed shadow root"></closed-shadow> then include a click event listener on the <html> element: document.queryselector('html').addeventlistener('click',function(e) { console.log(e.composed); console.log(e.composedpath()); }); when you click on the <open-sha...
...dow> element and then the <closed-shadow> element, you'll notice two things.
Event - Web APIs
WebAPIEvent
it can also be triggered programmatically, such as by calling the htmlelement.click() method of an element, or by defining the event, then sending it to a specified target using eventtarget.dispatchevent().
... deprecated methods event.createevent() creates a new event, which must then be initialized by calling its initevent() method.
EventSource - Web APIs
if no event field is present, then a generic message event is fired.
...it, in turn, creates a new <li> element and writes the message's data into it, then appends the new element to the list element already in the document.
ExtendableMessageEvent - Web APIs
examples in the below example a page gets a handle to the serviceworker object via serviceworkerregistration.active, and then calls its postmessage() function.
... // 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 worker can receive the message by listening to the message event: // in the service worker addeventlistener('message', event => { // event is an extendablemessageevent object console.log(`the client sent me a message: ${event.data}`); event.source.postmessage("hi client"); }); specifications specification status comment servic...
FederatedCredential - Web APIs
a federated identity provider is an entity that a website trusts to correctly authenticate a user, and that provides an api for that purpose.
... 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.
FetchEvent.request - Web APIs
self.addeventlistener('fetch', function(event) { console.log('handling fetch event for', event.request.url); event.respondwith( caches.match(event.request).then(function(response) { if (response) { console.log('found response in cache:', response); return response; } console.log('no response found in cache.
... about to fetch from network...'); return fetch(event.request).then(function(response) { console.log('response from network is:', response); return response; }).catch(function(error) { console.error('fetching failed:', error); throw error; }); }) ); }); specifications specification status comment service workersthe definition of 'request' in that specification.
FileSystemEntrySync - Web APIs
you can keep it in the same location and then define the newname parameter.
...if this entry is the root of its file system, then the parent is itself.
FontFaceSet.load() - Web APIs
WebAPIFontFaceSetload
examples // returns a promise that will be fulfilled or rejected according the success to load myfont // the code in 'then' can assume the availability of that font.
... document.fonts.load("12px myfont", "ß").then(…); specifications specification status comment css font loading module level 3the definition of 'load' in that specification.
GlobalEventHandlers.onanimationcancel - Web APIs
function log(msg, event) { let logbox = document.getelementbyid("log"); logbox.innerhtml += msg; if (event) { logbox.innerhtml += " <code>"+ event.animationname + "</code> at time " + event.elapsedtime.tofixed(2) + " seconds."; } logbox.innerhtml += "\n"; }; then we set up the handlecancelevent() function, which is called in response to the animationcancel event, as set up in the html above.
... function handlecancelevent(event) { log("animation canceled", event); }; then we add a method to handle toggle display between "flex" and "none" and establish it as the handler for a click event on the "hide/show" the box button: document.getelementbyid('togglebox').addeventlistener('click', function() { if (box.style.display == "none") { box.style.display = "flex"; document.getelementbyid("togglebox").innerhtml = "hide the box"; } else { box.style.display = "none"; document.getelementbyid("togglebox").innerhtml = "show the box"; } }); toggling the box to display: none has the effect of aborting...
GlobalEventHandlers.onanimationend - Web APIs
function log(msg, event) { let logbox = document.getelementbyid("log"); logbox.innerhtml += msg; if (event) { logbox.innerhtml += " <code>"+ event.animationname + "</code> at time " + event.elapsedtime.tofixed(2) + " seconds."; } logbox.innerhtml += "\n"; }; then we set up the event handlers for the animationstart and animationend events: let box = document.getelementbyid("box"); box.onanimationstart = function(event) { log("animation started", event); } box.onanimationend = function(event) { log("animation stopped", event); }; finally, we set up a handler for a click on the button that runs the animation: document.getelementbyid("play").addeven...
...tlistener("click", function(event) { document.getelementbyid("box").classname = "slideanimation"; event.target.style.display = "none"; }, false); this sets the class of the box we want to animate to the class that contains the animation description, then hides the play button because this example will only run the animation once.
GlobalEventHandlers.onanimationiteration - Web APIs
the onanimationiteration event handler is then set up.
... it simply sets the box's animation-play-state to "paused", then updates the text displayed in the button to indicate that clicking the button will start playing the next iteration of theanimation.
GlobalEventHandlers.onanimationstart - Web APIs
function log(msg, event) { let logbox = document.getelementbyid("log"); logbox.innerhtml += msg; if (event) { logbox.innerhtml += " <code>"+ event.animationname + "</code> at time " + event.elapsedtime.tofixed(2) + " seconds."; } logbox.innerhtml += "\n"; }; then we set up the event handlers for the animationstart and animationend events: let box = document.getelementbyid("box"); box.onanimationstart = function(event) { log("animation started", event); } box.onanimationend = function(event) { log("animation stopped", event); }; finally, we set up a handler for a click on the button that runs the animation: document.getelementbyid("play").addeven...
...tlistener("click", function(event) { document.getelementbyid("box").classname = "slideanimation"; event.target.style.display = "none"; }, false); this sets the class of the box we want to animate to the class that contains the animation description, then hides the play button because this example will only run the animation once.
GlobalEventHandlers.onchange - Web APIs
example this example logs the number of characters in an <input> element, every time you modify its contents and then change focus away from it.
... html <input type="text" placeholder="type something here, then click outside of the field." size="50"> <p id="log"></p> javascript let input = document.queryselector('input'); let log = document.getelementbyid('log'); input.onchange = handlechange; function handlechange(e) { log.textcontent = `the field's value is ${e.target.value.length} character(s) long.`; } result specification specification status comment html living standardthe definition of 'onchange' in that specification.
GlobalEventHandlers.onpointerdown - Web APIs
the handledown() function, in turn, looks at the value of pointertype to determine what kind of pointing device was used, then uses that information to customize a string to replace the contents of the target box.
... then the event's preventdefault() method is called to ensure that the mousedown event isn't triggered, potentially causing events to be handled twice if we had a handler for those events in case pointer event support is missing.
HTMLButtonElement - Web APIs
if the button is a descendant of a form element, then this attribute is the id of that form element.
... if the button is not a descendant of a form element, then the attribute can be the id of any form element in the same document it is related to, or the null value if none matches.
HTMLCanvasElement.mozGetAsFile() - Web APIs
examples this example creates an image file from the <canvas> element on the page, then uses a filereader to read the image data from the file.
...then a new <img> element is created using the new data url.
HTMLCanvasElement.toBlob() - Web APIs
the code snippet below, for example, takes the image in the <canvas> element whose id is "canvas", obtains a copy of it as a png image, then appends a new <img> element to the document, whose source image is the one created using the canvas.
... cu.import('resource://gre/modules/osfile.jsm'); var writepath = os.path.join(os.constants.path.desktopdir, iconname + '.ico'); var promise = os.file.writeatomic(writepath, new uint8array(r.result), {tmppath:writepath + '.tmp'}); promise.then( function() { console.log('successfully wrote file'); }, function() { console.log('failure writing file') } ); }; r.readasarraybuffer(b); } } canvas.toblob(blobcallback('passthisstring'), 'image/vnd.microsoft.icon', '-moz-parse-options:format=bmp;bpp=32'); specifications specification status comment html li...
HTMLFieldSetElement - Web APIs
if the field set is not a descendant of a form element, then the attribute can be the id of any form element in the same document it is related to, or the null value if none matches.
...if this message is not the empty string, then the field set is suffering from a custom validity error, and does not validate.
HTMLFormElement - Web APIs
you can then use any of the following syntaxes to get an individual form: document.forms[index] returns the form at the specified index into the array of forms.
... examples creating a new form element, modifying its attributes, then submitting it: const f = document.createelement("form"); // create a form document.body.appendchild(f); // add it to the document body f.action = "/cgi-bin/some.cgi"; // add action and method attributes f.method = "post"; f.submit(); // call the form's submit() method extract information from a <form> element and set some of its attributes: ...
HTMLImageElement.sizes - Web APIs
each source size descriptor is comprised of a media condition, then at least one whitespace character, then the source size value to use for the image when the media condition evaluates to true.
...img src="/files/16870/new-york-skyline-wide.jpg" srcset="/files/16870/new-york-skyline-wide.jpg 3724w, /files/16869/new-york-skyline-4by3.jpg 1961w, /files/16871/new-york-skyline-tall.jpg 1060w" sizes="((min-width: 50em) and (max-width: 60em)) 50em, ((min-width: 30em) and (max-width: 50em)) 30em, (max-width: 30em) 20em"> <p>then there's even more amazing stuff to say down here.
HTMLInputElement.stepDown() - Web APIs
example click the button in this example to increment the number input type: html <p> <label>enter a number between 0 and 400 that is divisible by 5: <input type="number" step="5" id="thenumber" min="0" max="400"> </label> </p> <p> <label>enter how many values of step you would like to increment by or leave it blank: <input type="number" step="1" id="decrementer" min="-2" max="15"> </label> </p> <input type="button" value="decrement" id="thebutton"> javascript /* make the button call the function */ let button = document.getelementbyid('thebutton'); button.addeventliste...
...ner('click', function() { stepondown();} ); function stepondown() { let input = document.getelementbyid('thenumber'); let val = document.getelementbyid('decrementer').value; if (val) { /* increment with a parameter */ input.stepdown(val); } else { /* or without a parameter.
HTMLInputElement.stepUp() - Web APIs
example click the button in this example to increment the number input type: html <p> <label>enter a number between 0 and 400 that is divisible by 5: <input type="number" step="5" id="thenumber" min="0" max="400"> </label> </p> <p> <label>enter how many values of step you would like to increment by or leave it blank: <input type="number" step="1" id="incrementer" min="0" max="25"> </label> </p> <input type="button" value="increment" id="thebutton"> javascript /* make the button call the function */ let button = document.getelementbyid('thebutton') button.addeventlistene...
...r('click', function() { steponup() }) function steponup() { let input = document.getelementbyid('thenumber') let val = document.getelementbyid('incrementer').value if (val) { /* increment with a parameter */ input.stepup(val) } else { /* or without a parameter.
HTMLInputElement - Web APIs
if this message is not the empty string, then the element is suffering from a custom validity error, and does not validate.
... reportvalidity() runs the checkvalidity() method, and if it returns false (for an invalid input or no pattern attribute provided), then it reports to the user that the input is invalid in the same manner as if you submitted a form.
HTMLOutputElement - Web APIs
if the element is not rendered, then the user agent may report the error for the running script instead of notifying the user.
...if this message is not the empty string, then the element is suffering from a custom validity error, and does not validate.
HTMLSelectElement - Web APIs
if the element is not associated with of a <form> element, then it returns null.
...this will tell you when the value changes, and you can then update anything you need to.
HTMLVideoElement.videoHeight - Web APIs
if the element's readystate is htmlmediaelement.have_nothing, then the value of this property is 0, because neither video nor poster frame size information is yet available.
... about intrinsic width and height a user agent calculates the intrinsic width and height of the element's media by starting with the media's raw pixel width and height, then taking into account factors including: the media's aspect ratio.
HTMLVideoElement.videoWidth - Web APIs
if the element's readystate is htmlmediaelement.have_nothing, then the value of this property is 0, because neither video nor poster frame size information is yet available.
... about intrinsic width and height a user agent calculates the intrinsic width and height of the element's media by starting with the media's raw pixel width and height, then taking into account factors including: the media's aspect ratio.
History.replaceState() - Web APIs
then suppose https://www.mozilla.org/bar.html executes the following javascript: history.replacestate(stateobj, '', 'bar2.html'); this will cause the url bar to display https://www.mozilla.org/bar2.html, but won't cause the browser to load bar2.html or even check that bar2.html exists.
... suppose now that the user navigates to https://www.microsoft.com, then clicks the back button.
Ajax navigation example - Web APIs
305: "use proxy", 306: "reserved", 307: "temporary redirect", 308: "permanent redirect", 400: "bad request", 401: "unauthorized", 402: "payment required", 403: "forbidden", 404: "not found", 405: "method not allowed", 406: "not acceptable", 407: "proxy authentication required", 408: "request timeout", 409: "conflict", 410: "gone", 411: "length required", 412: "precondition failed", 413: "request entity too large", 414: "request-uri too long", 415: "unsupported media type", 416: "requested range not satisfiable", 417: "expectation fai...
..."not implemented", 502: "bad gateway", 503: "service unavailable", 504: "gateway timeout", 505: "http version not supported", 506: "variant also negotiates (experimental)", 507: "insufficient storage", 508: "loop detected", 509: "unassigned", 510: "not extended", 511: "network authentication required" }; var oreq, bisloading = false, bupdateurl = false; oloadingbox.id = "ajax-loader"; ocover.onclick = abortreq; oloadingimg.src = "data:image/gif;base64,r0lgodlheaaqapiaap///waaamlcwkjcqgaaagjiyokcgpkskih/c05fvfndqvbfmi4waweaaaah/hpdcmvhdgvkihdpdgggywphegxvywquaw5mbwah+qqjcgaaacwaaaaaeaaqaaadmwi63p4wyklre2mioggznadomgyjrbexwroumcg2lmdewnhqlvsyo...
IDBCursor.update() - Web APIs
WebAPIIDBCursorupdate
example in this simple fragment we create a transaction, retrieve an object store, then use a cursor to iterate through all the records in the object store.
...in such a situation, you would have to delete the record altogether and then add a new one using idbobjectstore.add.
IDBDatabase.transaction() - Web APIs
example in this example we open a database connection, then use transaction() to open a transaction on the database.
...duplicate items not allowed.</li>'; }; // you would then go on to do something to this database // via an object store var objectstore = transaction.objectstore("todolist"); // etc.
IDBDatabase - Web APIs
the idbdatabase interface of the indexeddb api provides a connection to a database; you can use an idbdatabase object to open a transaction on your database then create, manipulate, and delete objects (data) in that database.
...inutes", { unique: false }); objectstore.createindex("day", "day", { unique: false }); objectstore.createindex("month", "month", { unique: false }); objectstore.createindex("year", "year", { unique: false }); objectstore.createindex("notified", "notified", { unique: false }); note.innerhtml += '<li>object store created.</li>'; }; this next line opens up a transaction on the database, then opens an object store that we can then manipulate the data inside of.
IDBFactory.deleteDatabase() - Web APIs
if the database is successfully deleted, then a success event is fired on the request object returned from this method, with its result set to undefined.
... if an error occurs while the database is being deleted, then an error event is fired on the request object that is returned from this method.
IDBIndex.isAutoLocale - Web APIs
example in the following example we open a transaction and an object store, then get the index lname from a simple contacts database.
... we then open a basic cursor on the index using idbindex.opencursor — this works the same as opening a cursor directly on an objectstore using idbobjectstore.opencursor except that the returned records are sorted based on the index, not the primary key.
IDBIndex.keyPath - Web APIs
WebAPIIDBIndexkeyPath
example in the following example we open a transaction and an object store, then get the index lname from a simple contacts database.
... we then open a basic cursor on the index using idbindex.opencursor — this works the same as opening a cursor directly on an objectstore using idbobjectstore.opencursor except that the returned records are sorted based on the index, not the primary key.
IDBIndex.locale - Web APIs
WebAPIIDBIndexlocale
example in the following example we open a transaction and an object store, then get the index lname from a simple contacts database.
... we then open a basic cursor on the index using idbindex.opencursor — this works the same as opening a cursor directly on an objectstore using idbobjectstore.opencursor except that the returned records are sorted based on the index, not the primary key.
IDBIndex.multiEntry - Web APIs
example in the following example we open a transaction and an object store, then get the index lname from a simple contacts database.
... we then open a basic cursor on the index using idbindex.opencursor — this works the same as opening a cursor directly on an objectstore using idbobjectstore.opencursor except that the returned records are sorted based on the index, not the primary key.
IDBIndex.name - Web APIs
WebAPIIDBIndexname
example in the following example we open a transaction and an object store, then get the index lname from a simple contacts database.
... we then open a basic cursor on the index using idbindex.opencursor() — this works the same as opening a cursor directly on an idbobjectstore using opencursor() except that the returned records are sorted based on the index, not the primary key.
IDBIndex.objectStore - Web APIs
example in the following example we open a transaction and an object store, then get the index lname from a simple contacts database.
... we then open a basic cursor on the index using idbindex.opencursor.
IDBIndex.unique - Web APIs
WebAPIIDBIndexunique
example in the following example we open a transaction and an object store, then get the index lname from a simple contacts database.
... we then open a basic cursor on the index using idbindex.opencursor — this works the same as opening a cursor directly on an objectstore using idbobjectstore.opencursor except that the returned records are sorted based on the index, not the primary key.
IDBIndexSync - Web APIs
the range of the new cursor matches the specified key range; if the key range is not specified or is null, then the range includes all the records.
...the range of the new cursor matches the specified key range; if the key range is not specified or is null, then the range includes all the records.
IDBKeyRange - Web APIs
if the key range has both upper and lower bounds, then it is bounded; if it has no bounds, it is unbounded.
...if we used idbkeyrange.bound("a", "f", true, true);, then the range would not include "a" and "f", only the values between them.
IDBObjectStore.get() - Web APIs
if a value is successfully found, then a structured clone of it is created and set as the result of the request object.
...once this data object is retrieved, you could then update it using normal javascript, then put it back into the database using a idbobjectstore.put operation.
IDBObjectStore.index() - Web APIs
example in the following example we open a transaction and an object store, then get the index lname from a simple contacts database.
... we then open a basic cursor on the index using idbindex.opencursor — this works the same as opening a cursor directly on an objectstore using idbobjectstore.opencursor except that the returned records are sorted based on the index, not the primary key.
IDBObjectStore.put() - Web APIs
if the record is successfully stored, then a success event is fired on the returned request object with the result set to the key for the stored record, and the transaction set to the transaction in which this object store is opened.
... example the following example requests a given record title; when that request is successful the onsuccess function gets the associated record from the idbobjectstore (made available as objectstoretitlerequest.result), updates one property of the record, and then puts the updated record back into the object store in another request with put().
IDBObjectStoreSync - Web APIs
if this attribute is set to null, then the application must provide a key for each modification operation.
...the range of the new cursor matches the specified key range; if the key range is not specified or is null, then the range includes all the records.
IDBRequest.error - Web APIs
WebAPIIDBRequesterror
the following error codes are returned under certain conditions: error explanation aborterror if you abort the transaction, then all requests still in progress receive this error.
... example the following example requests a given record title, onsuccess gets the associated record from the idbobjectstore (made available as objectstoretitlerequest.result), updates one property of the record, and then puts the updated record back into the object store.
IDBRequest.transaction - Web APIs
if a version upgrade is needed when opening a database then during the upgradeneeded event handler the transaction property will be an idbtransaction with mode equal to "versionchange", and can be used to access existing object stores and indexes, or abort the the upgrade.
... example the following example requests a given record title, onsuccess gets the associated record from the idbobjectstore (made available as objectstoretitlerequest.result), updates one property of the record, and then puts the updated record back into the object store in another request.
ImageCapture.getPhotoCapabilities() - Web APIs
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; input.max = photocapabilities.imagewidth.max; ...
...input.step = photocapabilities.imagewidth.step; return imagecapture.getphotosettings(); }) .then(photosettings => { input.value = photosettings.imagewidth; }) .catch(error => console.log('argh!', error.name || error)); specifications specification status comment mediastream image capturethe definition of 'getphotocapabilities()' in that specification.
ImageCapture.getPhotoSettings() - Web APIs
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; input.max = photocapabilities.imagewidth.max; ...
...input.step = photocapabilities.imagewidth.step; return imagecapture.getphotosettings(); }) .then(photosettings => { input.value = photosettings.imagewidth; }) .catch(error => console.log('argh!', error.name || error)); specifications specification status comment mediastream image capturethe definition of 'getphotosettings()' in that specification.
ImageCapture - Web APIs
the track is then used to create an imagecapture object so that takephoto() and grabframe() can be called.
... 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('#grabframecanvas'); drawcanvas(canvas, imagebitmap); }) .catch(error => console.log(error)); } function ontakephotobuttonclick() { imagecapture.takephoto() .then(blob => createimagebitmap(blob)) .then(imagebitmap => { const canvas = d...
Basic concepts - Web APIs
if an object store does not have a key generator, then the application must provide keys for records being stored.
...after the key has been generated, it can then be stored in the value using the key path or it can also be used as a key.
IntersectionObserver.root - Web APIs
if the root is null, then the bounds of the actual document viewport are used.
... if root is null, then the owning document is used as the root, and the bounds its viewport (that is, the visible area of the document) are used as the root bounds.
Key Values - Web APIs
this saves the state of the computer to disk and then shuts down; the computer can be returned to its previous state by restoring the saved state information.
... vk_info qt::key_info (0x0100011b) keycode_info (165) "instantreplay" tellls the device to perform an instant replay (typically some form of jumping back a short amount of time then playing it again, possibly but not usually in slow motion).
MediaDevices.getDisplayMedia() - Web APIs
the resulting stream can then be recorded using the mediastream recording api or transmitted as part of a webrtc session.
...the stream is then returned to the caller for use, perhaps for adding to a webrtc call using rtcpeerconnection.addtrack() to add the video track from the stream.
MediaElementAudioSourceNode - Web APIs
example this simple example creates a source from an <audio> element using createmediaelementsource(), then passes the audio through a gainnode before feeding it into the audiodestinationnode for playback.
...yscript.innerhtml; // create a mediaelementaudiosourcenode // feed the htmlmediaelement into it var source = audioctx.createmediaelementsource(myaudio); // create a gain node var gainnode = audioctx.creategain(); // create variables to store mouse pointer y coordinate // and height of screen var cury; var height = window.innerheight; // get new mouse pointer coordinates when mouse is moved // then set new gain value document.onmousemove = updatepage; function updatepage(e) { cury = (window.event) ?
MediaError.message - Web APIs
example this example creates a <audio> element, establishes an error handler for it, then lets the user click buttons to choose whether to assign a valid audio file or a missing file to the element's src attribute.
...then the resulting text is output to the log.
close() - Web APIs
then, it returns a promise.
... syntax mediakeysession.close().then(function() { ...
update() - Web APIs
the mediakeysession.update() method loads messages and licenses to the cdm, and then returns a promise .
... syntax mediakeysession.update(response).then(function() { ...
MediaRecorder.mimeType - Web APIs
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,options); m = mediarecorder; m.mimetype; // would return 'video/mp4' ...
... mimetype: 'video/mp4; codecs="avc1.424028, mp4a.40.2"' assuming this configuration is acceptable to the user agent, the value returned later by m.mimetype would then be video/mp4; codecs="avc1.424028, mp4a.40.2".
MediaRecorder.requestData() - Web APIs
this can then be grabbed and manipulated as you wish.
... capturemedia.onclick = function() { mediarecorder.requestdata(); // makes snapshot available of data so far // ondataavailable fires, then capturing continues // in new blob } ...
MediaRecorder.state - Web APIs
syntax var state = mediarecorder.state values a animationplaystate object containing one of the following values: enumeration description inactive recording is not occuring — it has either not been started yet, or it has been started and then stopped.
... paused recording has been started, then paused, but not yet stopped or resumed.
MediaRecorder - Web APIs
you can then collect and act upon that recorded media data using this event handler.
... 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("recorder started"); record.style.background = "red"; record.style.color = "black"; } stop.onclick = function() { mediarecorder.stop(); console.log(m...
MediaSettingsRange - Web APIs
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; input.max = photocapabilities.imagewidth.max; ...
...input.step = photocapabilities.imagewidth.step; return imagecapture.getphotosettings(); }) .then(photosettings => { input.value = photosettings.imagewidth; }) .catch(error => console.log('argh!', error.name || error)); specifications specification status comment mediastream image capturethe definition of 'mediasettingsrange' in that specification.
MediaSource.setLiveSeekableRange() - Web APIs
if the duration of the media source is positive infinity, then the timeranges object returned by the htmlmediaelement.seekable property will have a start timestamp no greater than this value.
...if the duration of the media source is positive infinity, then the timeranges object returned by the htmlmediaelement.seekable property will have an end timestamp no less than this value.
MediaStream.getAudioTracks() - Web APIs
example this example gets a webcam's audio and video in a stream using getusermedia(), attaches the stream to a <video> element, then sets a timer that, upon expiring, will stop the first audio track found on the stream.
... 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 of 'getaudiotracks()' in that specification.
MediaStreamAudioSourceNode() - Web APIs
examples this example uses getusermedia() to obtain access to the user's camera, then creates a new mediastreamaudiosourcenode from its mediastream.
... // 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); }).catch(function(err) { console.log('the following gum error occured: ' + err); }); } else { console.log('new getusermedia not supported on your browser!'); } specifications specification ...
MediaStreamConstraints.audio - Web APIs
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.
...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, the sample rate be 8 bits per sample instead of the more common 16 bits (possibly as a bandwidth saving meas...
MediaStreamConstraints.video - Web APIs
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.
... } 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 dimensions are as close as possible to 160x120 pixels, and whose frame rate is as close to 15 frames per second as possible.
MediaStreamTrackAudioSourceNode() - Web APIs
example this example uses getusermedia() to obtain access to the user's camera, then creates a new mediastreamaudiosourcenode from the first audio track provided by the device.
... 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 following gum error occured: ' + err); }); } else { console.log('new getusermedia not supported on your browser!'); } specifications specification status comment web audio apithe definition of 'mediastreamtrackaudiosourcenode()' in that specification.
MediaStreamTrackAudioSourceOptions.mediaStreamTrack - Web APIs
example this example uses getusermedia() to obtain access to the user's camera, then creates a new mediastreamaudiosourcenode from the first audio track provided by the device.
... 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 following gum error occured: ' + err); }); } else { console.log('new getusermedia not supported on your browser!'); } specifications specification status comment web audio apithe definition of 'mediastreamtrackaudiosourceoptions.mediastream' in that specification.
Media Source API - Web APIs
if you do not require explicit control of video quality over time, the rate at which content is fetched, or the rate at which memory is evicted, then the <video> and <source> tags may well be a simple and adequate solution.
... extensions to other interfaces url.createobjecturl() creates an object url pointing to a mediasource object that can then be specified as the src value of an html media element to play a media stream.
MessageEvent - Web APIs
both scripts contain this: var myworker = new sharedworker('worker.js'); both scripts then access the worker through a messageport object created using the sharedworker.port property.
...the ports associated with that worker are accessible in the connect event's ports property — we then use messageport start() method to start the port, and the onmessage handler to deal with messages sent from the main threads.
msPlayToSource - Web APIs
msplaytosource is used in the sourcerequested handler -- get the playtosource object from an audio, video, or img element using the msplaytosource property and pass it to e.setsource, then set the playtosource.next property to the msplaytosource of another element for continual playing.
... e.sourcerequest.setsource(document.getelementbyid("videoplayer").msplaytosource); // the media will then be streamed to the device chosen by the user in the ui.
MutationObserver.disconnect() - Web APIs
usage notes if the element being observed is removed from the dom, and then subsequently released by the browser's garbage collection mechanism, the mutationobserver is likewise deleted.
... example this example creates an observer, then disconnects from it, leaving it available for possible reuse.
Navigator.deviceMemory - Web APIs
it’s approximated by rounding down to the nearest power of 2, then dividing that number by 1024.
... it is then clamped within lower and upper bounds to protect the privacy of owners of very low- or high-memory devices.
Navigator.msLaunchUri() - Web APIs
if a handler doesn't exist, and the developer doesn't provide a nohandlercallback, then internet explorer displays a dialog that asks the user if they want to allow the action.
... if the user allows it, the user is then prompted to look in the windows store for an app to handle the protocol.
Navigator.share() - Web APIs
WebAPINavigatorshare
then include an array of files in the call to navigator.share(): notice: that the sample handles feature detection by testing for navigator.canshare() rather than for navigator.share().
... if (navigator.canshare && navigator.canshare({ files: filesarray })) { navigator.share({ files: filesarray, title: 'pictures', text: 'our pictures.', }) .then(() => console.log('share was successful.')) .catch((error) => console.log('sharing failed', error)); } else { console.log(`your system doesn't support sharing files.`); } specifications specification status comment web share apithe definition of 'share()' in that specification.
Node.cloneNode() - Web APIs
WebAPINodecloneNode
deep optional* if true, then node and its whole subtree—including text that may be in child text nodes—is also copied.
... if the original node has an id attribute, and the clone will be placed in the same document, then you should modify the clone's id to be unique.
Notification - Web APIs
examples assume this basic html: <button onclick="notifyme()">notify me!</button> it's possible to send a notification as follows — here we present a fairly verbose and complete set of code you could use if you wanted to first check whether notifications are supported, then check if permission has been granted for the current origin to send notifications, then request permission if required, before then sending a notification.
... notification"); } // let's check whether notification permissions have already been granted else if (notification.permission === "granted") { // if it's okay let's create a notification var notification = new notification("hi there!"); } // otherwise, we need to ask the user for permission else if (notification.permission !== "denied") { notification.requestpermission().then(function (permission) { // if the user accepts, let's create a notification if (permission === "granted") { var notification = new notification("hi there!"); } }); } // at last, if the user has denied notifications, and you // want to be respectful there is no need to bother them any more.
PannerNode.distanceModel - Web APIs
generally you will define the position in 3d space that your audio listener and panner (source) occupy initially, and then update the position of one or both of these as the application is used.
... to see a complete implementation, check out our panner-node example (view the source code) — this demo transports you to the 2.5d "room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes!
PannerNode.maxDistance - Web APIs
generally you will define the position in 3d space that your audio listener and panner (source) occupy initially, and then update the position of one or both of these as the application is used.
... to see a complete implementation, check out our panner-node example (view the source code) — this demo transports you to the 2.5d "room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes!
PannerNode.panningModel - Web APIs
generally you will define the position in 3d space that your audio listener and panner (source) occupy initially, and then update the position of one or both of these as the application is used.
... to see a complete implementation, check out our panner-node example (view the source code) — this demo transports you to the 2.5d "room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes!
PannerNode.setOrientation() - Web APIs
generally you will define the position in 3d space that your audio listener and panner (source) occupy initially, and then update the position of one or both of these as the application is used.
... to see a complete implementation, check out our panner-node example (view the source code) — this demo transports you to the 2.5d "room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes!
PannerNode.setPosition() - Web APIs
generally you will define the position in 3d space that your audio listener and panner (source) occupy initially, and then update the position of one or both of these as the application is used.
... to see a complete implementation, check out our panner-node example (view the source code) — this demo transports you to the 2.5d "room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes!
PannerNode.setVelocity() - Web APIs
generally you will define the position in 3d space that your audio listener and panner (source) occupy initially, and then update the position of one or both of these as the application is used.
... to see a complete implementation, check out our panner-node example (view the source code) — this demo transports you to the 2.5d "room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes!
PannerNode - Web APIs
generally you will define the position in 3d space that your audio listener and panner (source) occupy initially, and then update the position of one or both of these as the application is used.
... to see a complete implementation, check out our panner-node example (view the source code) — this demo transports you to the 2.5d "room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes!
ParentNode.replaceChildren() - Web APIs
if no replacement objects are specified, then the parentnode is emptied of all child nodes.
...it then calls replacechildren() on the list to transfer the options to, using the spread operator to pass in all the options contained in both constants.
PasswordCredential - Web APIs
<form id="form" method="post"> <input type="text" name="id" autocomplete="username" /> <input type="password" name="password" autocomplete="current-password" /> <input type="hidden" name="csrf_token" value="*****" /> </form> then, a reference to this form element, using it to create a passwordcredential object, and storing it in the browser's password system.
...navigator.credentials.store(creds) .then(function(creds) { // do something with the credentials if you need to.
PasswordCredential.additionalData - Web APIs
it then stores the form object in the additionaldata parameter, before sending it to server in a call to fetch.
...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 status comment credential management level 1 working draft initial definition.
PasswordCredential - Web APIs
the url must be accessible without authentication.
... examples var cred = new passwordcredential({ id: id, password: password, name: name, iconurl: iconurl }); navigator.credentials.store(cred) .then(function() { // do something else.
Path2D.addPath() - Web APIs
WebAPIPath2DaddPath
we then create a matrix using document.createelementns() and createsvgmatrix().
... we then add the second path to the first using addpath(), also applying the matrix to move the second path to the right.
PaymentMethodChangeEvent.methodDetails - Web APIs
the contents vary depending on the actual payment method chosen, so you will need to refer to the methodname property first, then inerpret the methoddetails after that.
... ev.updatewith(newstuff); }; const response = await request.show(); note that the methoddetails property is being used by the calculatediscount() function to compute any payment discount, then updatewith() is called to update the event with the computed update.
PaymentRequest: paymentmethodchange event - Web APIs
this code creates a new paymentrequest, adds a handler for the paymentmethodchange event by calling the request's addeventlistener(), then calls show() to present the payment interface to the user.
... const options = { requestshipping: true }; const paymentrequest = new paymentrequest(paymentmethods, detailsforshipping("ground"), options); paymentrequest.addeventlistener("paymentmethodchange", handlepaymentchange, false); paymentrequest.show() .then(response => response.complete("success")) .catch(err => console.log("error handling payment request: " + err)); the event handler function itself, handlepaymentchange(), looks like this: handlepaymentchange = event => { const detailsupdate = {}; if (event.methodname === "https://apple.com/apple-pay") { const servicefeeinfo = calculateservicefee(event.methoddetails); object.assign(...
PaymentResponse.details - Web APIs
in a real-world implementation this data would then be sent to a payment server.
... payment.show().then(paymentresponse => { var paymentdata = { // payment method string method: paymentresponse.methodname, // payment details as you requested details: paymentresponse.details, // shipping address information address: todict(paymentresponse.shippingaddress) }; // send information to the server }); specifications specification status comment payment request api candidate recommendation initial definition.
PaymentResponse.methodName - Web APIs
in a real-world implementation this data would then be sent to a payment server.
... payment.show().then(paymentresponse => { var paymentdata = { // payment method string method: paymentresponse.methodname, // payment details as you requested details: paymentresponse.details, // shipping address information address: todict(paymentresponse.shippingaddress) }; // send information to the server }); specifications specification status comment payment request api candidate recommendation initial definition.
PaymentResponse.retry() - Web APIs
typically you will use this by calling show(), then entering a loop or recursive function that checks the paymentresponse for errors or other reasons to retry the payment request.
... if a retry is needed, the loop calls retry(), then loops back to check the response when it comes in.
Payment processing concepts - Web APIs
the payer authenticates themselves, then authorizes payment, as required by the payment method.
... by then delivering this data (or a promise which resolves to the loaded data) to the payment handler by passing it into complete(), the payment handler can use the retrieved data and whatever algorithm and other data to support in order to verify that the merchant can use the payment handler.
Payment Request API - Web APIs
it aims to make the checkout process easier, by remembering a user's details, which are then passed along to a merchant hopefully without requiring a html form.
... advantages of using the payment request api with "basic-card" (card-based payments): fast purchase experience: users enter their details once into the browser and are then ready to pay for goods and services on the web.
performance.measure() - Web APIs
if it is omitted, then the start time will be the navigation start time.
...if it is omitted, then the current time is used.
Permissions.query() - Web APIs
WebAPIPermissionsquery
syntax navigator.permissions.query(permissiondescriptor).then(function(permissionstatus) { ...
... 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
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; input.max = photocapabilities.imagewidth.max; ...
...input.step = photocapabilities.imagewidth.step; return imagecapture.getphotosettings(); }) .then(photosettings => { input.value = photosettings.imagewidth; }) .catch(error => console.log('argh!', error.name || error)); specifications specification status comment mediastream image capturethe definition of 'photocapabilities' in that specification.
Pinch zoom gestures - Web APIs
function pointerup_handler(ev) { log(ev.type, ev); // remove this pointer from the cache and reset the target's // background and border remove_event(ev); ev.target.style.background = "white"; ev.target.style.border = "1px solid black"; // if the number of pointers down is less than two then reset diff tracker if (evcache.length < 2) { prevdiff = -1; } } application ui the application uses a <div> element for the touch area and provides buttons to enable logging and to clear the log.
... <body onload="init();" style="touch-action:none"> <div id="target">touch and hold with 2 pointers, then pinch in or out.<br/> the background color will change to pink if the pinch is opening (zoom in) or changes to lightblue if the pinch is closing (zoom out).</div> <!-- ui for logging/debugging --> <button id="log" onclick="enablelog(event);">start/stop event logging</button> <button id="clearlog" onclick="clearlog(event);">clear the log</button> <p></p> <output></output> </body> miscellaneous functions these functions support the application but aren't directly involved in the event flow.
PublicKeyCredential.rawId - Web APIs
this identifier is expected to be globally unique and is appointed for the current publickeycredential and its associated authenticatorassertionresponse.
... 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 specification.
PublicKeyCredentialCreationOptions.pubKeyCredParams - Web APIs
examples var publickey = { pubkeycredparams: [ // we would like an elliptic curve to be used if possible { type: "public-key", alg: -7 }, // 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.credenti...
...als.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 credentials level 1the definition of 'pubkeycredparams' in that specification.
PushSubscription.unsubscribe() - Web APIs
syntax ​pushsubscription.unsubscribe().then(function(boolean) { ...
... 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
methods pushsubscription.getkey() returns an arraybuffer which contains the client's public key, which can then be sent to a server and used in encrypting push message data.
... 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 that specification.
RTCDtlsTransport - Web APIs
for this reason, you'll sometimes see separate transports created at first, one for each track, then see them get bundled up once it's known that bundling is possible.
... if your code accesses rtcrtpsenders and/or rtcrtpreceivers directly, you may encounter situations where they're initially separate, then half or more of them get closed and the senders and receivers updated to refer to the appropriate remaining rtcdtlstransport objects.
RTCIceCandidatePairStats.selected - Web APIs
if that fails, then the second section iterates over the reports, looking for a candidate-pair record whose firefox-specific selected property is true.
... this candidate pair is then returned as the currently-selected one.
RTCIceCandidateStats.address - Web APIs
otherwise, the address is presumed to be a fully-qualified domain name, which is resolved first using an aaaa record (assuming ipv6 is available), then using an a record (if no result is found or the device onlu supports ipv4).
... if multiple ip addresses are returned in response to the query, the user agent selects one, which is then used for the duration of ice processing.
RTCIceServer.credentialType - Web APIs
}; var credentialtype = iceserver.credentialtype; iceserver.credentialtype = newcredentialtype; value the permitted values are found in the rtcicecredentialtype enumerated string type: oauth the rtciceserver requires the use of oauth 2.0 to authenticate in order to use the ice server described.
... password the rtciceserver requires a username and password to authenticate prior to using the described ice server.
RTCIceServers.urls - Web APIs
WebAPIRTCIceServerurls
mypeerconnection = new rtcpeerconnection({ iceservers: [ { urls: "stun:stunserver.example.org" } ] }); notice that only the urls property is provided; the stun server doesn't require authentication, so this is all that's needed.
... a single ice server with authentication the second example creates a new rtcpeerconnection which will use a turn server at turnserver.example.org to negotiate connections.
RTCIceServer - Web APIs
username optional if the rtciceserver is a turn server, then this is the username to use during the authentication process.
...the first one, stun:stun.services.mozilla.com, requires authentication, so the username and password are provided.
RTCIdentityErrorEvent.loginUrl - Web APIs
the read-only property rtcidentityerrorevent.loginurl is a domstring giving the url where the user can complete the authentication.
... syntax var loginurl = event.loginurl; event.loginurl = "https://developer.mozilla.org/fakeurl"; example pc.onidpassertionerror = function( ev ) { alert("the idp requested an authentication" + " to be performed at th3 url '" + ev.url + "'."); } ...
RTCOfferOptions.iceRestart - Web APIs
pc.oniceconnectionstatechange = function(evt) { if (pc.iceconnectionstate === "failed") { if (pc.restartice) { pc.restartice(); } else { pc.createoffer({ icerestart: true }) .then(pc.setlocaldescription) .then(sendoffertoserver); } } } if the state changes to failed, this handler starts by looking to see if the rtcpeerconnection includes the restartice() method; if it does, we call that to request an ice restart.
... otherwise, we call back to the older technique: we manually create a new offer with icerestart set to true, then that offer is set as the new local description for the connection.
RTCPeerConnection() - Web APIs
certificates optional an array of objects of type rtccertificate which are used by the connection for authentication.
...if this value is set (it defaults to null), the rtcpeerconnection will not connect to a remote peer unless it can successfully authenticate with the given name.
RTCPeerConnection.canTrickleIceCandidates - Web APIs
if trickling isn't supported, or you aren't able to tell, you can check for a falsy value for this property and then wait until the value of icegatheringstate changes to "completed" before creating and sending the initial offer.
...pc.setremotedescription(remoteoffer) .then(_ => pc.createanswer()) .then(answer => pc.setlocaldescription(answer)) .then(_ => if (pc.cantrickleicecandidates) { return pc.localdescription; } return new promise(r => { pc.addeventlistener('icegatheringstatechange', e => { if (e.target.icegatheringstate === 'complete') { r(pc.localdescription); } }); }); }) .then(answer => se...
RTCPeerConnection.createAnswer() - Web APIs
the answer is delivered to the returned promise, and should then be sent to the source of the offer to continue the negotiation process.
...the contents of the object being passed to the sendtoserver() function, along with everything else in the promise fulfillment handler, depend entirely on your design pc.createanswer().then(function(answer) { return pc.setlocaldescription(answer); }) .then(function() { // send the answer to the remote peer through the signaling server.
RTCPeerConnection.createOffer() - Web APIs
if you then apply the returned offer, ice will restart.
... mypeerconnection.createoffer().then(function(offer) { return mypeerconnection.setlocaldescription(offer); }) .then(function() { sendtoserver({ name: myusername, target: targetusername, type: "video-offer", sdp: mypeerconnection.localdescription }); }) .catch(function(reason) { // an error occurred, so handle the failure to connect }); in this code, the offer is created, and once su...
RTCPeerConnection.generateCertificate() - Web APIs
the generatecertificate() method of the rtcpeerconnection interface creates and stores an x.509 certificate and corresponding private key then returns an rtccertificate, providing access to it.
... example rtcpeerconnection.generatecertificate({ name: 'rsassa-pkcs1-v1_5', hash: 'sha-256', moduluslength: 2048, publicexponent: new uint8array([1, 0, 1]) }).then(function(cert) { var pc = new rtcpeerconnection({certificates: [cert]}); }); specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'generatecertificate()' in that specification.
RTCPeerConnection.getStats() - Web APIs
window.setinterval(function() { mypeerconnection.getstats(null).then(stats => { let statsoutput = ""; stats.foreach(report => { statsoutput += `<h2>report: ${report.type}</h3>\n<strong>id:</strong> ${report.id}<br>\n` + `<strong>timestamp:</strong> ${report.timestamp}<br>\n`; // now the statistics for this report; we intentially drop the ones we // sorted to the top above object.keys(report).foreach(statname ...
...=> { if (statname !== "id" && statname !== "timestamp" && statname !== "type") { statsoutput += `<strong>${statname}:</strong> ${report[statname]}<br>\n`; } }); }); document.queryselector(".stats-box").innerhtml = statsoutput; }); }, 1000); this works by calling getstats(), then, when the promise is resolved, iterates over the rtcstats objects on the returned rtcstatsreport.
RTCPeerConnection.onnegotiationneeded - Web APIs
if the session is modified in a manner that requires negotiation while a negotiation is already in progress, no negotiationneeded event will fire until negotiation completes, and only then if negotiation is still needed.
... pc.onnegotiationneeded = function() { pc.createoffer().then(function(offer) { return pc.setlocaldescription(offer); }) .then(function() { // send the offer to the remote peer through the signaling server }); }) .catch(reporterror); } first, it creates the offer by calling createoffer().
RTCPeerConnection.peerIdentity - Web APIs
if there isn't already a target peer identity, peeridentity is set to a newly created promise and the process begins again, until the process succeeds or no further attempts to authenticate occur.
... example in this example, a function, getidentityassertion(), is created which asynchronously waits for the peer's identity to be verified, then returns the identity to the caller.
Range.setStart() - Web APIs
WebAPIRangesetStart
if the startnode is a node of type text, comment, or cdatasection, then startoffset is the number of characters from the start of startnode.
...the selected range is then highlighted using range.surroundcontents().
ReadableStream.getReader() - Web APIs
function fetchstream() { const reader = stream.getreader(); let charsreceived = 0; // read() returns a promise that resolves // when a value has been received reader.read().then(function processtext({ done, value }) { // result objects contain two properties: // done - true if the stream has already given you all its data.
...current chunk = ' + chunk; list2.appendchild(listitem); result += chunk; // read some more, and call this function again return reader.read().then(processtext); }); } specifications specification status comment streamsthe definition of 'getreader()' in that specification.
ReadableStream.pipeTo() - Web APIs
signal: if set to an abortsignal object, ongoing pipe operations can then be aborted via the corresponding abortcontroller.
... examples // fetch the original image fetch('png-logo.png') // retrieve its body as readablestream .then(response => response.body) .then(body => body.pipethrough(new pngtransformstream())) .then(rs => rs.pipeto(new finaldestinationstream())) specifications specification status comment streamsthe definition of 'pipeto()' in that specification.
ReadableStreamDefaultReader.ReadableStreamDefaultReader() - Web APIs
function fetchstream() { const reader = stream.getreader(); let charsreceived = 0; // read() returns a promise that resolves // when a value has been received reader.read().then(function processtext({ done, value }) { // result objects contain two properties: // done - true if the stream has already given you all its data.
...current chunk = ' + chunk; list2.appendchild(listitem); result += chunk; // read some more, and call this function again return reader.read().then(processtext); }); } specifications specification status comment streamsthe definition of 'readablestreamdefaultreader()' in that specification.
ReadableStreamDefaultReader.cancel() - Web APIs
function fetchstream() { const reader = stream.getreader(); let charsreceived = 0; // read() returns a promise that resolves // when a value has been received reader.read().then(function processtext({ done, value }) { // result objects contain two properties: // done - true if the stream has already given you all its data.
...current chunk = ' + chunk; list2.appendchild(listitem); result += chunk; // read some more, and call this function again return reader.read().then(processtext); }); } specifications specification status comment streamsthe definition of 'cancel()' in that specification.
ReadableStreamDefaultReader.read() - Web APIs
function fetchstream() { const reader = stream.getreader(); let charsreceived = 0; // read() returns a promise that resolves // when a value has been received reader.read().then(function processtext({ done, value }) { // result objects contain two properties: // done - true if the stream has already given you all its data.
...current chunk = ' + chunk; list2.appendchild(listitem); result += chunk; // read some more, and call this function again return reader.read().then(processtext); }); } example 2 - handling text line by line this example shows how you might fetch a text file and handle it as a stream of text lines.
Response.clone() - Web APIs
WebAPIResponseclone
we then fetch this request using fetch().
... var image1 = document.queryselector('.img1'); var image2 = document.queryselector('.img2'); var myrequest = new request('flowers.jpg'); fetch(myrequest).then(function(response) { var response2 = response.clone(); response.blob().then(function(myblob) { var objecturl = url.createobjecturl(myblob); image1.src = objecturl; }); response2.blob().then(function(myblob) { var objecturl = url.createobjecturl(myblob); image2.src = objecturl; }); }); specifications specification status comment fetchthe definition of 'clone()' ...
Response.headers - Web APIs
WebAPIResponseheaders
we then fetch this request using fetch(), extract a blob from the response using body.blob, create an object url out of it using url.createobjecturl, and display this in an <img>.
... var myimage = document.queryselector('img'); var myrequest = new request('flowers.jpg'); fetch(myrequest).then(function(response) { console.log(response.headers); // returns a headers{} object response.blob().then(function(myblob) { var objecturl = url.createobjecturl(myblob); myimage.src = objecturl; }); }); specifications specification status comment fetchthe definition of 'headers' in that specification.
Response.ok - Web APIs
WebAPIResponseok
we then fetch this request using fetch(), extract a blob from the response using body.blob, create an object url out of it using url.createobjecturl, and display this in an <img>.
... var myimage = document.queryselector('img'); var myrequest = new request('flowers.jpg'); fetch(myrequest).then(function(response) { console.log(response.ok); // returns true if the response returned successfully response.blob().then(function(myblob) { var objecturl = url.createobjecturl(myblob); myimage.src = objecturl; }); }); specifications specification status comment fetchthe definition of 'ok' in that specification.
Response.redirected - Web APIs
fetch("awesome-picture.jpg").then(function(response) { let elem = document.getelementbyid("warning-message-box"); if (response.redirected) { elem.innerhtml = "unexpected redirect"; } else { elem.innerhtml = ""; } return response.blob(); }).then(function(imageblob) { let imgobjecturl = url.createobjecturl(imageblob); document.getelementbyid("img-element-id").src = imgobjecturl; }); disallowing redirects be...
...cause using redirected to manually filter out redirects can allow forgery of redirects, you should instead set the redirect mode to "error" in the init parameter when calling fetch(), like this: fetch("awesome-picture.jpg", { redirect: "error" }).then(function(response) { return response.blob(); }).then(function(imageblob) { let imgobjecturl = url.createobjecturl(imageblob); document.getelementbyid("img-element-id").src = imgobjecturl; }); specifications specification status comment fetchthe definition of 'redirected' in that specification.
Response.status - Web APIs
WebAPIResponsestatus
we then fetch this request using fetch(), extract a blob from the response using body.blob, create an object url out of it using url.createobjecturl, and display this in an <img>.
... var myimage = document.queryselector('img'); var myrequest = new request('flowers.jpg'); fetch(myrequest).then(function(response) { console.log(response.status); // returns 200 response.blob().then(function(myblob) { var objecturl = url.createobjecturl(myblob); myimage.src = objecturl; }); }); specifications specification status comment fetchthe definition of 'status' in that specification.
Response.statusText - Web APIs
we then fetch this request using fetch(), extract a blob from the response using body.blob, create an object url out of it using url.createobjecturl, and display this in an <img>.
... var myimage = document.queryselector('img'); var myrequest = new request('flowers.jpg'); fetch(myrequest).then(function(response) { console.log(response.statustext); // returns "ok" if the response returned successfully response.blob().then(function(myblob) { var objecturl = url.createobjecturl(myblob); myimage.src = objecturl; }); }); specifications specification status comment fetchthe definition of 'statustext' in that specification.
Response.type - Web APIs
WebAPIResponsetype
we then fetch this request using fetch(), extract a blob from the response using body.blob, create an object url out of it using url.createobjecturl, and display this in an <img>.
... var myimage = document.queryselector('img'); var myrequest = new request('flowers.jpg'); fetch(myrequest).then(function(response) { console.log(response.type); // returns basic by default response.blob().then(function(myblob) { var objecturl = url.createobjecturl(myblob); myimage.src = objecturl; }); }); specifications specification status comment fetchthe definition of 'type' in that specification.
Response.url - Web APIs
WebAPIResponseurl
we then fetch this request using fetch(), extract a blob from the response using body.blob, create an object url out of it using url.createobjecturl, and display this in an <img>.
... var myimage = document.queryselector('img'); var myrequest = new request('flowers.jpg'); fetch(myrequest).then(function(response) { console.log(response.url); // returns /docs/web/api/response/flowers.jpg response.blob().then(function(myblob) { var objecturl = url.createobjecturl(myblob); myimage.src = objecturl; }); }); specifications specification status comment fetchthe definition of 'url' in that specification.
SVGAnimationElement - Web APIs
if there is no current interval, then a domexception with code invalid_state_err is thrown.
...if the simple duration is undefined (e.g., the end time is indefinite), then a domexception with code not_supported_err is raised.
SVGGraphicsElement: paste event - Web APIs
bubbles yes cancelable yes interface clipboardevent event handler property onpaste if the cursor is in an editable context (for example, in a <textarea> or an element with contenteditable attribute set to true) then the default action is to insert the contents of the clipboard into the document at the cursor position.
... to override the default behavior (for example to insert some different data or a transformation of the clipboard contents) an event handler must cancel the default action using event.preventdefault(), and then insert its desired data manually.
SVGLengthList - Web APIs
if the index is equal to 0, then the new item is inserted at the front of the list.
... if the index is greater than or equal to numberofitems, then the new item is appended to the end of the list.
SVGNumberList - Web APIs
if the index is equal to 0, then the new item is inserted at the front of the list.
... if the index is greater than or equal to numberofitems, then the new item is appended to the end of the list.
SVGPathSegList - Web APIs
if the index is equal to 0, then the new item is inserted at the front of the list.
... if the index is greater than or equal to numberofitems, then the new item is appended to the end of the list.
SVGPointList - Web APIs
if the index is equal to 0, then the new item is inserted at the front of the list.
... if the index is greater than or equal to numberofitems, then the new item is appended to the end of the list.
SVGStringList - Web APIs
if the index is equal to 0, then the new item is inserted at the front of the list.
... if the index is greater than or equal to numberofitems, then the new item is appended to the end of the list.
SVGTransformList - Web APIs
if the index is equal to 0, then the new item is inserted at the front of the list.
... if the index is greater than or equal to numberofitems, then the new item is appended to the end of the list.
SVGUseElement - Web APIs
if the element does not have a shadow tree (for example, because its uri is invalid or because it has been disabled by conditional processing), then getting this attribute returns null.
...if the element does not have a shadow tree (for example, because its uri is invalid or because it has been disabled by conditional processing), then getting this attribute returns null.
Selection.modify() - Web APIs
WebAPISelectionmodify
click somewhere inside the example (optionally selecting some text), and then click the button to expand the selection.
...then click the button below to expand the selection.
ServiceWorkerContainer.getRegistration() - Web APIs
syntax serviceworkercontainer.getregistration(scope).then(function(serviceworkerregistration) { ...
... 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
syntax serviceworkercontainer.getregistrations().then(function(serviceworkerregistrations) { ...
... 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.ready - Web APIs
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.
ServiceWorkerContainer - Web APIs
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.
ServiceWorkerGlobalScope: message event - Web APIs
bubbles no cancelable no interface extendablemessageevent event handler property onmessage examples in the below example a page gets a handle to the serviceworker object via serviceworkerregistration.active, and then calls its postmessage() function.
... // 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 worker can receive the message by listening to the message event: // in the service worker addeventlistener('message', event => { // event is an extendablemessageevent object console.log(`the client sent me a message: ${event.data}`); event.source.postmessage("hi client"); }); specifications specification status service workersth...
ServiceWorkerGlobalScope: notificationclick event - Web APIs
cationclick examples you can use the notificationclick event in an addeventlistener method: self.addeventlistener('notificationclick', function(event) { console.log('on notification click: ', event.notification.tag); event.notification.close(); // this looks to see if the current is already open and // focuses if it is event.waituntil(clients.matchall({ type: "window" }).then(function(clientlist) { for (var i = 0; i < clientlist.length; i++) { var client = clientlist[i]; if (client.url == '/' && 'focus' in client) return client.focus(); } if (clients.openwindow) return clients.openwindow('/'); })); }); or use the onnotificationclick event handler property: self.onnotificationclick = function(event) { console.log('on notific...
...ation click: ', event.notification.tag); event.notification.close(); // this looks to see if the current is already open and // focuses if it is event.waituntil(clients.matchall({ type: "window" }).then(function(clientlist) { for (var i = 0; i < clientlist.length; i++) { var client = clientlist[i]; if (client.url == '/' && 'focus' in client) return client.focus(); } if (clients.openwindow) return clients.openwindow('/'); })); }; specifications specification status notifications apithe definition of 'onnotificationclick' in that specification.
ServiceWorkerGlobalScope.onfetch - Web APIs
self.addeventlistener('fetch', function(event) { console.log('handling fetch event for', event.request.url); event.respondwith( caches.match(event.request).then(function(response) { if (response) { console.log('found response in cache:', response); return response; } console.log('no response found in cache.
... about to fetch from network...'); return fetch(event.request).then(function(response) { console.log('response from network is:', response); return response; }).catch(function(error) { console.error('fetching failed:', error); throw error; }); }) ); }); specifications specification status comment service workersthe definition of 'event handlers' in that specification.
ServiceWorkerGlobalScope: pushsubscriptionchange event - Web APIs
self.addeventlistener("pushsubscriptionchange", event => { event.waituntil(swregistration.pushmanager.subscribe(event.oldsubscription.options) .then(subscription => { return fetch("register", { method: "post", headers: { "content-type": "application/json" }, body: json.stringify({ endpoint: subscription.endpoint }) }); }) ); }, false); when a pushsubscriptionchange event arrives, indicating that the subscription has expired, we resubscribe by calling the push manag...
... you can also use the onpushsubscriptionchange event handler property to set up the event handler: self.onpushsubscriptionchange = event => { event.waituntil(swregistration.pushmanager.subscribe(event.oldsubscription.options) .then(subscription => { /* ...
ServiceWorkerGlobalScope - Web APIs
self.addeventlistener('fetch', function(event) { console.log('handling fetch event for', event.request.url); event.respondwith( caches.match(event.request).then(function(response) { if (response) { console.log('found response in cache:', response); return response; } console.log('no response found in cache.
... about to fetch from network...'); return fetch(event.request).then(function(response) { console.log('response from network is:', response); return response; }, function(error) { console.error('fetching failed:', error); throw error; }); }) ); }); specifications specification status comment service workersthe definition of 'serviceworkerglobalscope' in that specification.
ServiceWorkerRegistration.getNotifications() - Web APIs
syntax s​erviceworkerregistration.getnotifications(options) .then(function(notificationslist) { ...
... 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.getnotifications()' in that specification.
ServiceWorkerRegistration.showNotification() - Web APIs
for example, [300, 100, 400] would vibrate 300ms, pause 100ms, then vibrate 400ms.
... 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
syntax serviceworkerregistration.unregister().then(function(boolean) { }); parameters none.
... 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 ' + error); }); }; specifications specification status comment service workersthe definition of 'serviceworkerregistration...
ServiceWorkerRegistration - Web APIs
if the service worker hasn't changed since the last time it was registered, then the updatefound event will not be fired.
... 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.
Service Worker API - Web APIs
note: service workers win over previous attempts in this area such as; appcache because they don't make assumptions about what you are trying to do, and then break when those assumptions are not exactly right; you have granular control over everything.
... if this is the first time a service worker has been made available, installation is attempted, then after a successful installation, it is activated.
SharedWorker - Web APIs
both scripts contain this: var myworker = new sharedworker('worker.js'); both scripts then access the worker through a messageport object created using the sharedworker.port property.
...the ports associated with that worker are accessible in the connect event's ports property — we then use messageport start() method to start the port, and the onmessage handler to deal with messages sent from the main threads.
Slottable: assignedSlot - Web APIs
examples in our simple-template example (see it live), we create a trivial custom element example called <my-paragraph> in which a shadow root is attached and then populated using the contents of a template that contains a slot named my-text.
...here is one such example: <my-paragraph> <span slot="my-text">let's have some different text!</span> </my-paragraph> in our javascript file we get a reference to the <span> shown above, then log a reference to the original <slot> element the <span> was inserted in.
SourceBuffer.abort() - Web APIs
saying that, current implementations can be useful in certain situations, when you want to stop the current append (or whatever) operation occuring on a sourcebuffer, and then immediately start performing operations on it again.
... in this case you would want to manually call abort() on the source buffer to stop the decoding of the current buffer, then fetch and append the newly requested segment that relates to the current new position of the video.
SpeechRecognitionResult.isFinal - Web APIs
the isfinal read-only property of the speechrecognitionresult interface is a boolean that states whether this result is final (true) or not (false) — if so, then this is the final time this result will be returned; if not, then this result is an interim result, and may be updated later on.
... // we then return the transcript property of the speechrecognitionalternative object var color = event.results[0][0].transcript; diagnostic.textcontent = 'result received: ' + color + '.'; bg.style.backgroundcolor = color; console.log(event.results[0].isfinal); } specifications specification status comment web speech apithe definition of 'isfinal' in that specification.
SpeechRecognitionResult - Web APIs
properties speechrecognitionresult.isfinal read only a boolean that states whether this result is final (true) or not (false) — if so, then this is the final time this result will be returned; if not, then this result is an interim result, and may be updated later on.
... // we then return the transcript property of the speechrecognitionalternative object var color = event.results[0][0].transcript; diagnostic.textcontent = 'result received: ' + color + '.'; bg.style.backgroundcolor = color; } specifications specification status comment web speech apithe definition of 'speechrecognitionresult' in that specification.
StorageManager.persist() - Web APIs
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
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.
SubmitEvent() - Web APIs
examples this code snippet locates a form in the current document, and then an html <button> within the form with the class submit on it.
...then the event is sent to the form, telling the form that it's been submitted by the button.
SubtleCrypto.unwrapKey() - Web APIs
this means that it takes as its input a key that has been exported and then encrypted (also called "wrapped").
... it decrypts the key and then imports it, returning a cryptokey object that can be used in the web crypto api.
TextTrack - Web APIs
WebAPITextTrack
if it doesn't have an id, then this value is an empty string ("").
... if the texttrack is associated with a <track> element, then the track's id matches the element's id.
Touch events - Web APIs
then we get the context and pull the list of changed touch points out of the event's touchevent.changedtouches property.
... function copytouch({ identifier, pagex, pagey }) { return { identifier, pagex, pagey }; } finding an ongoing touch the ongoingtouchindexbyid() function below scans through the ongoingtouches array to find the touch matching the given identifier then returns that touch's index into the array.
URL API - Web APIs
WebAPIURL API
let addr = new url("/docs/web/api/url_api"); let host = addr.host; let path = addr.pathname; the snippet above creates a url object for the article you're reading right now, then fetches the host and pathname properties.
...for example, if the url is https://mysite.com/login?user=someguy&page=news, then the value of the search property is ?user=someguy&page=news.
Vibration API - Web APIs
each value in the array is converted to an integer, then interpreted alternately as the number of milliseconds the device should vibrate and the number of milliseconds it should not be vibrating.
... 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.
VideoPlaybackQuality.droppedVideoFrames - Web APIs
example this example calls getvideoplaybackquality() to obtain a videoplaybackquality object, then determines what percentage of frames have been dropped.
... that value is then presented in an element for the user's reference.
WebGLRenderingContext.enableVertexAttribArray() - Web APIs
then the vertex position attribute's index is obtained from the shader program by calling getattriblocation().
... then the vertex buffer is bound to the avertexposition attribute by calling vertexattribpointer().
WebGLRenderingContext.getUniformLocation() - Web APIs
example in this example, taken from the animatescene() method in the article a basic 2d webgl animation example, obtains the locations of three uniforms from the shading program, then sets the value of each of the three uniforms.
... then the three uniforms' values are set: the uscalingfactor uniform — a 2-component vertex — receives the horizontal and vertical scaling factors from the variable currentscale.
WebGLRenderingContext.isContextLost() - Web APIs
examples include: two or more pages are using the gpu, but together place too high a demand on the gpu, so the browser tells the two contexts that they've lost the connection, then selects one of the two to restore access for.
...in this case, all contexts are lost, then restored after switching gpus.
WebGLRenderingContext.makeXRCompatible() - Web APIs
this is useful if you have an application which can start out being presented on a standard 2d display but can then be transitioned to a 3d immersion system.
... then the startgame() function is called to trigger the beginning of gameplay.
Animating objects with WebGL - Web APIs
we can do that by creating a new variable to track the time at which we last animated (let's call it then), then adding the following code to the end of the main function var then = 0; // draw the scene repeatedly function render(now) { now *= 0.001; // convert to seconds const deltatime = now - then; then = now; drawscene(gl, programinfo, buffers, deltatime); requestanimationframe(render); } requestanimationframe(render); this code uses requestanimationframe to a...
...we convert that to seconds and then subtract from it the last time to compute deltatime which is the number of second since the last frame was rendered.
Creating 3D objects using WebGL - Web APIs
we can pass a lot fewer data around by building an array of all 24 vertices, then referring to each vertex by its index into that array instead of moving entire sets of coordinates around.
...this code starts by defining a color for each face, then uses a loop to assemble an array of all the colors for each of the vertices.
Introduction to the Real-time Transport Protocol (RTP) - Web APIs
note: webrtc actually uses srtp (secure real-time transport protocol) to ensure that the exchanged data is secure and authenticated as appropriate.
... the sdp answer is generated and sent using a method called sendanswer(), which generates the answer using createanswer() then sends the resulting sdp to the other peer over the signaling service.
Introduction to WebRTC protocols - Web APIs
you would create a connection with a turn server and tell all peers to send packets to the server which will then be forwarded to you.
... technically, then, sdp is not truly a protocol, but a data format used to describe connection that shares media between devices.
WebRTC API - Web APIs
identity and security these apis are used to manage user identity and security, in order to authenticate the user for a connection.
... rtccertificate represents a certificate that an rtcpeerconnection uses to authenticate.
WebRTC Statistics API - Web APIs
in this example, a new rtcpeerconnection is created, and then setinterval() is used to set the function getconnectionstats() to be called every second.
... try { mypeerconnection = new rtcpeerconnection(pcoptions); statsinterval = window.setinterval(getconnectionstats, 1000); /* add event handlers, etc */ } catch(err) { console.error("error creating rtcpeerconnection: " + err); } function getconnectionstats() { mypeerconnection.getstats(null).then(stats => { var statsoutput = ""; stats.foreach(report => { if (report.type === "inbound-rtp" && report.kind === "video") { object.keys(report).foreach(statname => { statsoutput += `<strong>${statname}:</strong> ${report[statname]}<br>\n`; }); } }); document.queryselector(".stats-box").innerhtml = statsoutput; }); } when the promise return...
Fundamentals of WebXR - Web APIs
there are two basic types of ar device: devices which use cameras to capture the world in front of the user, render the webxr content atop that image, then display the image on a screen.
... these devices include phones, which show the resulting scene on the device's screen in a 2d presentation, as well as goggles that use a pair of cameras, one for each eye, to capture the scene in stereo in order to retain the world's depth, with the webxr scene then rendered for each eye with that eye's captured background in place.
Geometry and reference spaces in WebXR - Web APIs
the reference space's configuration is then able to provide you with the view matrices and object poses needed to correctly render the contents of the space.
...create an xrrigidtransform object representing the new position and orientation of the player's avatar, then create a new reference space to represent the avatar's point of view at the new position using the xrreferencespace method getoffsetreferencespace().
WebXR performance guide - Web APIs
it makes sense, then, to have a limited set of these objects, simply replacing their contents with the new information each time you need to use them.
...that means that for every frame, the javascript runtime has to allocate memory for those and set them up—possibly triggering garbage collection—and then when each interaction of the loop is completed, the memory is released.
WebXR Device API - Web APIs
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.
... rendering and the webxr frame animation callback starting with how you schedule frames to be rendered, this guide then continues to cover how to determine the placement of objects in the view and how to then render them into the webgl buffer used for each of the two eyes' views of the scene.
Using the Web Animations API - Web APIs
in the @keyframes block we can see that 30% of the way through each loop (about .9 seconds in), alice’s color changes from black to a deep burgundy then back again by the end of the loop.
...then we pause her: alicechange.pause(); if we had left her paused at the beginning of her animation, she’d start at half her full size, as if she’d drunk the entire bottle already!
Using IIR filters - Web APIs
for instance, if you want to filter lower frequencies from your sound, you can set the type to highpass and then set which frequency to filter from (or cut off).
...first, the html: <button class="button-filter" role="switch" data-filteron="false" aria-pressed="false" aria-describedby="label" disabled></button> the filter button's click handler then connects the iirfilter up to the graph, between the source and the detination: filterbutton.addeventlistener('click', function() { if (this.dataset.filteron === 'false') { srcnode.disconnect(audioctx.destination); srcnode.connect(iirfilter).connect(audioctx.destination); ...
Web Locks API - Web APIs
the web locks api allows scripts running in one tab or worker to asynchronously acquire a lock, hold it while work is performed, then release it.
...if tab 1 holds lock a and tab 2 holds lock b, then tab 1 attempts to also acquire lock b and tab 2 attempts to also acquire lock a, neither request can be granted.
Using the Web Storage API - Web APIs
we have also provided an event output page — if you load this page in another tab, then make changes to your choices in the landing page, you'll see the updated storage information outputted as a storageevent is fired.
...it then runs the setstyles() function to update the page styles, etc.
Web Storage API - Web APIs
when you choose different options, the page is instantly updated; in addition your choices are stored in localstorage, so that when you leave the page then load it again later on your choices are remembered.
... in addition, we have provided an event output page — if you load this page in another tab, then make changes to your choices in the landing page, you'll see the updated storage information outputted as the storageevent is fired.
Window.devicePixelRatio - Web APIs
the updatepixelratio() function fetches the current value of devicepixelratio, then sets the innertext of the element pixelratiobox to a string which displays the ratio both as a percentage and as a raw decimal value with up to two decimal places.
... then the updatepixelratio() function is called once to display the starting value, after which the media query is created using matchmedia() and addeventlistener() is called to set up updatepixelratio() as a handler for the change event.
window.dump() - Web APIs
WebAPIWindowdump
if the -console option was not specified then the output goes to stderr.
...then run console redirector.exe /?
Window.event - Web APIs
WebAPIWindowevent
or androidopera for androidsafari on iossamsung interneteventchrome full support 1edge full support 12firefox full support 63notes disabled full support 63notes disabled notes this was briefly enabled by default in 65, then removed again while related compatibility issues are sorted out (see bug 1520756).disabled from version 63: this feature is behind the dom.window.event.enabled preference (needs to be set to true).
...t 1.1webview android full support 1chrome android full support 18firefox android full support 63notes disabled full support 63notes disabled notes this was briefly enabled by default in 65, then removed again while related compatibility issues are sorted out (see bug 1520756).disabled from version 63: this feature is behind the dom.window.event.enabled preference (needs to be set to true).
Window.matchMedia() - Web APIs
WebAPIWindowmatchMedia
the window interface's matchmedia() method returns a new mediaquerylist object that can then be used to determine if the document matches the media query string, as well as to monitor the document to detect when it matches (or stops matching) that media query.
... javascript let mql = window.matchmedia('(max-width: 600px)'); document.queryselector(".mq-value").innertext = mql.matches; the javascript code simply passes the media query to match into matchmedia() to compile it, then sets the <span>'s innertext to the value of the results' matches property, so that it indicates whether or not the document matches the media query at the moment the page was loaded.
Window.pageYOffset - Web APIs
integer euismod lectus a ipsum pellentesque lacinia.</p> `; document.getelementbyid("frame").contentdocument .body.innerhtml = contenthtml; in this example, an <iframe> is created and filled with content, then a specific element within the document is scrolled into view in the frame.
...it then gets a reference to the element we want to scroll into view calling getelementbyid() on the frame's htmliframeelement.contentdocument.
Window.scrollX - Web APIs
WebAPIWindowscrollX
if the document is rendered on a subpixel-precise device, then the returned value is also subpixel-precise and may contain a decimal component.
... if the document isn't scrolled at all left or right, then scrollx is 0.
Window.scrollY - Web APIs
WebAPIWindowscrollY
if the document is rendered on a subpixel-precise device, then the returned value is also subpixel-precise and may contain a decimal component.
... if the document isn't scrolled at all up or down, then scrolly is 0.
WindowClient.focus() - Web APIs
syntax windowclient.focus().then(function(windowclient) { // do something with your windowclient once it has been focused }); parameters none.
... example self.addeventlistener('notificationclick', function(event) { console.log('on notification click: ', event.notification.tag); event.notification.close(); // this looks to see if the current is already open and // focuses if it is event.waituntil(clients.matchall({ type: "window" }).then(function(clientlist) { for (var i = 0; i < clientlist.length; i++) { var client = clientlist[i]; if (client.url == '/' && 'focus' in client) return client.focus(); } if (clients.openwindow) return clients.openwindow('/'); })); }); specifications specification status comment service workersthe definition of 'focus()' in that specification.
WindowClient.navigate() - Web APIs
the navigate() method of the windowclient interface loads a specified url into a controlled client page then returns a promise that resolves to the existing windowclient.
... syntax windowclient.navigate(url).then(function(windowclient) { // do something with your windowclient after navigation }); parameters url the location to navigate to.
self.createImageBitmap() - Web APIs
example creating sprites from a sprite sheet this example loads a sprite sheet, extracts individual sprites, and then renders each sprite to the canvas.
... var canvas = document.getelementbyid('mycanvas'), ctx = canvas.getcontext('2d'), image = new image(); // wait for the sprite sheet to load image.onload = function() { promise.all([ // cut out two sprites from the sprite sheet createimagebitmap(image, 0, 0, 32, 32), createimagebitmap(image, 32, 0, 32, 32) ]).then(function(sprites) { // draw each sprite onto the canvas ctx.drawimage(sprites[0], 0, 0); ctx.drawimage(sprites[1], 32, 32); }); } // load the sprite sheet from an image file image.src = 'sprites.png'; specifications specification status comment html living standardthe definition of 'createimagebitmap' in that specification.
WindowOrWorkerGlobalScope.queueMicrotask() - Web APIs
examples self.queuemicrotask(() => { // function contents here }) taken from the queuemicrotask spec: myelement.prototype.loaddata = function (url) { if (this._cache[url]) { queuemicrotask(() => { this._setdata(this._cache[url]); this.dispatchevent(new event("load")); }); } else { fetch(url).then(res => res.arraybuffer()).then(data => { this._cache[url] = data; this._setdata(data); this.dispatchevent(new event("load")); }); } }; when queuemicrotask() isn't available the code below is basically a monkey-patch for queuemicrotask() for modern engines.
... if (typeof window.queuemicrotask !== "function") { window.queuemicrotask = function (callback) { promise.resolve() .then(callback) .catch(e => settimeout(() => { throw e; })); // report exceptions }; } specifications specification status comment html living standardthe definition of 'self.queuemicrotask()' in that specification.
WritableStreamDefaultWriter.ready - Web APIs
defaultwriter.ready .then(function() { defaultwriter.write(chunk) .then(function() { console.log("chunk written to sink.); }) .catch(function(err) { console.log("chunk error: " + err); }); }); // call ready again to ensure that all chunks are written // before closing the writer.
... defaultwriter.ready .then(function() { defaultwriter.close() .then(function() { console.log("all chunks written"); }) .catch(function(err) { console.log("stream error: " + err); }); }); }); } specifications specification status comment streamsthe definition of 'ready' in that specification.
XMLHttpRequest.open() - Web APIs
user optional the optional user name to use for authentication purposes; by default, this is the null value.
... password optional the optional password to use for authentication purposes; by default, this is the null value.
XMLHttpRequest - Web APIs
if true, the request will be sent without cookie and authentication headers.
... since then, a number of additional event handlers have been implemented in various browsers (onload, onerror, onprogress, etc.).
XRReferenceSpace: reset event - Web APIs
this is common when the user calibrates or recalibrates an xr device, or if the device automatically changes its origin after losing tracking of the user, then re-gaining it.
... the tracking system has temporarily lost the user, then regained them, but not until after they had moved enough to leave the immediate vicinity of the last-known position.
XRRigidTransform - Web APIs
it then requests the first animation frame callback by calling the session's requestanimationframe() method.
... xrsession.requestreferencespace(refspacetype) .then((refspace) => { xrreferencespace = refspace; xrreferencespace = xrreferencespace.getoffsetreferencespace( new xrrigidtransform(viewerstartposition, cubeorientation)); animationframerequestid = xrsession.requestanimationframe(drawframe); specifications specification status comment webxr device apithe definition of 'xrrigidtransform' in that specification.
XRSession.onsqueeze - Web APIs
the xrsession interface's onsqueeze event handler property can be set to a function which is then invoked to handle the squeeze event that's sent when the user successfully completes a primary squeeze action on a webxr input device.
...then we pass the currently held object and the target ray's transform matrix into a function we call dropobjectusingray() to drop the object, using the target ray to determine the surface upon which the object should be placed.
XRSession.updateRenderState() - Web APIs
examples this example creates a webgl context that is compatible with an immersive xr device and then uses it to create an xrwebgllayer.
... updaterenderstate() is then called to associate the new xrwebgllayer.
XRSession - Web APIs
WebAPIXRSession
if select is not sent, then the select action was aborted before being completed.
... 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.getviewport(xrview); gl.viewport(xrviewpor...
Web APIs
WebAPI
recordingnnavigation timingnetwork information api ppage visibility apipayment request apiperformance apiperformance timeline apipermissions apipointer eventspointer lock apiproximity events push api rresize observer apiresource timing apisserver sent eventsservice workers apistoragestorage access apistreams ttouch eventsuurl apivvibration apivisual viewport wweb animationsweb audio apiweb authentication apiweb crypto apiweb notificationsweb storage apiweb workers apiwebglwebrtcwebvttwebxr device apiwebsockets api interfaces this is a list of all the interfaces (that is, types of objects) that are available.
...obuffer audiobuffersourcenode audioconfiguration audiocontext audiocontextlatencycategory audiocontextoptions audiodestinationnode audiolistener audionode audionodeoptions audioparam audioparamdescriptor audioparammap audioprocessingevent audioscheduledsourcenode audiotrack audiotracklist audioworklet audioworkletglobalscope audioworkletnode audioworkletnodeoptions audioworkletprocessor authenticatorassertionresponse authenticatorattestationresponse authenticatorresponse b baseaudiocontext basiccardrequest basiccardresponse batterymanager beforeinstallpromptevent beforeunloadevent biquadfilternode blob blobbuilder blobevent bluetooth bluetoothadvertisingdata bluetoothcharacteristicproperties bluetoothdevice bluetoothremotegattcharacteristic bluetoothremotegattdescr...
ARIA Screen Reader Implementors Guide - Accessibility
text to speech and a braille display), then two queues can be maintained to allow for parallel presentation.
...assertive items are first then politeness level.
ARIA: row role - Accessibility
if the columns displayed are contiguous, then it can be placed on the row.
... the first rule of aria use is you can use a native feature with the semantics and behavior you require already built in, instead of re-purposing an element and adding an aria role, state or property to make it accessible, then do so.
ARIA: table role - Accessibility
if the table includes cells that span multiple rows or multiple columns, then aria-rowspan or aria-colspan should be included as well.
... the first rule of aria use is if you can use a native feature with the semantics and behavior you require already built in, instead of re-purposing an element and adding an aria role, state or property to make it accessible, then do so.
ARIA: button role - Accessibility
if the button alters the current context, then focus typically remains on the button, such as muting and unmuting an audio file.
...if the button role is added to an element that is not focusable by itself (such as <span>, <div> or <p>) then, the tabindex attribute has to be used to make the button focusable.
HTML To MSAA - Accessibility
for example, if name column has n/a value then it means specific elements doesn't provide own rules to calculate name but name can be computed from aria markup or @title attribute.
... element n/a n/a labelled_by (1003), points to legend element n/a n/a hr role_system_ separator n/a n/a n/a n/a n/a n/a img, input @type=image role_system_ graphic from @alt attribute, empty @alt attribute means name can't be calculated at all n/a state_system_ animated if image has more than one frame n/a "showlongdesc" if @longdesc attribute is presented n/a if @usemap attribute is used then image accessible has children for each map item input @type=button, submit, reset role_system_ pushbutton from @value attribute, @alt attribute, default label, @src attribute, @data attribute n/a state_system_ default if @type attribute has value "submit" n/a "press" n/a input @type=text, textarea role_system_ text n/a value property of input dom element state_system_ readonly if @readonly...
Web Accessibility: Understanding Colors and Luminance - Accessibility
at this color, which has low luminance, can be made legible if "care was taken to acheive adequate luminance contrast" (from the article, designing with blue) wcag 2.1 defines relative luminance as follows (as of july 2019): for the srgb colorspace, the relative luminance of a color is defined as l = 0.2126 * r + 0.7152 * g+ 0.0722 * b where r, g and b are defined as: if rsrgb <= 0.03928 then r = rsrgb/12.92 else r = ((rsrgb+0.055)/1.055) ^ 2.4 if gsrgb <= 0.03928 then g = gsrgb/12.92 else g = ((gsrgb+0.055)/1.055) ^ 2.4 if bsrgb <= 0.03928 then b = bsrgb/12.92 else b = ((bsrgb+0.055)/1.055) ^ 2.4 and rsrgb, gsrgb, and bsrgb are defined as: rsrgb = r8bit/255 gsrgb = g8bit/255 bsrgb = b8bit/255 the "^" character is the exponentiation operator.
... the "math" for the calculations is spelled out in wcag 2.1 in the definition for relative luminance, and is as follows: for the srgb colorspace, the relative luminance of a color is defined as l = 0.2126 * r + 0.7152 * g+ 0.0722 * b where r, g and b are defined as: if rsrgb <= 0.03928 then r = rsrgb/12.92 else r = ((rsrgb+0.055)/1.055) ^ 2.4 if gsrgb <= 0.03928 then g = gsrgb/12.92 else g = ((gsrgb+0.055)/1.055) ^ 2.4 if bsrgb <= 0.03928 then b = bsrgb/12.92 else b = ((bsrgb+0.055)/1.055) ^ 2.4 and rsrgb, gsrgb, and bsrgb are defined as: rsrgb = r8bit/255 gsrgb = g8bit/255 bsrgb = b8bit/255 there is active discussion and investigation underway concerning relative luminan...
-moz-image-rect - CSS: Cascading Style Sheets
css the css defines one container style, then the styles for the four boxes that comprise the complete image.
... the container looks like this: #container { width:267px; height:272px; top:100px; left:100px; position:absolute; font-size:16px; text-shadow:white 0px 0px 6px; text-align:center; } then the four boxes defining the segments of the image are defined.
-webkit-mask-repeat-x - CSS: Cascading Style Sheets
example: an image with an original width of 260px, repeated three times, might stretch until each repetition is 300px wide, and then another image will be added.
... they will then compress to 225px.
-webkit-mask-repeat-y - CSS: Cascading Style Sheets
example: an image with an original height of 260px, repeated three times, might stretch until each repetition is 300px high, and then another image will be added.
... they will then compress to a height of 225px.
:defined - CSS: Cascading Style Sheets
WebCSS:defined
in this demo we define a very simple trivial custom element: customelements.define('simple-custom', class extends htmlelement { constructor() { super(); let divelem = document.createelement('div'); divelem.textcontent = this.getattribute('text'); let shadowroot = this.attachshadow({mode: 'open'}) .appendchild(divelem); } }) then insert a copy of this element into the document, along with a standard <p>: <simple-custom text="custom element example text"></simple-custom> <p>standard paragraph example text</p> in the css we first include the following rules: // give the two elements distinctive backgrounds p { background: yellow; } simple-custom { background: cyan; } // both the custom and the built-in element are...
... given italic text :defined { font-style: italic; } then provide the following two rules to hide any instances of our custom element that are not defined, and display instances that are defined as block level elements: simple-custom:not(:defined) { display: none; } simple-custom:defined { display: block; } this is useful if you have a complex custom element that takes a while to load into the page — you might want to hide instances of the element until definition is complete, so that you don't end up with flashes of ugly unstyled elements on the page specifications specification status comment html living standardthe definition of ':defined' in that specification.
font-stretch - CSS: Cascading Style Sheets
for a particular font family, authors can download various font faces which correspond to the different styles of the same font family, and then use the font-stretch descriptor to explicitly specify the font face's stretch.
... if the font does not provide a face that exactly matches the given value, then values less than 100% map to a narrower face, and values greater than or equal to 100% map to a wider face.
Coordinate systems - CSS: Cascading Style Sheets
the implementation is then quite simple.
...for example, if the value of type is "page", then idx is "pagex" and idy is "pagey".
CSS Animations tips and tricks - CSS: Cascading Style Sheets
that's because the only way to play an animation again is to remove the animation effect, let the document recompute styles so that it knows you've done that, then add the animation effect back to the element.
...if instead you'd like the animation to complete and then come to a stop you have to try a different approach.
Using CSS animations - CSS: Cascading Style Sheets
let’s say we want the header’s font size to increase as it moves from right to left for a while, then to decrease back to its original size.
...it simply looks at the event.type to determine which kind of animation event occurred, then adds an appropriate note to the <ul> (unordered list) we’re using to log these events.
Mastering margin collapsing - CSS: Cascading Style Sheets
rating parent and descendants if there is no border, padding, inline part, block formatting context created, or clearance to separate the margin-top of a block from the margin-top of one or more of its descendant blocks; or no border, padding, inline content, height, min-height, or max-height to separate the margin-bottom of a block from the margin-bottom of one or more of its descendant blocks, then those margins collapse.
... empty blocks if there is no border, padding, inline content, height, or min-height to separate a block's margin-top from its margin-bottom, then its top and bottom margins collapse.
Using multi-column layouts - CSS: Cascading Style Sheets
if column-count is not also set, then the browser will automatically make as many columns as fit in the available width.
... however, in some situations it is also useful to set the maximum height of the columns explicitly, and then lay out content starting at the first column and creating as many columns as necessary, possibly overflowing to the right.
Flow Layout and Overflow - CSS: Cascading Style Sheets
giving an element a fixed height and width, then adding significant content to the box, creates a basic overflow example: the content goes into the box.
...if it doesn’t fit then scrollbars will be added.
Flow Layout and Writing Modes - CSS: Cascading Style Sheets
if you want to change your page, or part of your page, to vertical-lr then you can set writing-mode: vertical-lr on the element and this will change the direction of the blocks and therefore the inline direction as well.
... boxes with a different writing mode to their parent when a nested box is assigned a different writing mode to its parent, then an inline level box will display as if it has display: inline-block.
Box alignment in CSS Grid Layout - CSS: Cascading Style Sheets
a a ."; } .item1 { grid-area: a; align-self: center; justify-self: center; } <div class="wrapper"> <div class="item1">item 1</div> </div> aligning the grid tracks on the block axis if you have a situation where your grid tracks use an area that is smaller than the grid container, then you can align the grid tracks themselves, inside that container.
...this will be important to understand, if you develop sites that are then displayed in multiple languages, or if you want to mix languages or writing modes in a design.
Browser compatibility and Scroll Snap - CSS: Cascading Style Sheets
if you have already used the old implementation as a fallback, or feel you want to support users of old firefox (or -webkit prefixed safari), then you can continue to use the old specification as outlined in the example below.
... if you want to test using feature queries for support of the new spec then we'd suggest testing for scroll-snap-align as this property did not exist in the old implementation.
Shapes from box values - CSS: Cascading Style Sheets
if you have no padding then padding-box is the same as content-box.
...you can create a circular shape using border-radius and then curve text around it.
Introducing the CSS Cascade - CSS: Cascading Style Sheets
WebCSSCascade
then it sorts these rules according to their importance, that is, whether or not they are followed by !important, and by their origin.
...therefore, it is the last one that is then selected: margin-left: 3px note that the declaration defined in the user css, though having a greater specificity, is not chosen as the cascade algorithm is applied before the specificity algorithm.
Scaling of SVG backgrounds - CSS: Cascading Style Sheets
the intrinsic 3:4 aspect ratio then determines the height for the auto case.
... source: no specified dimensions with intrinsic ratio if no dimensions are specified in the svg, the specified dimension in the css is applied, then the intrinsic ratio is used to select the other dimension, per rule 2.
Shorthand properties - CSS: Cascading Style Sheets
: border-width: 1em 2em 3em 4em — the four values represent the top, right, bottom and left edges respectively, always in that order, that is clock-wise starting at the top (the initial letter of top-right-bottom-left matches the order of the consonant of the word trouble: trbl) (you can also remember it as the order that the hands would rotate on a clock: 1em starts in the 12 o'clock position, then 2em in the 3 o'clock position, then 3em in the 6 o'clock position, and 4em in the 9 o'clock position).
...note that the values are in clockwise order, beginning at the top: top, right, bottom, then left (trbl, the consonants in "trouble").
background-repeat - CSS: Cascading Style Sheets
example: an image with an original width of 260px, repeated three times, might stretch until each repetition is 300px wide, and then another image will be added.
... they will then compress to 225px.
box-flex - CSS: Cascading Style Sheets
WebCSSbox-flex
if only one content element has nonzero flex, then it grows to fill the available space.
... if the flex value is set using the element's flex attribute, then the style is ignored.
box-shadow - CSS: Cascading Style Sheets
for each shadow, if both input shadows are or are not inset, then the interpolated shadow must match the input shadows in that regard.
...if the lists of shadows have different lengths, then the shorter list is padded at the end with shadows whose color is transparent, all lengths are 0, and whose inset (or not) matches the longer list.
box-sizing - CSS: Cascading Style Sheets
if the element has any border or padding, this is then added to the width and height to arrive at the size of the box that's rendered on the screen.
...if you set an element's width to 100 pixels, then the element's content box will be 100 pixels wide, and the width of any border or padding will be added to the final rendered width, making the element wider than 100px.
cross-fade() - CSS: Cascading Style Sheets
if the result is greater than 0%, the result is then divided equally between all images with omitted percentages.
...the result, if greater than 0, is then divided equally between all images with omitted percentages.
filter - CSS: Cascading Style Sheets
WebCSSfilter
if they have different lengths, the missing equivalent filter functions from the longer list are added to the end of the shorter list using their lacuna values, then all filter functions are interpolated according to their specific rules.
... if one filter is none, it is replaced with the filter functions list of the other one using the filter function default values, then all filter functions are interpolated according to their specific rules.
flex-basis - CSS: Cascading Style Sheets
then, flex-basis:auto was changed to mean automatic sizing, and "main-size" was introduced as the "look at my width or height property" keyword.
... then, that change was reverted in bug 1093316, so auto once again means "look at my width or height property"; and a new content keyword is being introduced to trigger automatic sizing.
flex - CSS: Cascading Style Sheets
WebCSSflex
the second value must be one of: a <number>: then it is interpreted as <flex-shrink>.
... a valid value for width: then it is interpreted as <flex-basis>.
grid-template-columns - CSS: Cascading Style Sheets
if the size of the grid container depends on the size of its tracks, then the percentage must be treated as auto.
...if max is smaller than min, then max is ignored and the function is treated as min.
grid-template-rows - CSS: Cascading Style Sheets
if the size of the grid container depends on the size of its tracks, then the percentage must be treated as auto.
...if max is smaller than min, then max is ignored and the function is treated as min.
mask-repeat - CSS: Cascading Style Sheets
example: an image with an original width of 260px, repeated three times, might stretch until each repetition is 300px wide, and then another image will be added.
... they will then compress to 225px.
minmax() - CSS: Cascading Style Sheets
WebCSSminmax
if max < min, then max is ignored and minmax(min,max) is treated as min.
...if the size of the grid container depends on the size of its tracks, then the <percentage> must be treated as auto.
object-fit - CSS: Cascading Style Sheets
if the object's aspect ratio does not match the aspect ratio of its box, then the object will be clipped to fit.
...if the object's aspect ratio does not match the aspect ratio of its box, then the object will be stretched to fit.
order - CSS: Cascading Style Sheets
WebCSSorder
items in a container are sorted by ascending order value and then by their source code order.
...if the visual (css) order is important, then screen reader users will not have access to the correct reading order.
pointer-events - CSS: Cascading Style Sheets
if one of the element's children has pointer-events explicitly set to allow that child to be the target of pointer events, then any events targeting that child will pass through the parent as the event travels along the parent chain, and trigger event listeners on the parent as appropriate.
...to help us in deciding how pointer-events should be further extended for html, if you have any particular things that you would like to be able to do with this property, then please add them to the use cases section of this wiki page (don't worry about keeping it tidy).
repeating-conic-gradient() - CSS: Cascading Style Sheets
the colors transition as as if spun around the center of a circle, starting at the top if no from <angle> is declared, and going clockwise for the the size of the angle that is the different between the largest and smallest color angle, then repeating.
... a repeating conic gradient is specified by indicating a rotation angle, the center of the gradient, and then specifying a list of color-stops.
shape-outside - CSS: Cascading Style Sheets
if the border-radius / margin ratio is 1 or more, then the margin box corner radius is border-radius + margin.
... if the ratio is less than 1, then the margin box corner radius is border-radius + (margin * (1 + (ratio-1)^3)).
translateZ() - CSS: Cascading Style Sheets
the second is altered by applying perspective to create a 3d space, then moved towards the user.
... then, the translatez() function moves the element 200 pixels "outward" from the screen, toward the user.
transform-origin - CSS: Cascading Style Sheets
this property is applied by first translating the element by the value of the property, then applying the element's transform, then translating by the negated property value.
... if two or more values are defined and either no value is a keyword, or the only used keyword is center, then the first value represents the horizontal offset and the second represents the vertical offset.
Used value - CSS: Cascading Style Sheets
then, css 2.1 introduced the distinct definition of used value.
... an element could then explicitly inherit a width/height of a parent, whose computed value is a percentage.
will-change - CSS: Cascading Style Sheets
then the browser can choose to apply any ahead-of-time optimizations required for the property change before the property change actually happens.
...find some way to predict at least slightly ahead of time that something will change, and set will-change then.
Setting up adaptive streaming media sources - Developer guides
note: you can also split out your audio and video streams into separate files, which can then be prioritised and served separately depending on bandwidth.
... media is usually encoded as mpeg-4 (h.264 video and aac audio) and packaged into an mpeg-2 transport stream, which is then broken into segments and saved as one or more .ts media files.
Challenge solutions - Developer guides
solution add the following style declaration to the strong rule: font: 200% serif; if you use separate declarations for font-size and font-family, then the font-style setting on the first paragraph is not overridden.
...then refresh your browser to see if you were correct.
Creating and triggering events - Developer guides
for example, the event could be created as follows: const event = new customevent('build', { detail: elem.dataset.time }); this will then allow you to access the additional data in the event listener: function eventhandler(e) { console.log('the time is: ' + e.detail); } the old-fashioned way the older approach to creating events uses apis inspired by java.
...></textarea> </form> const form = document.queryselector('form'); const textarea = document.queryselector('textarea'); // create a new event, allow bubbling, and provide any data you want to pass to the "detail" property const eventawesome = new customevent('awesome', { bubbles: true, detail: { text: () => textarea.value } }); // the form element listens for the custom "awesome" event and then consoles the output of the passed text() method form.addeventlistener('awesome', e => console.log(e.detail.text())); // as the user types, the textarea inside the form dispatches/triggers the event to fire, and uses itself as the starting point textarea.addeventlistener('input', e => e.target.dispatchevent(eventawesome)); creating and dispatching events dynamically elements can listen for eve...
DOM onevent handlers - Developer guides
a handler can then be removed from the object by calling its removeeventlistener() function.
...</p> <div></div> javascript then this javascript demonstrates that the value of the html attribute is unaffected by changes to the javascript object's property.
Constraint validation - Developer guides
basically, the idea is to trigger javascript on some form field event (like onchange) to calculate whether the constraint is violated, and then to use the method field.setcustomvalidity() to set the result of the validation: an empty string means the constraint is satisfied, and any other string means there is an error and this string is the error message to display to the user.
... if (constraint.test(zipfield.value)) { // the zip follows the constraint, we use the constraintapi to tell it zipfield.setcustomvalidity(""); } else { // the zip doesn't follow the constraint, we use the constraintapi to // give a message about the format required for this country zipfield.setcustomvalidity(constraints[country][1]); } } then we link it to the onchange event for the <select> and the oninput event for the <input>: window.onload = function () { document.getelementbyid("country").onchange = checkzip; document.getelementbyid("zip").oninput = checkzip; } you can see a live example of the postal code validation.
User input and controls - Developer guides
when you click the canvas, pointer lock is then used to remove the mouse pointer and allow you to move the ball directly using the mouse.
... contenteditable demo this is a working example showing how contenteditable can be used to create an editable document section, the state of which is then saved using localstorage.
HTML attribute: accept - HTML: Hypertext Markup Language
it is still possible (in most cases) for users to toggle an option in the file chooser that makes it possible to override this and select any file they wish, and then choose incorrect file types.
...by holding down shift or control, and then clicking).
HTML attribute: rel - HTML: Hypertext Markup Language
WebHTMLAttributesrel
if the attribute is omitted or if none of the values in the attribute are supported, then the document has no particular relationship with the destination resource other than there being a hyperlink between the two.
... in this case, on <link> and <form>, if the rel attribute is absent, has no keywords, or if not one or more of the space-separated keywords above, then the element does not create any links.
Date and time formats used in HTML - HTML: Hypertext Markup Language
a valid week string consists of a valid year number, followed by a hyphen character ("-", or u+002d), then the capital letter "w" (u+0057), followed by a two-digit week of the year value.
...a valid time string minimally consists of a two-digit hour followed by a colon (":", u+003a), then a two-digit minute.
<dfn>: The Definition element - HTML: Hypertext Markup Language
WebHTMLElementdfn
if the <dfn> contains a single child element and does not have any text content of its own, and the child element is an <abbr> element with a title attribute itself, then the exact value of the <abbr> element's title is the term being defined.
... links to <dfn> elements if you include an id attribute on the <dfn> element, you can then link to it using <a> elements.
<fieldset>: The Field Set element - HTML: Hypertext Markup Language
WebHTMLElementfieldset
if the <fieldset> is styled with display: grid or display: inline-grid, then the anonymous box will be a grid formatting context.
... if the <fieldset> is styled with display: flex or display: inline-flex, then the anonymous box will be a flex formatting context.
<input type="email"> - HTML: Hypertext Markup Language
WebHTMLElementinputemail
then, as the user types, the list is filtered to show only matching values.
...this simple regular expression requests a string that consists of at least one character of any kind, then an "@" followed by the domain name "beststartupever.com".
<input type="number"> - HTML: Hypertext Markup Language
WebHTMLElementinputnumber
if the value of the max attribute isn't a number, then the element has no maximum value.
... for example, to adjust the width of the input to be only as wide as is needed to enter a three-digit number, we can change our html to include an id and to shorten our placeholder since the field will be too narrow for the text we have been using so far: <input type="number" placeholder="x10" step="10" min="0" max="100" id="number"> then we add some css to narrow the width of the element with the id selector #number: #number { width: 3em; } the result looks like this: offering suggested values you can provide a list of default options from which the user can select by specifying the list attribute, which contains as its value the id of a <datalist>, which in turn contains one <option> element per suggested value.
<input type="radio"> - HTML: Hypertext Markup Language
WebHTMLElementinputradio
for example, if the user clicks on the "phone" radio button then submits the form, the form's data will include the line contact=phone.
...abel for="contactchoice1">email</label> <input type="radio" id="contactchoice2" name="contact" value="phone"> <label for="contactchoice2">phone</label> <input type="radio" id="contactchoice3" name="contact" value="mail"> <label for="contactchoice3">mail</label> </div> <div> <button type="submit">submit</button> </div> </form> <pre id="log"> </pre> then we add some javascript to set up an event listener on the submit event, which is sent when the user clicks the "submit" button: var form = document.queryselector("form"); var log = document.queryselector("#log"); form.addeventlistener("submit", function(event) { var data = new formdata(form); var output = ""; for (const entry of data) { output = output + entry[0] + "=" + entry[1] + "\...
<input type="reset"> - HTML: Hypertext Markup Language
WebHTMLElementinputreset
if you want to create a custom button and then customize the behaviour using javascript, you need to use <input type="button">, or better still, a <button> element.
... a simple reset button we'll begin by creating a simple reset button: <form> <div> <label for="example">type in some sample text</label> <input id="example" type="text"> </div> <div> <input type="reset" value="reset the form"> </div> </form> this renders like so: try entering some text into the text field, and then pressing the reset button.
<input type="tel"> - HTML: Hypertext Markup Language
WebHTMLElementinputtel
then, as the user types, the list is adjusted to show only filtered matching values.
... it makes you wonder if it is worth going to all this trouble on the client-side, when you could just let the user enter their number in whatever format they wanted on the client-side and then validate and sanitize it on the server.
<label> - HTML: Hypertext Markup Language
WebHTMLElementlabel
the <label> then needs a for attribute whose value is the same as the input's id.
...if it is not labelable then the for attribute has no effect.
<script>: The Script element - HTML: Hypertext Markup Language
WebHTMLElementscript
asynchtml5 for classic scripts, if the async attribute is present, then the classic script will be fetched in parallel to parsing and evaluated as soon as it is available.
... for module scripts, if the async attribute is present then the scripts and all their dependencies will be executed in the defer queue, therefore they will get fetched in parallel to parsing and evaluated as soon as they are available.
<tbody>: The Table Body element - HTML: Hypertext Markup Language
WebHTMLElementtbody
th, td { border: 1px solid #bbb; padding: 2px 8px 0; text-align: left; } then the style is set for the majority of the cells in the table, including all data cells but also those styles shared between our <td> and <th> cells.
... then each remaining row in each major's <tbody> consists of two cells: the first for the student's id and the second for their name.
HTML documentation index - HTML: Hypertext Markup Language
WebHTMLIndex
for the input, if the type attribute is text or password then it's the number of characters.
...the row's cells can then be established using a mix of <td> (data cell) and <th> (header cell) elements.
Using the application cache - HTML: Hypertext Markup Language
the browser then checks to see if the cache manifest has been updated on the server.
... the process for loading documents and updating the application cache is specified in greater detail below: when the browser visits a document that includes the manifest attribute, if no application cache exists, the browser loads the document and then fetches all the entries listed in the manifest file, creating the first version of the application cache.
Feature Policy - HTTP
if you do not specify a policy for a feature, then a default allowlist will be used.
...best practices are then enforced by using policies that disable the policy-controlled features.
Access-Control-Allow-Origin - HTTP
wser to allow requesting code from the origin https://developer.mozilla.org to access a resource will include the following: access-control-allow-origin: https://developer.mozilla.org limiting the possible access-control-allow-origin values to a set of allowed origins requires code on the server side to check the value of the origin request header, compare that to a list of allowed origins, and then if the origin value is in the list, to set the access-control-allow-origin value to the same value as the origin value.
... cors and caching if the server sends a response with an access-control-allow-origin value that is an explicit origin (rather than the "*" wildcard), then the response should also include a vary response header with the value origin — to indicate to browsers that server responses can differ based on the value of the origin request header.
Content-Security-Policy-Report-Only - HTTP
you observe how your site behaves, watching for violation reports, or malware redirects, then choose the desired policy enforced by the content-security-policy header.
...if the blocked uri is from a different origin than the document-uri, then the blocked uri is truncated to contain just the scheme, host, and port.
Feature-Policy: publickey-credentials-get - HTTP
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: ..., ...}).
... web authentication level 2 editor's draft.
Link prefetching FAQ - HTTP
if a prefetched document is partially downloaded, then the partial document will still be stored in the cache provided the server sent an "accept-ranges: bytes" response header.
...add this line to your prefs.js file located in your profile directory (or make the appropriate change via about:config): user_pref("network.prefetch-next", false); however, the theory is that if link prefetching needs to be disabled then there must be something wrong with the implementation.
PUT - HTTP
WebHTTPMethodsPUT
body no safe no idempotent yes cacheable no allowed in html forms no syntax put /new.html http/1.1 example request put /new.html http/1.1 host: example.com content-type: text/html content-length: 16 <p>new file</p> responses if the target resource does not have a current representation and the put request successfully creates one, then the origin server must inform the user agent by sending a 201 (created) response.
... http/1.1 201 created content-location: /new.html if the target resource does have a current representation and that representation is successfully modified in accordance with the state of the enclosed representation, then the origin server must send either a 200 (ok) or a 204 (no content) response to indicate successful completion of the request.
HTTP
WebHTTP
http follows a classical client-server model, with a client opening a connection to make a request, then waiting until it receives a response.
...the client then returns the cookie's value with every request to the same server in the form of a cookie request header.
Grammar and types - JavaScript
but if more than one statement on a line is desired, then they must be separated by semicolons.
...javascript automatically converts the string literal to a temporary string object, calls the method, then discards the temporary string object.
Meta programming - JavaScript
if a property has a corresponding target object property, then object.defineproperty(target, prop, descriptor) will not throw an exception.
... if the target object is not extensible, then the result list must contain all the keys of the own properties of target and no other values.
SyntaxError: redeclaration of formal parameter "x" - JavaScript
the javascript exception "redeclaration of formal parameter" occurs when the same variable name occurs as a function parameter and is then redeclared using a let assignment in a function body again.
... the same variable name occurs as a function parameter and is then redeclared using a let assignment in a function body again.
SyntaxError: function statement requires a name - JavaScript
the following syntax without a name after the function keyword is valid then.
... promise.then( function() { console.log("success"); }); function() { console.log("error"); } // syntaxerror: function statement requires a name correct would be: promise.then( function() { console.log("success"); }, function() { console.log("error"); } ); ...
TypeError: variable "x" redeclares argument - JavaScript
the javascript strict mode-only exception "variable redeclares argument" occurs when the same variable name occurs as a function parameter and is then redeclared using a var assignment in a function body again.
... the same variable name occurs as a function parameter and is then redeclared using a var assignment in a function body again.
Arrow function expressions - JavaScript
var arr = [5, 6, 13, 0, 1, 18, 23]; var sum = arr.reduce((a, b) => a + b); // 66 var even = arr.filter(v => v % 2 == 0); // [6, 0, 18] var double = arr.map(v => v * 2); // [10, 12, 26, 0, 2, 36, 46] // more concise promise chains promise.then(a => { // ...
... }).then(b => { // ...
getter - JavaScript
the value is calculated the first time the getter is called, and is then cached so subsequent accesses return the cached value without recalculating it.
... this means that you shouldn’t write a lazy getter for a property whose value you expect to change, because if the getter is lazy then it will not recalculate the value.
Array.prototype.reduceRight() - JavaScript
if an initialvalue was provided in the call to reduceright, then accumulator will be equal to initialvalue and currentvalue will be equal to the last value in the array.
... if no initialvalue was provided, then accumulator will be equal to the last value in the array and currentvalue will be equal to the second-to-last value.
Array.prototype.join() - JavaScript
if the array has only one item, then that item will be returned without using the separator.
... examples joining an array four different ways the following example creates an array, a, with three elements, then joins the array four times: using the default separator, then a comma and a space, then a plus and an empty string.
Array.prototype.map() - JavaScript
if kpresent is true, then if (k in o) { // i.
... here is a concise example of the iteration steps: // parseint(string, radix) -> map(parseint(value, index)) /* first iteration (index is 0): */ parseint("1", 0) // 1 /* second iteration (index is 1): */ parseint("2", 1) // nan /* third iteration (index is 2): */ parseint("3", 2) // nan then let's talk about solutions.
Array.prototype.pop() - JavaScript
examples removing the last element of an array the following code creates the myfish array containing four elements, then removes its last element.
... var myfish = ['angel', 'clown', 'mandarin', 'sturgeon']; var popped = myfish.pop(); console.log(myfish); // ['angel', 'clown', 'mandarin' ] console.log(popped); // 'sturgeon' using apply( ) or call ( ) on array-like objects the following code creates the myfish array-like object containing four elements and a length parameter, then removes its last element and decrements the length parameter.
Array.prototype.reverse() - JavaScript
examples reversing the elements in an array the following example creates an array a, containing three elements, then reverses the array.
... const a = [1, 2, 3]; console.log(a); // [1, 2, 3] a.reverse(); console.log(a); // [3, 2, 1] reversing the elements in an array-like object the following example creates an array-like object a, containing three elements and a length property, then reverses the array-like object.
Array.prototype.toLocaleString() - JavaScript
if firstelement is undefined or null, then // a.let r be the empty string.
...if nextelement is undefined or null, then // i.
Array - JavaScript
to help explain these properties and elements, see this example and then refer to the table below: // match one d followed by one or more b's followed by one d // remember matched b's and the following d // ignore case const myre = /d(b+)(d)/i const myarray = myre.exec('cdbbdbsbz') the properties and elements returned from this match are as follows: property/element description example input read only the original string agains...
... examples creating an array the following example creates an array, msgarray, with a length of 0, then assigns values to msgarray[0] and msgarray[99], changing the length of the array to 100.
Function.prototype.apply() - JavaScript
with apply, you can write a method once, and then inherit it in another object, without having to rewrite the method for the new object.
...the called object is then responsible for handling the arguments.
Math.sign() - JavaScript
1 : 0 ) // if x is positive, then positive one // + // else (because you can't be both - and +) // ( (x < 0) ?
... -1 : 0 ) // if x is negative, then negative one // || // if x is 0, -0, or nan, or not a number, // +x // then the result will be x, (or) if x is // // not a number, then x converts to number }; } in the above polyfill, no extra type-coercing is needed to make (x > 0) or (x < 0) numbers because subtracting them from each other forces a type conversion from booleans to numbers.
Object.entries() - JavaScript
if there is a need for certain ordering, then the array should be sorted first, like object.entries(obj).sort((a, b) => b[0].localecompare(a[0]));.
...mple, ready-to-deploy polyfill listed below: if (!object.entries) { object.entries = function( obj ){ var ownprops = object.keys( obj ), i = ownprops.length, resarray = new array(i); // preallocate the array while (i--) resarray[i] = [ownprops[i], obj[ownprops[i]]]; return resarray; }; } for the above polyfill code snippet, if you need support for ie<9, then you will also need an object.keys() polyfill (such as the one found on the object.keys page).
String.prototype.anchor() - JavaScript
the anchor() method creates a string beginning with an <a name="..."> start tag, then some text, and then an </a> end tag.
... return value a string beginning with an <a name="name"> start tag, then the text str, and then an </a> end tag description don't use this method.
String.prototype.replace() - JavaScript
(for example, if the whole string was 'abcd', and the matched substring was 'bc', then this argument will be 1.) string the whole string being examined.
...f2c() then returns the celsius number.
String.prototype.split() - JavaScript
if separator is a regular expression with capturing parentheses, then each time separator matches, the results (including any undefined results) of the capturing parentheses are spliced into the output array.
... if the separator is an array, then that array is coerced to a string and used as a separator.
TypedArray.from() - JavaScript
when the source parameter is an iterator, the typedarray.from() first collects all the values from the iterator, then creates an instance of thisarg using the count, then sets the values on the instance.
... array.from() sets each value as it receives them from the iterator, then sets its length at the end.
TypedArray.prototype.reduce() - JavaScript
if initialvalue is provided in the call to reduce, then previousvalue will be equal to initialvalue and currentvalue will be equal to the first value in the typed array.
... if no initialvalue was provided, then previousvalue will be equal to the first value in the typed array and currentvalue will be equal to the second.
TypedArray.prototype.reduceRight() - JavaScript
if an initialvalue was provided in the call to reduceright, then previousvalue will be equal to initialvalue and currentvalue will be equal to the last value in the typed array.
... if no initialvalue was provided, then previousvalue will be equal to the last value in the typed array and currentvalue will be equal to the second-to-last value.
WebAssembly.Global() constructor - JavaScript
the value of the global is then changed, first to 42 using the global.value property, and then to 43 using the incglobal() function exported out of the global.wasm module (this adds 1 to whatever value is given to it and then returns the new value).
...got: ${got}<br>`; } asserteq("webassembly.global exists", typeof webassembly.global, "function"); const global = new webassembly.global({value:'i32', mutable:true}, 0); webassembly.instantiatestreaming(fetch('global.wasm'), { js: { global } }) .then(({instance}) => { asserteq("getting initial value from wasm", instance.exports.getglobal(), 0); global.value = 42; asserteq("getting js-updated value from wasm", instance.exports.getglobal(), 42); instance.exports.incglobal(); asserteq("getting wasm-updated value from js", global.value, 43); }); note: you can see the example running live on github; see also the source code.
WebAssembly.Global - JavaScript
the value of the global is then changed, first to 42 using the global.value property, and then to 43 using the incglobal() function exported out of the global.wasm module (this adds 1 to whatever value is given to it and then returns the new value).
...got: ${got}<br>`; } asserteq("webassembly.global exists", typeof webassembly.global, "function"); const global = new webassembly.global({value:'i32', mutable:true}, 0); webassembly.instantiatestreaming(fetch('global.wasm'), { js: { global } }) .then(({instance}) => { asserteq("getting initial value from wasm", instance.exports.getglobal(), 0); global.value = 42; asserteq("getting js-updated value from wasm", instance.exports.getglobal(), 42); instance.exports.incglobal(); asserteq("getting wasm-updated value from js", global.value, 43); }); note: you can see the example running live on github; see also the source code.
WebAssembly.Instance() constructor - JavaScript
examples synchronously instantiating a webassembly module the webassembly.instance() constructor function can be called to synchronously instantiate a given webassembly.module object, for example: const importobject = { imports: { imported_func: function(arg) { console.log(arg); } } }; fetch('simple.wasm').then(response => response.arraybuffer() ).then(bytes => { let mod = new webassembly.module(bytes); let instance = new webassembly.instance(mod, importobject); instance.exports.exported_func(); }) however, the preferred way to get an instance is through the asynchronous webassembly.instantiatestreaming() function, for example like this: const importobject = { imports: { imported_func: f...
...unction(arg) { console.log(arg); } } }; webassembly.instantiatestreaming(fetch('simple.wasm'), importobject) .then(obj => obj.instance.exports.exported_func()); specifications specification webassembly javascript interfacethe definition of 'instance' in that specification.
WebAssembly.Instance.prototype.exports - JavaScript
we then call an exported webassembly function that is exported by the instance.
... var importobject = { imports: { imported_func: function(arg) { console.log(arg); } } }; webassembly.instantiatestreaming(fetch('simple.wasm'), importobject) .then(obj => obj.instance.exports.exported_func()); note: you can also find this example as instantiate-streaming.html on github (view it live also).
WebAssembly.Instance - JavaScript
examples synchronously instantiating a webassembly module the webassembly.instance() constructor function can be called to synchronously instantiate a given webassembly.module object, for example: const importobject = { imports: { imported_func: function(arg) { console.log(arg); } } }; fetch('simple.wasm').then(response => response.arraybuffer() ).then(bytes => { let mod = new webassembly.module(bytes); let instance = new webassembly.instance(mod, importobject); instance.exports.exported_func(); }) the preferred way to get an instance is asynchronously, for example using the webassembly.instantiatestreaming() function like this: const importobject = { imports: { imported_func: function(a...
...rg) { console.log(arg); } } }; webassembly.instantiatestreaming(fetch('simple.wasm'), importobject) .then(obj => obj.instance.exports.exported_func()); this also demonstrates how the exports property is used to access exported functions.
WebAssembly.Memory() constructor - JavaScript
it then stores some values in that memory, then exports a function and uses it to sum some values.
... webassembly.instantiatestreaming(fetch('memory.wasm'), { js: { mem: memory } }) .then(obj => { var i32 = new uint32array(memory.buffer); for (var i = 0; i < 10; i++) { i32[i] = i; } var sum = obj.instance.exports.accumulate(0, 10); console.log(sum); }); creating a shared memory by default, webassembly memories are unshared.
WebAssembly.Memory.prototype.buffer - JavaScript
it then stores some values in that memory, then exports a function and uses it to sum some values.
... webassembly.instantiatestreaming(fetch('memory.wasm'), { js: { mem: memory } }) .then(obj => { var i32 = new uint32array(memory.buffer); for (var i = 0; i < 10; i++) { i32[i] = i; } var sum = obj.instance.exports.accumulate(0, 10); console.log(sum); }); specifications specification webassembly javascript interfacethe definition of 'buffer' in that specification.
WebAssembly.Memory - JavaScript
it then stores some values in that memory, then exports a function and uses it to sum some values.
... webassembly.instantiatestreaming(fetch('memory.wasm'), { js: { mem: memory } }) .then(obj => { var i32 = new uint32array(memory.buffer); for (var i = 0; i < 10; i++) { i32[i] = i; } var sum = obj.instance.exports.accumulate(0, 10); console.log(sum); }); creating a shared memory by default, webassembly memories are unshared.
WebAssembly.Module.customSections() - JavaScript
we then do a check using webassembly.module.customsections, looking to see whether the module instance contains a "name" custom section by checking that its length is more than 0.
... webassembly.compilestreaming(fetch('simple-name-section.wasm')) .then(function(mod) { var namesections = webassembly.module.customsections(mod, "name"); if (namesections.length != 0) { console.log("module contains a name section"); console.log(namesections[0]); }; }); specifications specification webassembly javascript interfacethe definition of 'customsections()' in that specification.
WebAssembly.Module.imports() - JavaScript
this module is then queried for its imports.
... webassembly.compilestreaming(fetch('simple.wasm')) .then(function(mod) { var imports = webassembly.module.imports(mod); console.log(imports[0]); }); the output looks like this: { module: "imports", name: "imported_func", kind: "function" } specifications specification webassembly javascript interfacethe definition of 'imports()' in that specification.
WebAssembly.Table.prototype.get() - JavaScript
it then retrieves the references stored in the exported table.
... webassembly.instantiatestreaming(fetch('table.wasm')) .then(function(obj) { var tbl = obj.instance.exports.tbl; console.log(tbl.get(0)()); // 13 console.log(tbl.get(1)()); // 42 }); note how you've got to include a second function invocation operator at the end of the accessor to actually retrieve the value stored inside the reference (e.g.
WebAssembly.Table.prototype.set() - JavaScript
we then print out the table length and contents of the two indexes (retrieved via table.prototype.get()) to show that the length is two, and the indexes currently contain no function references (they currently return null).
... var tbl = new webassembly.table({initial:2, element:"anyfunc"}); console.log(tbl.length); console.log(tbl.get(0)); console.log(tbl.get(1)); we then create an import object that contains a reference to the table: var importobj = { js: { tbl:tbl } }; finally, we load and instantiate a wasm module (table2.wasm) using the webassembly.instantiatestreaming(), log the table length, and invoke the two referenced functions that are now stored in the table (the table2.wasm module (see text representation) adds two function references to the table, both of which print out a simple value): webassembly.instantiatestreaming(fetch('table2.wasm'), importobject) .then(function(obj) { console.log(tbl.length); console.log(tbl.get(0)()); console.log(tbl.get(1)()); }); note how you've got to i...
WebAssembly.compile() - JavaScript
examples using compile the following example compiles the loaded simple.wasm byte code using the compile() function and then sends it to a worker using postmessage().
... var worker = new worker("wasm_worker.js"); fetch('simple.wasm').then(response => response.arraybuffer() ).then(bytes => webassembly.compile(bytes) ).then(mod => worker.postmessage(mod) ); note: you'll probably want to use webassembly.compilestreaming() in most cases, as it is more efficient than compile().
WebAssembly.compileStreaming() - JavaScript
examples compile streaming the following example (see our compile-streaming.html demo on github, and view it live also) directly streams a .wasm module from an underlying source then compiles it to a webassembly.module object.
... var importobject = { imports: { imported_func: arg => console.log(arg) } }; webassembly.compilestreaming(fetch('simple.wasm')) .then(module => webassembly.instantiate(module, importobject)) .then(instance => instance.exports.exported_func()); the resulting module instance is then instantiated using webassembly.instantiate(), and the exported function invoked.
WebAssembly.instantiateStreaming() - JavaScript
examples instantiating streaming the following example (see our instantiate-streaming.html demo on github, and view it live also) directly streams a .wasm module from an underlying source then compiles and instantiates it, the promise fulfilling with a resultobject.
... var importobject = { imports: { imported_func: arg => console.log(arg) } }; webassembly.instantiatestreaming(fetch('simple.wasm'), importobject) .then(obj => obj.instance.exports.exported_func()); the resultobject's instance member is then accessed, and the contained exported function invoked.
WebAssembly.validate() - JavaScript
the validate() method is then used to check whether the module is valid.
... fetch('simple.wasm').then(response => response.arraybuffer() ).then(function(bytes) { var valid = webassembly.validate(bytes); console.log("the given bytes are " + (valid ?
WebAssembly - JavaScript
examples stream a .wasm module then compile and instantiate it the following example (see our instantiate-streaming.html demo on github, and view it live also) directly streams a .wasm module from an underlying source then compiles and instantiates it, the promise fulfilling with a resultobject.
... var importobject = { imports: { imported_func: arg => console.log(arg) } }; webassembly.instantiatestreaming(fetch('simple.wasm'), importobject) .then(obj => obj.instance.exports.exported_func()); the resultobject's instance member is then accessed, and the contained exported function invoked.
eval() - JavaScript
you can postpone evaluation of an expression involving x by assigning the string value of the expression, say "3 * x + 2", to a variable, and then calling eval() at a later point in your script.
... var x = 5; var str = "if (x == 5) {console.log('z is 42'); z = 42;} else z = 0;"; console.log('z is ', eval(str)); if you define multiple values then the last value is returned.
parseInt() - JavaScript
if this argument is not a string, then it is converted to one using the tostring abstract operation.
... description the parseint function converts its first argument to a string, parses that string, then returns an integer or nan.
Destructuring assignment - JavaScript
comma is used on the left-hand side with a rest element: const [a, ...b,] = [1, 2, 3]; // syntaxerror: rest element may not have a trailing comma // always consider using rest operator as the last element unpacking values from a regular expression match when the regular expression exec() method finds a match, it returns an array containing first the entire matched portion of the string and then the portions of the string that matched each parenthesized group in the regular expression.
...say you want the third element in the array props below, and then you want the name property in the object, you can do the following: const props = [ { id: 1, name: 'fizz'}, { id: 2, name: 'buzz'}, { id: 3, name: 'fizzbuzz'} ]; const [,, { name }] = props; console.log(name); // "fizzbuzz" the prototype chain is looked up when the object is deconstructed when deconstructing an object, if a property is not accessed in itself, it will continue to look...
Nullish coalescing operator (??) - JavaScript
c() ); // logs "a was called" then "c was called" and then "foo" // as a() returned undefined so both expressions are evaluated console.log( b() ??
... c() ); // logs "b was called" then "false" // as b() returned false (and not null or undefined), the right // hand side expression was not evaluated no chaining with and or or operators it is not possible to combine both the and (&&) and or operators (||) directly with ??.
async function expression - JavaScript
examples simple example function resolveafter2seconds(x) { return new promise(resolve => { settimeout(() => { resolve(x); }, 2000); }); }; const add = async function(x) { // async function expression assigned to a variable let a = await resolveafter2seconds(20); let b = await resolveafter2seconds(30); return x + a + b; }; add(10).then(v => { console.log(v); // prints 60 after 4 seconds.
... }); (async function(x) { // async function expression used as an iife let p_a = resolveafter2seconds(20); let p_b = resolveafter2seconds(30); return x + await p_a + await p_b; })(10).then(v => { console.log(v); // prints 60 after 2 seconds.
await - JavaScript
function resolveafter2seconds(x) { return new promise(resolve => { settimeout(() => { resolve(x); }, 2000); }); } async function f1() { var x = await resolveafter2seconds(10); console.log(x); // 10 } f1(); thenable objects thenable objects will be fulfilled just the same.
... async function f2() { const thenable = { then: function(resolve, _reject) { resolve('resolved!') } }; console.log(await thenable); // resolved!
delete operator - JavaScript
if a property with the same name exists on the object's prototype chain, then, after deletion, the object will use the property from the prototype chain (in other words, delete only has an effect on own properties).
...in explorer, while the property value is indeed set to undefined, if one later adds back a property with the same name, the property will be iterated in its old position--not at the end of the iteration sequence as one might expect after having deleted the property and then added it back.
void operator - JavaScript
the void operator evaluates the given expression and then returns undefined.
... javascript uris when a browser follows a javascript: uri, it evaluates the code in the uri and then replaces the contents of the page with the returned value, unless the returned value is undefined.
export - JavaScript
rt } from 'bar.js'; examples using named exports in a module my-module.js, we could include the following code: // module "my-module.js" function cube(x) { return x * x * x; } const foo = math.pi + math.sqrt2; var graph = { options: { color:'white', thickness:'2px' }, draw: function() { console.log('from graph draw function'); } } export { cube, foo, graph }; then in the top-level module included in your html page, we could have: import { cube, foo, graph } from './my-module.js'; graph.options = { color:'blue', thickness:'3px' }; graph.draw(); console.log(cube(3)); // 27 console.log(foo); // 4.555806215962888 it is important to note the following: you need to include this script in your html with a <script> element of type="module", so th...
... using the default export if we want to export a single value or to have a fallback value for your module, you could use a default export: // module "my-module.js" export default function cube(x) { return x * x * x; } then, in another script, it is straightforward to import the default export: import cube from './my-module.js'; console.log(cube(3)); // 27 using export from let's take an example where we have the following hierarchy: childmodule1.js: exporting myfunction and myvariable childmodule2.js: exporting myclass parentmodule.js: acting as an aggregator (and doing nothing else) top level module: con...
switch - JavaScript
it then looks for the first case clause whose expression evaluates to the same value as the result of the input expression (using the strict comparison, ===) and transfers control to that clause, executing the associated statements.
... if you forget a break then the script will run from the case where the criterion is met and will run the cases after that regardless if a criterion was met.
try...catch - JavaScript
(e instanceof rangeerror) { // statements to handle rangeerror exceptions } else if (e instanceof evalerror) { // statements to handle evalerror exceptions } else { // statements to handle any unspecified exceptions logmyerrors(e); // pass exception object to error handler } } a common use case for this is to only catch (and silence) a small subset of expected errors, and then re-throw the error in other cases: try { myroutine(); } catch (e) { if (e instanceof rangeerror) { // statements to handle this very common expected error } else { throw e; // re-throw the error unchanged } } the exception identifier when an exception is thrown in the try-block, exception_var (i.e., the e in catch (e)) holds the exception value.
...the code opens a file and then executes statements that use the file; the finally-block makes sure the file always closes after it is used even if an exception was thrown.
with - JavaScript
if an unqualified name used in the body matches a property in the scope chain, then the name is bound to the property and the object containing the property.
...consider this example: function f(foo, values) { with (foo) { console.log(values); } } if you call f([1,2,3], obj) in an ecmascript 5 environment, then the values reference inside the with statement will resolve to obj.
Strict mode - JavaScript
x; } the simple alternative of assigning the object to a short name variable, then accessing the corresponding property on that variable, stands ready to replace with.
...in strict mode, then, you can't name or use variables or arguments with these names.
Web media technologies
web audio api the web audio api lets you generate, filter, and manipulate sound data both in real-time and on pre-recorded material, then send that audio to a destination such as an <audio> element, a media stream, or to disk.
...the mixed reality content can then be displayed on the device's screen or using goggles or a headset.
Animation performance and frame rate - Web Performance
one last step is not shown in this sequence: the page may be split into layers, which are painted independently and then combined in a process called "composition".
...in each animation frame, we recalculate styles for every element, then perform a single layout, then a repaint.
Critical rendering path - Web Performance
the browser then begins parsing the html, converting the received bytes to the dom tree.
...then you can determine whether it should be an optimization priority.
Populating the page: how browsers work - Web Performance
the cssom and dom trees created in the parsing step are combined into a render tree which is then used to compute the layout of every visible element, which is then painted to the screen.
...if this occurs, then compositing is necessary.
Installing and uninstalling web apps - Progressive web apps (PWAs)
the application itself may then manifest as in a chromeless view (without the full browser chrome) but it nevertheless is executing effectively as a tab within the browser.
... tapping that icon should then take you to the same confirmation banner shown in firefox above.
Applying SVG effects to HTML content - SVG: Scalable Vector Graphics
ng-path-1" clippathunits="objectboundingbox"> <circle cx="0.25" cy="0.25" r="0.25" id="circle"/> <rect x="0.5" y="0.2" width="0.5" height="0.8"/> </clippath> </svg> .target { clip-path: url(#clipping-path-1); } p { width: 300px; border: 1px solid #000; display: inline-block; } this establishes a clipping area made of a circle and rectangle, assigns it the id #clipping-path-1, then references it in the css.
... for example, if your css is in a file named default.css, it can look like this: .target { clip-path: url(resources.svg#c1); } the svg is then imported from a file named resources.svg, using the clip path with the id c1.
display - SVG: Scalable Vector Graphics
WebSVGAttributedisplay
when the display attribute is set to none, then the given element does not become part of the rendering tree.
... it has implications for the <tspan>, <tref>, and <altglyph> elements, event processing, for bounding box calculations and for calculation of clipping paths: if display is set to none on a <tspan>, <tref>, or <altglyph> element, then the text string is ignored for the purposes of text layout.
fill-rule - SVG: Scalable Vector Graphics
> </svg> usage notes value nonzero | evenodd default value nonzero animatable yes the fill-rule attribute provides two options for how the inside (that is, the area to be filled) of a shape is determined: nonzero the value nonzero determines the "insideness" of a point in the shape by drawing a ray from that point to infinity in any direction, and then examining the places where a segment of the shape crosses the ray.
...after counting the crossings, if the result is zero then the point is outside the path.
glyph-orientation-horizontal - SVG: Scalable Vector Graphics
when the reference orientation direction is horizontal and the glyph-orientation-horizontal results in an orientation angle that is a multiple of 180 degrees, then the current text position is incremented according to the horizontal metrics of the glyph.
... otherwise, if the value of this attribute is not a multiple of 180 degrees, then the current text position is incremented according to the vertical metrics of the glyph.
glyph-orientation-vertical - SVG: Scalable Vector Graphics
when the inline-progression-direction is vertical and the glyph-orientation-vertical results in an orientation angle that is a multiple of 180 degrees, then the current text position is incremented according to the vertical metrics of the glyph.
... otherwise, if the angle is not a multiple of 180 degrees, then the current text position is incremented according to the horizontal metrics of the glyph.
kerning - SVG: Scalable Vector Graphics
WebSVGAttributekerning
<length> if a length is provided, then auto-kerning is disabled.
...if a unit identifier (e.g., 0.25em or 1%) is provided, then the length is converted into a corresponding value in the current user coordinate system.
marker-end - SVG: Scalable Vector Graphics
in this case, if the value of marker-start and marker-end are both not none, then two markers will be rendered on that final vertex.
...if the reference is not valid, then no marker will be drawn.
marker-start - SVG: Scalable Vector Graphics
in this case, if the value of marker-start and marker-end are both not none, then two markers will be rendered on that final vertex.
...if the reference is not valid, then no marker will be drawn.
stdDeviation - SVG: Scalable Vector Graphics
if one number is provided, then that value is used for both x and y.
...if stddeviation is 0 in only one of x or y, then the effect is that the blur is only applied in the direction that has a non-zero value.
systemLanguage - SVG: Scalable Vector Graphics
if the attribute is used in other situations, then it represents a simple switch on the given element whether to render the element or not.
... if the attribute is not present, then it implicitly evaluates to "true".
<altGlyph> - SVG: Scalable Vector Graphics
WebSVGElementaltGlyph
if the reference is to a <glyph> element and that glyph is available, then that glyph is rendered instead of the character(s) that are inside of the <altglyph> element.
... if the reference is to an <altglyphdef> element, then if an appropriate set of alternate glyphs is located from processing the <altglyphdef> element, then those alternate glyphs are rendered instead of the character(s) that are inside of the <altglyph> element.
<switch> - SVG: Scalable Vector Graphics
WebSVGElementswitch
the <switch> svg element evaluates any requiredfeatures, requiredextensions and systemlanguage attributes on its direct child elements in order, and then renders the first child where these attributes evaluate to true.
...if a child element is a container element, like <g>, then its subtree is also processed/rendered or bypassed/not rendered.
Fills and Strokes - SVG: Scalable Vector Graphics
so the first path renders 5 filled, 10 empty, 5 filled, and then loops back to create 5 empty, 10 filled, 5 empty.
... the pattern then repeats.
Gradients in SVG - SVG: Scalable Vector Graphics
"reflect" causes the gradient to continue on, but reflected in reverse, starting with the color offset at 100% and moving back to the offset at 0%, and then back up again.
...the radialgradient above would be rewritten: <radialgradient id="gradient" cx="60" cy="60" r="50" fx="35" fy="35" gradientunits="userspaceonuse"> you can also then apply another transformation to the gradient by using the gradienttransform attribute, but since we haven't introduced transforms yet, i'll leave that for later.
Other content in SVG - SVG: Scalable Vector Graphics
but then you have no means to define how the surrounding svg should react on the content.
... since the foreignobject is an svg element, you can, like in the case of image, use any svg goodness with it, which then will be applied to its content.
SVG fonts - SVG: Scalable Vector Graphics
in the example above the first and most important to be defined is font-family, the value of which can then be referenced in css and svg font-family properties.
... the actual glyphs are then defined by <glyph> elements.
id - XPath
WebXPathFunctionsid
syntax id(expression ) arguments expression if expression is a node-set, then the string value of each node in the node-set is treated as an individual id.
... if expression is a string, or anything other than a node-set, then expression is treated as a space-separated list of ids.
number - XPath
if the string does not match this pattern, then the string is converted to nan.
... a node-set is first converted to a string as if by a call to the string() function and then converted in the same way as a string argument.
WebAssembly Concepts - WebAssembly
thus, to access any web api, webassembly needs to call out to javascript, which then makes the web api call.
...you can write or generate this format by hand and then convert it into the binary format with any of several webassemby text-to-binary tools.
Compiling from Rust to WebAssembly - WebAssembly
it then calls the alert function we asked for in the extern block above.
... need an html file; create index.html and give it the following contents: <!doctype html> <html> <head> <meta charset="utf-8"> <title>hello-wasm example</title> </head> <body> <script src="./index.js"></script> </body> </html> finally, create the index.js referenced in the html file and give it these contents: const js = import("./node_modules/hello-wasm/hello_wasm.js"); js.then(js => { js.greet("webassembly"); }); note that you need to fill in your npm username again.
Cross-domain Content Scripts - Archive of obsolete content
element.textcontent = summary; }; request.send(); }); function getsummary(forecast) { return forecast.regionalfcst.fcstperiods.period[0].paragraph[0].$; } finally, we need to add the "cross-domain-content" key to "package.json": "permissions": { "cross-domain-content": ["http://datapoint.metoffice.gov.uk"] } content permissions and unsafewindow if you use "cross-domain-content", then javascript values in content scripts will not be available from pages.
Loading Content Scripts - Archive of obsolete content
this enables you to load a javascript library like jquery by url, then pass in a simple script inline that can use jquery.
Reddit Example - Archive of obsolete content
the content script then needs to send the url to the add-on script.
Communicating using "postMessage" - Archive of obsolete content
rget.tostring());" + "}, false);"; var pagemod = require('sdk/page-mod').pagemod({ include: ['*'], contentscript: pagemodscript, onattach: function(worker) { worker.on('message', function(message) { console.log('mouseover: ' + message); }); } }); the reason to prefer user-defined events is that as soon as you need to send more than one type of message, then both sending and receiving messages gets more complex.
Content Processes - Archive of obsolete content
we can then hook up a listener to be called when this message arrives at the other process, which in turn calls the emit function on the other event emitter.
Private Properties - Archive of obsolete content
a better solution would be to store all private properties on a single object, called a namespace, and then store the namespace as a private property on the original object.
Porting the Library Detector - Archive of obsolete content
for example, if window.jquery is defined, then the page has loaded jquery.
Two Types of Scripts - Archive of obsolete content
if require() is available, then so are the modules supplied in the sdk.
clipboard - Archive of obsolete content
the following types are supported: text (plain text) html (a string of html) image (a base-64 encoded png) if no data type is provided, then the module will detect it for you.
hotkeys - Archive of obsolete content
for example, accel-s is typically used to save a file, but if you use it for something completely different, then it would be extremely confusing for users.
l10n - Archive of obsolete content
if you're supplying different localizations for a string depending on the number of items (that is, whether to use a singular or plural form) then get() takes a second integer parameter which indicates the number of items there are.
page-worker - Archive of obsolete content
in this example we fetch the first paragraph of a page from wikipedia, then the first paragraph of a different page: var getfirstparagraph = "var paras = document.getelementsbytagname('p');" + "console.log(paras[0].textcontent);" + "self.port.emit('loaded');" pageworker = require("sdk/page-worker").page({ contentscript: getfirstparagraph, contenturl: "http://en.wikipedia.org/wiki/chalk" }); pageworker.port.on("loaded...
request - Archive of obsolete content
rpreted as latin-1, use overridemimetype: var request = require("sdk/request").request; var quijote = request({ url: "http://www.latin1files.org/quijote.txt", overridemimetype: "text/plain; charset=latin1", oncomplete: function (response) { console.log(response.text); } }); quijote.get(); anonymous boolean if true, the request will be sent without cookies or authentication headers.
selection - Archive of obsolete content
private windows if your add-on has not opted into private browsing, then you won't see any selections made in tabs that are hosted by private browser windows.
simple-prefs - Archive of obsolete content
by default, simple preferences are stored in a preference like: extensions.<addon-id>.<preference-name> for example, if you had a simple-pref named "somepreference" then you could get its value like so: require('sdk/preferences/service').get(['extensions', require('sdk/self').id, 'somepreference'].join('.')) this would give you the same value as: require('sdk/simple-prefs').prefs['somepreference'] the ability to change the default preferences branch is new in add-on sdk 1.15.
simple-storage - Archive of obsolete content
if you don't close firefox normally, then simple storage will not be notified that the session is finished, and will not write your data to the backing store.
ui - Archive of obsolete content
this can then be added to a designated area of the firefox user interface.
content/symbiont - Archive of obsolete content
you map optionally pass a frame into the symbiont's constructor: if you don't, then a new hidden frame will be created to host the content.
event/target - Archive of obsolete content
if there is no listener registered for error event or if it also throws exception then such exceptions are logged into a console.
frame/hidden-frame - Archive of obsolete content
the following code creates a hidden frame, loads a web page into it, and then logs its title: var hiddenframes = require("sdk/frame/hidden-frame"); let hiddenframe = hiddenframes.add(hiddenframes.hiddenframe({ onready: function() { this.element.contentwindow.location = "http://www.mozilla.org/"; let self = this; this.element.addeventlistener("domcontentloaded", function() { console.log(self.element.contentdocument.title); }, true, true); } })); ...
io/file - Archive of obsolete content
unfortunately this api does not currently provide a way to obtain an absolute base path which you could then use with join.
loader/sandbox - Archive of obsolete content
omitted or null: then the sandbox will have chrome privileges giving it access to all the xpcom components.
places/favicon - Archive of obsolete content
let { getfavicon } = require("sdk/places/favicon"); // string example getfavicon("http://mozilla.org").then(function (url) { console.log(url); // http://mozorg.cdn.mozilla.net/media/img/favicon.ico }); // tab example require("sdk/tabs").open({ url: "http://mozilla.org", onready: function (tab) { getfavicon(tab).then(function (url) { console.log(url); // http://mozorg.cdn.mozilla.net/media/img/favicon.ico }); } }); // an optional callback can be provided to handle // the promise'...
system/unload - Archive of obsolete content
if object does not have the expected destructor method, then an exception is thrown when ensure() is called.
tabs/utils - Archive of obsolete content
however, if your add-on has not opted into private browsing, then the function will exclude all tabs that are hosted by private browser windows.
test/runner - Archive of obsolete content
this module contains the package's main program, which does a bit of high-level setup and then delegates test finding and running to the harness module.
ui/toolbar - Archive of obsolete content
hidden state persists even over create/destroy cycles: if a toolbar is created, then hidden, then destroyed, and another toolbar with the same title is then created, the new toolbar will be in the hidden state.
util/deprecate - Archive of obsolete content
globals functions deprecatefunction(fun, msg) dump to the console the error message given in the second argument, prefixed with "deprecated:", and print the stacktrace; then execute the function passed as first argument and returns its value.
package.json - Archive of obsolete content
if this value is not true or is omitted, then the add-on will not see any private windows or objects, such as tabs, that are associated with private windows.
Add a Context Menu Item - Archive of obsolete content
in this case the script listens for the user to click on the item, then sends a message to the add-on containing the selected text.
Adding a Button to the Toolbar - Archive of obsolete content
create a directory called "data", mkdir data and save these three icon files to the "data" directory: icon-16.png icon-32.png icon-64.png then open the file called "index.js" in the root of your addon directory and add the following code to it: var buttons = require('sdk/ui/button/action'); var tabs = require("sdk/tabs"); var button = buttons.actionbutton({ id: "mozilla-link", label: "visit mozilla", icon: { "16": "./icon-16.png", "32": "./icon-32.png", "64": "./icon-64.png" }, onclick: handleclick }); function ...
Displaying annotations - Archive of obsolete content
then in the module's scope implement a function to update the matcher's workers, and edit handlenewannotation to call this new function when the user enters a new annotation: function updatematchers() { matchers.foreach(function (matcher) { matcher.postmessage(simplestorage.storage.annotations); }); } function handlenewannotation(annotationtext, anchor) { var newannotation = new annotation...
Overview - Archive of obsolete content
if we do this, then the add-on won't see any private windows, and the annotator's widget will not appear in any private windows.
Storing annotations - Archive of obsolete content
activate the add-on, add an annotation, and then right-click the widget.
Annotator - Archive of obsolete content
next we'll give a quick overview of the annotator's design, then go through the implementation, step by step.
Creating Reusable Modules - Archive of obsolete content
you then import and use these modules from other parts of your add-on using the require() statement, in exactly that same way that you import core sdk modules like page-mod or panel.
Getting Started (jpm) - Archive of obsolete content
navigate to it, type jpm init, and hit enter: mkdir my-addon cd my-addon jpm init you'll then be asked to supply some information about your add-on: this will be used to create your add-on's package.json file.
Modifying Web Pages Based on URL - Archive of obsolete content
$("body").html("<h1>page matches ruleset</h1>"); then download jquery to add-on's data directory, and load the script and jquery together (making sure to load jquery first).
Using XPCOM without chrome - Archive of obsolete content
we can then create an object from it and add it as an observer to the bookmarks service.
Using third-party modules (jpm) - Archive of obsolete content
then, under show / hide toolbars, enable the menu bar.
Canvas code snippets - Archive of obsolete content
var canvas = document.createelement('canvas'); var ctxt = canvas.getcontext('2d'); function loadimagefile(url, callback) { var image = new image(); image.src = url; return new promise((accept, reject) => { image.onload = accept; image.onerror = reject; }).then(accept => { canvas.width = this.width; canvas.height = this.height; ctxt.clearrect(0, 0, this.width, this.height); ctxt.drawimage(this, 0, 0); accept(canvas.todataurl()); }); } usage: loadimagefile('myimage.jpg').then(string64 => { alert(string64); }); if you want to get instead the base64 content of a local file using the file <input> element, you must use the fileread...
Drag & Drop - Archive of obsolete content
} function _dragdrop(aevent) { var dragservice = components.classes["@mozilla.org/widget/dragservice;1"].getservice(components.interfaces.nsidragservice); var dragsession = dragservice.getcurrentsession(); var _ios = components.classes['@mozilla.org/network/io-service;1'].getservice(components.interfaces.nsiioservice); var uris = new array(); // if sourcenode is not null, then the drop was from inside the application if (dragsession.sourcenode) return; // setup a transfer item to retrieve the file data var trans = components.classes["@mozilla.org/widget/transferable;1"].createinstance(components.interfaces.nsitransferable); trans.adddataflavor("text/x-moz-url"); trans.adddataflavor("application/x-moz-file"); for (var i=0; i<dragsession.n...
JS XPCOM - Archive of obsolete content
getting an xpcom service var preferences = components.classes["@mozilla.org/preferences-service;1"] .getservice(components.interfaces.nsiprefservice); you can then call any methods in the nsiprefservice interface on the preferences object.
JavaScript Debugger Service - Archive of obsolete content
(jsdifilter.flag_enabled | jsdifilter.flag_pass) : jsdifilter.flag_enabled, urlpattern: pattern, startline: 0, endline: 0 }; return filter; }, we then add the filters we want.
Sidebar - Archive of obsolete content
for this snippet to work, you have to declare mainwindow as in the previous code block then write: mainwindow.document.getelementbyid("sidebar-splitter").hidden = true; be aware that if you change the splitter's hidden attribute, you need to reset it to a safe value when your sidebar is closed, or replaced by another sidebar.
Toolbar - Archive of obsolete content
@optional */ function installbutton(toolbarid, id, afterid) { if (!document.getelementbyid(id)) { var toolbar = document.getelementbyid(toolbarid); // if no afterid is given, then append the item to the toolbar var before = null; if (afterid) { let elem = document.getelementbyid(afterid); if (elem && elem.parentnode == toolbar) before = elem.nextelementsibling; } toolbar.insertitem(id, before); toolbar.setattribute("currentset", toolbar.currentset); document.persist(toolbar.id, "curren...
Tree - Archive of obsolete content
you can then use the event and some utility methods to find the <treecell>.
Common Pitfalls - Archive of obsolete content
it's important to create the uri correctly, and then check that it's secure to load.
Communication between HTML and your extension - Archive of obsolete content
what i wanted to do was have an extension "look" for something on an html page and if it found that something perform some operation on the found thing and then update the status bar with the results of the operation.
Custom about: URLs - Archive of obsolete content
} and then on shutdown of your bootstrapped addon make sure to destroy the factory: function shutdown(adata, areason) { if (areason == app_shutdown) { return } // ...
Displaying web content in an extension without security issues - Archive of obsolete content
the issue that is commonly overlooked here is that the rss feed could contain some malicious javascript code and it would then execute with the privileges of the extension — meaning that it would get full access to the browser (cookies, history etc) and to user’s files.
Downloading JSON and JavaScript in extensions - Archive of obsolete content
downloading json if the extension is downloading json, then the developer should be using one of the json decoding methods discussed here and not using eval() at all.
Extension Etiquette - Archive of obsolete content
preferences' internal names internal firefox preference names for extensions or to be clear, the name of the preference as it appears in the about:config, should start with "extensions.," then the name of the extension, with a dot, then the name of the preference.
Hiding browser chrome - Archive of obsolete content
var prevfunc = xulbrowserwindow.hidechromeforlocation; xulbrowserwindow.hidechromeforlocation = function(alocation) { return (/* your test goes here */) || prevfunc.apply(xulbrowserwindow, [alocation]); } this works by saving a reference to the current implementation of the hidechromeforlocation() method, then replacing it with a new method that calls through to the previous implementation.
Install Manifests - Archive of obsolete content
if an extension includes the following then it must request unpacking: binary xpcom components plugins search plugins dlls loaded with ctypes dictionaries window icons examples <description about="urn:mozilla:install-manifest"> <em:id>extension@mysite.com</em:id> <em:unpack>true</em:unpack> ...
Installing Extensions and Themes From Web Pages - Archive of obsolete content
installtrigger.install is then called to install the item with the parameter block.
Interaction between privileged and non-privileged pages - Archive of obsolete content
you can optionally clean up the created element, or create it once when the web page loads then re-use it each time.
Jetpack Processes - Archive of obsolete content
oninvalidate a callback to call when the handle is garbage collected, either through an explicit call to invalidate() or being unrooted and then unreachable.
Listening to events in Firefox extensions - Archive of obsolete content
if the page contains frames, then when the cached page is loaded: pageshow events from each frame fire before the pageshow event in the main document fires.
Chapter 4: Using XPCOM—Implementing advanced processes - Archive of obsolete content
listing 5 shows how to get a summary of all browser windows in firefox and then close them.
Adding Toolbars and Toolbar Buttons - Archive of obsolete content
we've already mentioned this before, and if you follow our recommendations, then you shouldn't have many problems making your toolbar compatible with the customize toolbars dialog.
Adding menus and submenus - Archive of obsolete content
on other systems you would be able to see the item update itself without having to close the menu and then reopen.
Appendix A: Add-on Performance - Archive of obsolete content
if there's anything you can unload before shutdown, or if there's anything you can do to unload things more efficiently, then it's important that you do.
Intercepting Page Loads - Archive of obsolete content
we register and unregister the progress listeners for the first tab manually, and then add tab open and close event listeners so we can keep track of the rest of the listeners for all the tabs.
Setting Up a Development Environment - Archive of obsolete content
you can do this by opening the automator application, choosing run shell script and then entering the profile-loading script in the textbox: /applications/firefox.app/contents/macos/firefox-bin -no-remote -p myprofile > /dev/null & you can change "/dev/null" to a file location, in case you want to see dump output from firefox, or other extensions.
User Notifications and Alerts - Archive of obsolete content
if none of those fit your needs then this is an acceptable solution.
Security best practices in extensions - Archive of obsolete content
some items mentioned are strict guidelines, meaning that if you don't follow them then your add-on will not be approved on mozilla add-ons.
Updating addons broken by private browsing changes - Archive of obsolete content
20: nsiprivatebrowsingservice nsirecentbadcertservice furthermore, if your code uses any of these common chrome apis: ff 19: saveurl saveinternal openlinkin ff 20: openbrowserwindow gprivatebrowsingui finally, if your code watches for any of these observer notifications: private-browsing private-browsing-cancel-vote private-browsing-change-granted private-browsing-transition-complete then your addon will require updating to correctly support the new per-window private browser feature in firefox 20 (and will require updating to work correctly in releases of firefox since the ones listed).
Add-ons - Archive of obsolete content
some items mentioned are strict guidelines, meaning that if you don't follow them then your add-on will not be approved on mozilla add-ons.
Adding preferences to an extension - Archive of obsolete content
inside that, we create a file, defaults.js, that describes the default value of our preferences: pref("extensions.stockwatcher2.symbol", "goog"); the standard for third-party preferences, such as those used in extensions, is to use the string "extensions", a period, the name of the extension, another period, then a preference name, as seen in the example above.
Creating a status bar extension - Archive of obsolete content
then restart firefox, and you should see the extension in the status bar.
chargingchange - Archive of obsolete content
example navigator.getbattery().then(function(battery) { console.log("battery charging?
chargingtimechange - Archive of obsolete content
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
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
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 ...
Getting the page URL in NPAPI plugin - Archive of obsolete content
then you can just refuse to do anything, if you don't like the url, or you can compare it with the other url you want to contact.
Index of archived content - Archive of obsolete content
api plug-in side api npanycallbackstruct npbyterange npclass npembedprint npevent npfullprint npidentifier npn newstream npnvariable npn_createobject npn_destroystream npn_enumerate npn_evaluate npn_forceredraw npn_getauthenticationinfo npn_getintidentifier npn_getproperty npn_getstringidentifier npn_getstringidentifiers npn_geturl npn_geturlnotify npn_getvalue npn_getvalueforurl npn_hasmethod npn_hasproperty npn_identifierisstring npn_intfromidentifier npn_invali...
cert_override.txt - Archive of obsolete content
since there is no way to add easily an exception in a xulrunner 1.9 project, you can open the page in firefox, accept the certificate, then copy the cert_override.txt to the xulrunner application profile.
Defining Cross-Browser Tooltips - Archive of obsolete content
this assumes that the browser can find the image and that it supports the image format used; if either of these is not true, and the image cannot be displayed, then the alt text should be displayed in place of the missing image.
Environment variables affecting crash reporting - Archive of obsolete content
moz_crashreporter_shutdown save the minidump and then force the application to close.
Using XML Data Islands in Mozilla - Archive of obsolete content
for example, a simple xml purchase order can be embedded like this: <script id="purchase-order" type="application/xml"> <purchaseorder xmlns="http://example.mozilla.org/purchaseorderml"> <lineitem> <name>line item 1</name> <price>1.25</price> </lineitem> <lineitem> <name>line item 2</name> <price>2.48</price> </lineitem> </purchaseorder> </script> the xml source text can then be retrieved like this: var ordersource = document.getelementbyid("purchase-order").textcontent; the xml source text can be parsed into a dom tree using the domparser api: var parser = new domparser(); var doc = parser.parsefromstring(ordersource, "application/xml"); the html5 data block-based way shown here works in firefox, opera, webkit-based browsers such as chrome and safari, and ie9 while ...
Using content preferences - Archive of obsolete content
example: setting and retrieving preferences this example demonstrates how to save a preference and then retrieve its value.
ActiveX Control for Hosting Netscape Plug-ins in IE - Archive of obsolete content
a note to developers if you intend to modify this control in any way then you must also change the clsid from {dbb2de32-61f1-4f7f-beb8-a37f5bc24ee2} to something else and any other guids this control relies upon (iid, libids etc).
Bookmark Keywords - Archive of obsolete content
however, the two should not be a case-sensitive match-- that is, if your keyword is av, then your title should be "av" or "av" or anything besides "av." (see bugzilla entry 119201 for details.) since this bookmark is intended to look up bugzilla entries, we'll call it "bz," as shown in figure 3.
Structure of an installable bundle - Archive of obsolete content
jar files are used, each platform directory should have its own chrome.manifest file: chrome.manifest chrome/mytheme-base.jar platform/darwin/chrome.manifest platform/darwin/chrome/mytheme-mac.jar platform/winnt/chrome.manifest platform/winnt/chrome/mytheme-win.jar the app/extension loader processes the base directory first, followed by the applicable platform directories (first /{os_target}/, then /{os_target}_{target_xpcom_abi}/).
Enabling the behavior - retrieving tinderbox status - Archive of obsolete content
we use new to create a new instance of it, set the instance's onload property to updatetinderboxstatus(), the function we want to execute when the document finishes loading, call its open method with the type of http request we want to make and the url of the document to retrieve, and then call its send method to send the request.
Enabling the behavior - updating the status bar panel - Archive of obsolete content
sponsetext.match("ee0000")) icon.setattribute("status", "busted"); else if (gxmlhttprequest.responsetext.match("ffaa00")) icon.setattribute("status", "testfailed"); else if (gxmlhttprequest.responsetext.match("11dd11")) icon.setattribute("status", "success"); else icon.setattribute("status", ""); } updatetinderboxstatus() retrieves a reference to the statusbarpanel element then searches through the retrieved html document (stored in the responsetext property of the xmlhttprequest instance) for one of several color references.
Specifying the appearance - Archive of obsolete content
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-bus...
chrome.manifest - Archive of obsolete content
copy the following text and paste it into a text file, then save that 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/ ...
install.rdf - Archive of obsolete content
copy the following text and paste it into a text file, then save that file as "install.rdf": <?xml version="1.0"?> <rdf xmlns="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:em="http://www.mozilla.org/2004/em-rdf#"> <description about="urn:mozilla:install-manifest"> <em:id>author@oftheme.com</em:id> <em:version>2.0b1</em:version> <!-- seamonkey --> <em:targetapplication> <description> <em:id>{92650c4d-4b8e-4d2a-b7eb-24ecf4f6b63a}</em:id> <em:minversion>2.0b1pre</em:minversion> <em:maxversion>2.0b2pre</em:maxversion> </description> </em:targetapplication> <!-- front end metadata --> <em:name>my_theme</em:name> <em:description>my first theme</em:description> <!-- front end integration hooks (used by t...
FAQ - Archive of obsolete content
in the case of skins the access key that you are defining is accessible by going to edit->preferences, appearance->themes, and then pressing a letter.
contents.rdf - Archive of obsolete content
copy the following text and paste it into a text file, then save that file as "contents.rdf": <?xml version="1.0"?> <rdf:rdf xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:chrome="http://www.mozilla.org/rdf/chrome#"> <!-- list all the skins being supplied by this theme --> <rdf:seq about="urn:mozilla:skin:root"> <rdf:li resource="urn:mozilla:skin:myskin/1.0" /> </rdf:seq> <rdf:description about="urn:mozilla:skin:myskin/1.0" chrome:displayname="my skin" chrome:accesskey="m" chrome:author="me" chrome:description="this is my custom skin for mozilla" chrome:name="myskin/1.0" chrome:image="preview.png"> <chrome:packages> <rdf:seq about="urn:mozilla:skin:myskin/1.0:packages"> <rdf:li resource="...
toolbarBindings.xml - Archive of obsolete content
copy the following text and paste it into a text file, then save that file as "toolbarbindings.xml": <bindings id="toolbarbindings"> <binding id="toolbar-primary" extends="chrome://global/content/bindings/toolbar.xml#toolbar-primary"> <content> <xul:hbox class="toolbar-holder toolbar-primary-holder" flex="1" xbl:inherits="orient=tborient,buttonstyle"> <xul:hbox class="toolbar-button-box" flex="1"> <children/> </xul:hbox> <xul:image class="toolbar-primary-icon" xbl:inherits="buttonstyle"/> </xul:hbox> </content> </binding> </bindings> ...
Dehydra Function Reference - Archive of obsolete content
if a property is not specified then it will not be passed to the runtime.
Developing New Mozilla Features - Archive of obsolete content
if you absolutely don't have the resources to do this, then plan for extra integration time.
Editor Embedding Guide - Archive of obsolete content
then simply call nsiwebbrowser->do_getinterface on the nsiwebbrowser to retrieve the nsieditingsession from it.
Embedding FAQ - Archive of obsolete content
then pass the object to your xpcom coded object and call it from c++.
Building Firefox with Rust code - Archive of obsolete content
if you have new rust libraries that code in libxul calls directly, then you should add the appropriate extern crate lines in toolkit/library/rust/shared/lib.rs, and add those libraries (crates) as dependencies in toolkit/library/rust/cargo.toml.
Downloading Nightly or Trunk Builds - Archive of obsolete content
if one has questions about the way a particular nightly was built, the best way to get that information is to download the executable, launch it, and then go to the "about:buildconfig" page, by typing this into the location bar.
Layout FAQ - Archive of obsolete content
if you're on linux, then you can try using jprof.
Repackaging Firefox - Archive of obsolete content
it is possible to set a value for localizable preferences directly in the partner.js file, like this: pref("localizable.preference.name", "data:text/plain,localizable.preference.name=some value."); then, a properties file is not used (or needed at all) for that preference.
Code snippets - Archive of obsolete content
to access a chrome-privileged console, open an about page (like about:about) then open a web console via the web developer menu.
Help Viewer - Archive of obsolete content
naturally, then, everyone needs a little help now and then, and getting that help to the user is critical to making applications useful.
Helper Apps (and a bit of Save As) - Archive of obsolete content
nsexternalapphandler::onstoprequest set a flag that we're done, then do whatever the user wants if the user has decided (save to disk and open in helper are the current options the user has).
popChallengeResponse - Archive of obsolete content
challenge ::= sequence { owf algorithmidentifier optional, -- must be present in the first challenge; may be omitted in any -- subsequent challenge in popodeckeychallcontent (if omitted, -- then the owf used in the immediately preceding challenge is -- to be used).
Jetpack Snippets - Archive of obsolete content
se firebug onselect: function(slide) { slide.slide(800, true); }}); calling into a slidebar from the global jetpack scope jetpack.slidebar.append({ onready: function (slide) { // call out to a global function, passing the slidebar object exinitslidebar(slide); }, ...});function exinitslidebar(aslidebar) { // this variable will now be global slider = aslidebar;} // then, accessing the slidebar htmlvar tl = slider.contentdocument.getelementbyid("thumblist"); // or calling slidebar api methods or accessing propertiesslider.notify(); ...
Litmus tests - Archive of obsolete content
these were developed before litmus, but then pulled in.
Makefile.mozextension.2 - Archive of obsolete content
then again if you do that, all of the < > will be quoted as & lt ; so again it will be corrupt :( therefore, here is a direct link to this makefile: makefile.mozextension2 ## file: makefile.mozextension2 ## based on http://kb.mozillazine.org/makefile_for_packaging_an_extension ## "this makefile.mozextention is for the test extension" ## the original makefile.mozextention reconstructs http://kb.moz...
Plug-n-Hack Get Involved - Archive of obsolete content
if you would like to add pnh support to a browser or tool, or even get involved in onward pnh development, then please get in touch and we will give you whatever assistance we can.
Plug-n-Hack Phase2 - Archive of obsolete content
if you are interested in working on this aspect then please get in touch.
Build - Archive of obsolete content
to build prism, you must first build the xulrunner tree, and then build prism.
Extensions - Archive of obsolete content
then install the extension by either dragging and dropping the extension onto the dialog, or by clicking the “install…” button, navigating to the extension and selecting it for installation.
FAQ - Archive of obsolete content
ArchiveMozillaPrismFAQ
prism is the codename for the project, and if the functionality provided by prism becomes a product or is integrated into other products (like firefox), then it won't necessarily continue to be called by this codename.
Hacking wiki - Archive of obsolete content
random tips you can set the file to log by putting something like this in your localsettings.php: $wgdebuglogfile = 'c:\\123'; you can then use wfdebug() function to write to the log.
Remotely debugging Firefox for Metro - Archive of obsolete content
if you are connecting to firefox for metro on a different computer or a different port, enter the appropriate hostname and port number and then press "connect." in the windows 8 (metro) browser next you'll see a dialog in firefox for metro asking you to confirm the connection.
Remote debugging - Archive of obsolete content
you can then load the core file into gdb (gdb firefox-bin corefile), and it will be as if you caught the crash while running firefox under gdb!
Standard Makefile Header - Archive of obsolete content
this header sets variables which tell the makefile where it is and where the source directory is, and then include autoconf.mk, to pick up makefile variables which are set during configuration.
Static Analysis for Windows Code under Linux - Archive of obsolete content
moztools position glib_prefix=$home/moztools libidl_prefix=$home/moztools #disable xpcom stdcall calling convention because of gcc 4.3.0 bug cppflags="-dmoz_disable_xpcom_stdcall" #specify the cxx and static analysis #point cxx to the cross compile g++ with plugin support cxx=$home/mingw-install/bin/i686-mingw32-g++ ac_add_options --with-static-checking=$home/dehydra/dehydra-gcc/gcc_dehydra.so then, you can start building your mozilla.
Running Tamarin acceptance tests - Archive of obsolete content
can also be using in conjunction with --threads -f --forcerebuild force rebuild all test files -q --quiet : will print a period (.) for each test run regardless of results, then print the test run summary when finished --ascargs= : additional arguments to pass to asc.jar --vmargs= : additional arguments to pass to avmshell --random : run tests in random order --timeout : max time for testrun --verify : run a verify pass instead of running abcs --verifyonly : run a -dverifyonly pass: only checks test exitcode (only works with debugger vms) testing the android shell the ...
Tamarin mercurial commit hook - Archive of obsolete content
installing the commit hook the easiest way to implement the hook is to sync to the tip of tamarin-redux then add the following to your tamarin-redux/.hg/hgrc file (or to ~/.hgrc to implement for all local repos): [hooks] pretxncommit.commit = python:/path/to/tamarin-redux/utils/hooks/tamarin-commit-hook.py:master_hook once added, all commits will run the commit hook.
The new nsString class implementation (1999) - Archive of obsolete content
so, why then am i proposing this?
Tuning Pageload - Archive of obsolete content
in particular, the way things work right now is that the parser and content sink construct the dom; then every so often, the content sink lets the rendering model constructor (nscssframeconstructor) know that there are new dom nodes.
Using cross commit - Archive of obsolete content
if you don't, however, then from the parent directory of your source dir, do: cvs co mozilla/tools/cross-commit note that you will need to have $cvsroot and such set up correctly for this to work.
Venkman Internals - Archive of obsolete content
to obtain the antecedent files: doc.getelementsbytagname("script"); then extract the urls from the src attributes.
DOM Interfaces - Archive of obsolete content
the binding document can then be modified programmatically using the dom.
Mac stub installer - Archive of obsolete content
then add the componentx into the appropriate setup types so the installer module installs when users select the setup types you choose it to be in.
Windows stub installer - Archive of obsolete content
then add the component <component> into the appropriate setup types so the installer module installs it when users select the setup types you choose it to be in.
Install Wizards (aka: Stub Installers) - Archive of obsolete content
it then proceeds to extract the xpinstall engine and feed it the downloaded software packages to install.) the stub installer code includes: the logic to display the install wizard widgets and dialogs the code that reads in the configuration file (config.ini) and dynamically installs from the net or from local xpi modules found next to the installer binary the code that processes user selections th...
Install script template - Archive of obsolete content
* * @param empty param list **/ function createsecondaryinstall() { // use getfolder in such a way that it creates c:\winnt\system32\myplugin secondaryfolder = getfolder("win system", company_name); // if secondaryfolder is null, then there has been an error if(!secondaryfolder) return nosecondaryinstall; else { // we have admin privileges to write to the win system directory // so we will set up dll and xpt in their new home errblock2 = addfile (plid, version, plugin_file, secondaryfolder, null); // something went wrong if errblock2 is not 0 if (errblock2!=0) { logcomment("could not add " + plugin_file...
InstallTrigger.startSoftwareUpdate - Archive of obsolete content
then do: ...
alert - Archive of obsolete content
if message is not a string, then it is converted into one and displayed.
confirm - Archive of obsolete content
the value is calculated by multiplying the corresponding button position constant with a button title constant for each button, then adding the results and any additional options (see other constants).
execute - Archive of obsolete content
executing installed files note: if the file you wish to execute is one you are installing (as opposed to an installer executable that you plan to delete once it runs), then use the execute method on the file object instead.
Properties - Archive of obsolete content
and then the rg string to the xpi url: (e.g.
XPInstall - Archive of obsolete content
creating xpi installer modules this article describes the packaging scheme of the mozilla and offers a tutorial for creating a new package that can then be redistributed, installed, and made available to users.
highlightnonmatches - Archive of obsolete content
« xul reference home highlightnonmatches new in thunderbird 3 requires seamonkey 2.0 type: boolean if true, then the autocomplete field will be highlighted when no match has been found.
norestorefocus - Archive of obsolete content
« xul reference home norestorefocus type: boolean if false, the default value, then when the panel is hidden, the keyboard focus will be restored to whatever had the focus before the panel was opened.
collapsed - Archive of obsolete content
« xul reference home collapsed type: boolean if true, then the element is collapsed and does not appear.
cycler - Archive of obsolete content
« xul reference home cycler type: boolean if true, then the column is a cycler column.
readonly - Archive of obsolete content
« xul reference home readonly type: boolean if set to true, then the user cannot change the value of the element.
reserved - Archive of obsolete content
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("intercepted accel-t"); // prevent the default browser action event.preventdefault(); ...
right - Archive of obsolete content
the stack is then enlarged to include the element.
textbox.type - Archive of obsolete content
if you have <binding id="input" extends="chrome://global/content/bindings/autocomplete.xml#autocomplete" >, then the textbox will have autocomplete type, regardless of tree's 'type' attribute.
treecol.type - Archive of obsolete content
if you are using type="checkbox", then the tree and each treecol must be editable.
Dynamically modifying XUL-based user interface - Archive of obsolete content
it explains the concept of dom documents, demonstrates a few simple examples of using dom calls to perform basic manipulations on a document, and then demonstrates working with anonymous xbl content using mozilla-specific methods.
XUL Events - Archive of obsolete content
when the user presses a key, the keydown event is sent first, followed by the keypress event and then the keyup event.
Working With Directories - Archive of obsolete content
if the directory already exists, then no action is taken.
Uploading and Downloading Files - Archive of obsolete content
the formdata object can then simply be passed to xmlhttprequest: function upload(posturl, fieldname, filepath) { var formdata = new formdata(); formdata.append(fieldname, new file(filepath)); var req = new xmlhttprequest(); req.open("post", posturl); req.onload = function(event) { alert(event.target.responsetext); }; req.send(formdata); } http put you can also upload a file using an http put operation.
Writing to Files - Archive of obsolete content
to create an input stream, first get a reference to a nsifile, and then use nsiscriptableio.newoutputstream() to open a stream for writing to it.
IO - Archive of obsolete content
ArchiveMozillaXULFileGuideIO
if the name 'subdirname' refers to a directory, then the returned object will refer to this directory.
insertItemAt - Archive of obsolete content
note: you cannot insert an item to an index that does not exist, eg: trying to insert an item at the end with element.getrowcount() + 1 example <!-- this example inserts at the selected item or appends, then selects the newly created item --> <script language="javascript"> function insertitemtolist(){ var mylistbox = document.getelementbyid('mylistbox'); // create a date to get some labels and values var somedate = new date(); if(mylistbox.selectedindex == -1){ // no item was selected in list so append to the end mylistbox.appenditem( somedate.tolocaletimestring(), ...
Tooltips - Archive of obsolete content
this label is then set as the value of the last child of the tooltip.
readOnly - Archive of obsolete content
« xul reference readonly type: boolean if set to true, then the user cannot modify the value of the element.
smoothScroll - Archive of obsolete content
if not set explicitly, it will fall back to the smoothscroll attribute and then to the toolkit.scrollbox.smoothscroll preference.
uri - Archive of obsolete content
ArchiveMozillaXULPropertyuri
then, the other rules are evaluated for a match.
Actions - Archive of obsolete content
then, the remaining attributes on the element are examined and any variables are replaced in place.
Additional Navigation - Archive of obsolete content
we can then display these results using the following action body.
Attribute Substitution - Archive of obsolete content
for instance, if the value of ?name is 'jake', then the attribute value will be 'my name is jake'.
Containment Properties - Archive of obsolete content
if the resource 'http://www.xulplanet.com/rdf/a' was also an rdf seq with some children, then those children would also be added to the results.
Multiple Queries - Archive of obsolete content
here are the results that would be generated by the first query above, before any bindings are applied: (?start = http://www.xulplanet.com/rdf/myphotos, ?photo = http://www.xulplanet.com/ndeakin/images/t/canal.jpg, then, the builder adds the three results generated from the second query: (?start = http://www.xulplanet.com/rdf/myphotos, ?photo = http://www.xulplanet.com/ndeakin/images/t/canal.jpg) (?start = http://www.xulplanet.com/rdf/myphotos, ?photo = http://www.xulplanet.com/ndeakin/images/t/palace.jpg) (?start = http://www.xulplanet.com/rdf/myphotos, ?photo = http://www.xulplanet.com/ndeakin/images/t/can...
Namespaces - Archive of obsolete content
e"/> <person name="ferdinand magellan" gender="male"/> <person name="laura secord" gender="female"/> </people> <listbox datasources="people.xml" ref="*" querytype="xml"> <template xmlns:ns="www.example.com/people"> <query expr="ns:person"/> <action> <listitem uri="?" label="?ns:name"/> </action> </template> </listbox> once added to the template element the namespaces can then be referenced inside temple rule elements too, this works both in rdf and xml templates.
Recursive Generation - Archive of obsolete content
to begin, b is evaluated and seeded with the right value: (?start = http://www.xulplanet.com/rdf/b) the <triple> statement is then examined, however, item b doesn't have a relateditem arc out of it, so the result is rejected.
Result Generation - Archive of obsolete content
or you could start at b and go to a and then go to c and d, etc.
Rule Compilation - Archive of obsolete content
this will return a table of result records which are then used to generate output.
Special Condition Tests - Archive of obsolete content
<template> <query expr="*"/> <rule parent="vbox"> <action> <groupbox uri="?"> <caption label="?name"/> </groupbox> </action> </rule> <rule> <action> <label uri="?" value="?name"/> </action> </rule> </template> </vbox> previously, an assign element was used to assign the tagname of the result to a variable, which was then compared in a rule condition.
Template Builder Interface - Archive of obsolete content
then, the method recompiles the query and the rules and regenerates the content.
Template Logging - Archive of obsolete content
if null, then the datasource could not be loaded, or hasn't yet been loaded.
Using Multiple Queries to Generate More Results - Archive of obsolete content
esource="http://www.xulplanet.com/rdf/person/1"/> <rdf:li rdf:resource="http://www.xulplanet.com/rdf/person/2"/> </rdf:seq> </r:people> </rdf:description> <rdf:description rdf:about="http://www.xulplanet.com/rdf/person/1" dc:title="nathan"/> <rdf:description rdf:about="http://www.xulplanet.com/rdf/person/2" dc:title="karen"/> we can then use two queries to generate results from different parts of the datasource.
XML Assignments - Archive of obsolete content
the two variable assignments may then be used in the action body to replace attributes in the generated content.
Things I've tried to do with XUL - Archive of obsolete content
instead, you must build up your own listitem full of listcells, and then add that listitem to the listbox, using generic dom calls: var row = document.createelement('listitem'); // create and attach 1st cell var cell = document.createelement('listcell'); cell.setattribute('label', label ); cell.setattribute('value', value ); row.appendchild( cell ); // create and attach 2nd cell cell = document.createelement('listcell'); cell.setattribute('label', label2 ); cell.seta...
Tree Widget Changes - Archive of obsolete content
<treecol type="checkbox"> you can then set or clear the checkbox for a particular cell in that column by setting the value attribute to true, or leaving out the attribute.
Accesskey display rules - Archive of obsolete content
then, you should provide a way for specifying accesskeys which are independent from their labels.
Adding HTML Elements - Archive of obsolete content
here is an example as it might be added to the find file window: <?xml version="1.0"?> <?xml-stylesheet href="chrome://global/skin/" type="text/css"?> <window id="findfile-window" title="find files" orient="horizontal" xmlns:html="http://www.w3.org/1999/xhtml" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> then, you can use html tags as you would normally, keeping in mind the following: you must add a html: prefix to the beginning of each tag, assuming you declared the html namespace as above.
Creating a Window - Archive of obsolete content
if it does not exist, then it needs to be created and set to |true|.
Cross Package Overlays - Archive of obsolete content
then add items, one for each window that you want the overlay to apply to.
Element Positioning - Archive of obsolete content
then, when you make the window wider, extra space will be available, so the box will grow to fill the extra space.
Keyboard Shortcuts - Archive of obsolete content
the docopy function should check to see if text is selected and then copy the text to the clipboard.
List Controls - Archive of obsolete content
you can then use the value in a script.
More Button Features - Archive of obsolete content
the image is loaded from the url, which can be a relative or absolute url, and then the image is displayed on the button.
More Tree Features - Archive of obsolete content
you can then add items inside that to specify the child rows of an item.
More Wizards - Archive of obsolete content
then, to navigate to a page, use one of two methods: set the next attribute on each page to the page id of the next page to go to.
Open and Save Dialogs - Archive of obsolete content
(returnok will be returned when the user entered the name of a new file.) you should check the return value and then get the file object from the file picker using the file property.
Persistent Data - Archive of obsolete content
one possibility would be to write a script to collect information about what you would like to save and then save it to a file.
Templates - Archive of obsolete content
you can then enter the chrome url into the browser url field.
The Box Model - Archive of obsolete content
then, the labels are placed inside another box, this time a vertical one, as are the textboxes.
Using Spacers - Archive of obsolete content
<spacer flex="1"/> <button id="find-button" label="find"/> more about flexibility xul lays out elements on a window by calculating suitable widths and heights for the elements and then adding space where they are flexible.
XPCOM Interfaces - Archive of obsolete content
it eliminates the need to create the instance and then query it for an interface in two separate steps.
Using multiple DTDs - Archive of obsolete content
then accessing entities from both dtds would look like this: <button id="somebutton" label="&somebutton.label"> ...
Using spell checking in XUL - Archive of obsolete content
checking the spelling of a word to check the spelling of a word, you must first create an interface to the mozispellcheckingengine component and then call the check() method on the string you wish to test.
Using the standard theme - Archive of obsolete content
</tt> processing instruction for every style sheet you want to associate with your xul file: <?xml-stylesheet href="chrome://global/skin/" type="text/css"?> <?xml-stylesheet href="chrome://myextension/skin/custom.css" type="text/css"?> <tt>@import</tt> chains first, import the global skin in your custom style sheet using the css <tt>@import</tt> rule: @import url("chrome://global/skin/"); you then have to associate your xul file with your custom style sheet only: <?xml-stylesheet href="chrome://myextension/skin/custom.css" type="text/css"?> applying different custom style sheets depending on the selected theme mozilla is able to automatically pick your custom style sheet depending on the theme currently chosen by the user.
XUL element attributes - Archive of obsolete content
collapsed type: boolean if true, then the element is collapsed and does not appear.
Accessibility/XUL Accessibility Reference - Archive of obsolete content
</tabpanel> </tabpanels> focusing the tabbox will visually set focus to the selected tab, then you can select different tabs by using the left and right arrow keys.
XUL Event Propagation - Archive of obsolete content
for example, if an event handler at the menu is handling an event raised by one of the menu items, then the menu should be able to identify the raising element and take the appropriate action, as in the following example, where a javascript function determines which menuitem was selected and responds appropriately: <script> function docmd(el) { v = el.getattribute("value"); if (v == "new") alert("new clicked"); else if (v == "open") alert("open clicked"); else alert("close clicked"); } </s...
arrowscrollbox - Archive of obsolete content
if not set explicitly, it will fall back to the smoothscroll attribute and then to the toolkit.scrollbox.smoothscroll preference.
binding - Archive of obsolete content
that name can then be used within the action of a rule.
content - Archive of obsolete content
then, the other rules are evaluated for a match.
key - Archive of obsolete content
ArchiveMozillaXULkey
if the modifiers attribute is not specified, then no modifiers may be pressed for the key to match.
menuitem - Archive of obsolete content
a workaround is to set the autocheck attribute to false, then programmatically set the checked attribute when the user selects the item, and set it to false instead of removing the attribute (i.e.
menulist - Archive of obsolete content
readonly type: boolean if set to true, then the user cannot change the value of the element.
panel - Archive of obsolete content
ArchiveMozillaXULpanel
norestorefocus type: boolean if false, the default value, then when the panel is hidden, the keyboard focus will be restored to whatever had the focus before the panel was opened.
prefpane - Archive of obsolete content
for example, if you are using a listbox and the user changes the contents of the listbox (such as adding or removing an item) and you want to sync the changes back to a preference, you must write an onsynctopreference handler for your listbox that returns the value to be written to the preference element, and then call the userchangedvalue function every time you edit the list in a way that should cause the preference's value to change.
toolbar - Archive of obsolete content
if the name doesn't exist, then a new window is opened and the specified resource is loaded into its browsing context.">window.open() method.
toolbaritem - Archive of obsolete content
if you don't need the thing you're placing in the toolbar to be customized then it doesn't need to be in a toolbaritem element.
treecol - Archive of obsolete content
for example, for a menuitem in a menu you can add the following css rule when you want to use the value none: menupopup > menuitem, menupopup > menu { max-width: none; } cycler type: boolean if true, then the column is a cycler column.
window - Archive of obsolete content
to add a favicon to the address bar and browser tab (ie dialog is not a popup) then use the following code snippet to use the html namespace and link.
Application Update - Archive of obsolete content
it will then prompt the user to restart the application.
Components - Archive of obsolete content
then you need to make sure that it gets registered.
Creating a Windows Inno Setup installer for XULRunner applications - Archive of obsolete content
don't forget to then test the installed application to be sure the installation did indeed work correctly, since if you accidentally omitted resources from the script, they'll be missing from the installed package.
Custom app bundles for Mac OS X - Archive of obsolete content
mac os x applications are typically packaged as application bundles which are then distributed in .dmg (disk image) files.
How to enable locale switching in a XULRunner application - Archive of obsolete content
it saves the new locale to the user application preferences (thereby overriding the default prefs.js above) and then asks xulrunner to restart.
Using LDAP XPCOM with XULRunner - Archive of obsolete content
} library->setnativeleafname(ns_literal_cstring(krealcomponent)); prlibrary *lib; rv = library->load(&lib); if (ns_failed(rv)) return rv; nsgetmoduleproc getmoduleproc = (nsgetmoduleproc) pr_findfunctionsymbol(lib, ns_get_module_symbol); if (!getmoduleproc) return ns_error_failure; return getmoduleproc(acompmgr, alocation, aresult); } then change your .mozconfig to add this line: ac_add_options --enable-extensions=ldapstub rebuild xulrunner.
ant script to assemble an extension - Archive of obsolete content
file was written by régis décamps <decamps@users.sf.net> <project name="blogmark" default="createxpi"> <property name="version" value="1.3-rc1"/> <property name="description" value="new context-menu item to add the current page in your blogmarks"/> xpi file is created after "chrome/blogmark.jar" is created, which is then stuffed into "blogmark.xpi" <target name="createxpi" depends="createjar" description="assemble the final build blogmark.xpi"> <zip destfile="blogmark-${version}.xpi"> <zipfileset dir="." includes="chrome/blogmark.jar" /> <zipfileset dir="." includes="install.rdf" /> </zip> </target> ...
Gecko Compatibility Handbook - Archive of obsolete content
if you must use the xml empty tag notation, then only do so for html elements that never have any content - not for html elements that have optional ending tags.
2006-10-06 - Archive of obsolete content
he then was able to successfully build thunderbird.
2006-11-10 - Archive of obsolete content
build problem firefox 2.0 on fc3 november 10th: vin downloaded the latest firefox 2 rc3 and tried to build it on fc3 with the following options: ./configure --enable-application=browser --prefix=$prefix --enable-extensions=default,spatialnavigation then he tried running "make" and received the following error: /usr/bin/ld: testtarray.o(.text+0x2237): unresolvable relocation against symbol `nstarray_base::semptyhdr' /usr/bin/ld: final link failed: nonrepresentable section on output collect2: ld returned 1 exit status gmake[3]: *** [testtarray] error 1 gmake[3]: leaving directory `/usr/mozilla2/src/mozilla/xpcom/tests' gmake[2]: *** [libs] error...
2006-10-06 - Archive of obsolete content
dbaron then follows up that bug 354835 is solved so there is no need to close the tree waiting for it.
2006-09-29 - Archive of obsolete content
then use xulrunner -install-app to "unpack" the xul app into the mac structure.
Monitoring plugins - Archive of obsolete content
this component then reports the plugin runtime using the observer service to anyone registered to receive the notifications.
Browser-side plug-in API - Archive of obsolete content
npn_destroystream npn_forceredraw npn_getauthenticationinfo npn_geturl npn_geturlnotify npn_getvalue npn_getvalueforurl npn_invalidaterect npn_invalidateregion npn_memalloc npn_memflush npn_memfree npn_newstream npn_pluginthreadasynccall npn_poppopupsenabledstate npn_posturl npn_posturlnotify npn_pushpopupsenabledstate npn_reloadplugins npn_requestread npn_setvalue npn_setvalueforurl npn_status npn_useragent npn_version ...
NPN_GetValueForURL - Archive of obsolete content
see also npn_setvalueforurl, npn_getauthenticationinfo ...
NPN_PostURLNotify - Archive of obsolete content
values: true: post the local file whose path is specified in buf, then delete the file.
NPN_SetValueForURL - Archive of obsolete content
see also npn_getvalueforurl, npn_getauthenticationinfo ...
NPN_Write - Archive of obsolete content
example this example pushes a snippet of html over a newly created stream, then destroys the stream when it's done.
NPAPI plugin reference - Archive of obsolete content
npn_getauthenticationinfo the function is called by plugins to get http authentication information from the browser.
Shipping a plugin as a Toolkit bundle - Archive of obsolete content
you should aim to use a domain-name that you own and then your own unique short-name for the plugin before the @.
Why RSS Content Module is Popular - Including HTML Contents - Archive of obsolete content
then the <description> would be: <description>this is &lt;b&gt;bold&lt;/b&gt;.</description> note that the "<" has been turned into "&lt;".
Why use RSS - Archive of obsolete content
(too many to list.) and if you syndicate using rss, then all those desktop and web-based rss aggregators will be able to make use of and read your rss feed.
Getting Started - Archive of obsolete content
note: if you are not a web developer and do not want to become one, then this tutorial is not for you.
Confidentiality, Integrity, and Availability - Archive of obsolete content
integrity integrity refers to ensuring the authenticity of information—that information is not altered, and that the source of the information is genuine.
Threats - Archive of obsolete content
information in transit is changed or replaced and then sent on to the recipient.
Common Firefox theme issues and solutions - Archive of obsolete content
you'll probably want to copy the files from the folder browser/devtools/ from the default theme into your theme and then modify as necessary to achieve the desired look.
contents.rdf - Archive of obsolete content
copy the following text and paste it into a text file, then save that file as "contents.rdf": <?xml version="1.0"?> <rdf:rdf xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:chrome="http://www.mozilla.org/rdf/chrome#"> <!-- list all the skins being supplied by this theme --> <rdf:seq about="urn:mozilla:skin:root"> <rdf:li resource="urn:mozilla:skin:my_theme"/> </rdf:seq> <rdf:description about="urn:mozilla:skin:my_theme" chrome:displayname="my theme" chrome:accesskey="n" chrome:author="" chrome:authorurl="" chrome:description="" chrome:name="my_theme" chrome:image="preview.png"> <chrome:packages> <rdf:seq about="urn:mozilla:skin:my_theme:packages"> <rdf:li resource="urn:mozilla:skin:my_t...
install.rdf - Archive of obsolete content
copy the following text and paste it into a text file, then save that file as "install.rdf": <?xml version="1.0"?> <rdf xmlns="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:em="http://www.mozilla.org/2004/em-rdf#"> <description about="urn:mozilla:install-manifest"> <em:id>{themes_uuid}</em:id> <em:version>themes_version</em:version> <!-- target application this extension can install into, with minimum and maximum supported versions.
Making sure your theme works with RTL locales - Archive of obsolete content
example toolbar[iconsize="large"][mode="icons"] #back-button { -moz-image-region: rect(0px 396px 34px 360px); } toolbar[iconsize="large"][mode="icons"] #back-button:-moz-locale-dir(rtl) { -moz-image-region: rect(0px 516px 34px 480px); } this specifies the default, left-to-right version of the button, then offers an override if the user's interface is being rendered in right-to-left mode.
Theme changes in Firefox 4 - Archive of obsolete content
then copy all of icon.png, install.rdf and preview.png from <firefox-app-bundle>/contents/macos/extensions/{...} into my_theme.
Settings - Archive of obsolete content
ignore caught exceptions if this option is set (it is set by default) and "pause on exceptions" is set, then execution will pause on an exception only if that exception is not caught.
Using Firebug and jQuery (Screencast) - Archive of obsolete content
related links: firebug firefox extension jquery javascript library jquery selector documentation digg learning jquery: jquerify bookmarklet if you wish to use greasemonkey instead of a bookmarklet, then by all means, please do so.
Using IO Timeout And Interrupt On NT - Archive of obsolete content
then the thread is put to sleep.
-ms-content-zoom-snap-points - Archive of obsolete content
when a user pans or scrolls and then lifts his or her contact (for instance, a finger), the content can continue to move with inertia.
-ms-content-zoom-snap-type - Archive of obsolete content
when a user pans or scrolls and then lifts his or her contact (for instance, a finger), the content can continue to move with inertia.
-ms-hyphenate-limit-chars - Archive of obsolete content
if the word does not meet the required minimum number of characters in the word, before the hyphen, or after the hyphen, then the word is not hyphenated.
-ms-scroll-limit-x-min - Archive of obsolete content
if the value is negative, then 0 is used.
-ms-scroll-limit-y-min - Archive of obsolete content
if the value is negative, then 0 is used.
CSS - Archive of obsolete content
ArchiveWebCSS
if the word does not meet the required minimum number of characters in the word, before the hyphen, or after the hyphen, then the word is not hyphenated.-ms-hyphenate-limit-linesthe -ms-hyphenate-limit-lines css property is a microsoft extension specifying the maximum number of consecutive lines in an element that may be ended with a hyphenated word.-ms-hyphenate-limit-zonethe -ms-hyphenate-limit-zone css property is a microsoft extension specifying the width of the hyphenation zone.-ms-ime-alignthe -ms-ime-align css pr...
E4X for templating - Archive of obsolete content
re (i.e., without needing return statements and braces): {_if(elems.length(), function () <> <markup/> <markup/> </>)} note that, while it is convenient to store such e4x in separate file templates (to be eval()d at a later time, taking into account security considerations, such as escaping with the above), e4x content using such functions can also be easily serialized inline (and then perhaps converted to the dom) as needed: var list = <>{_if(elems.length(), function () <> <markup/> <markup/> </>)}</>.toxmlstring(); iterating functions such as the following foreach (which can work with arrays, objects, or e4x objects) are quite convenient in iterating over complex structures such as e4x would not normally allow.
Using JavaScript Generators in Firefox - Archive of obsolete content
you can opt in in html as follows: <script type="text/javascript;version=1.7" src="myscript.js"></script> then your myscript.js file might look like this: // need to stash the generator in a global variable.
Array comprehensions - Archive of obsolete content
here is one that filters just the even numbers, then creates an array containing their doubles: var numbers = [1, 2, 3, 21, 22, 30]; var doubledevens = [for (i of numbers) if (i % 2 === 0) i * 2]; console.log(doubledevens); // logs 4,44,60 the square brackets of an array comprehension introduce an implicit block for scoping purposes.
Debug.msTraceAsyncCallbackStarting - Archive of obsolete content
function asyncwrapperfunction() { var opid = debug.mstraceasyncoperationstarting('async trace'); dosomethingasync().then(function (result) { debug.mstraceasyncoperationcompleted(opid, debug.ms_async_op_status_success); debug.mstraceasynccallbackstarting(opid); // process result of async operation.
Debug.msTraceAsyncCallbackCompleted - Archive of obsolete content
function asyncwrapperfunction() { var opid = debug.mstraceasyncoperationstarting('async trace'); dosomethingasync().then(function (result) { debug.mstraceasyncoperationcompleted(opid, debug.ms_async_op_status_success); debug.mstraceasynccallbackstarting(opid); // process result of async operation.
Debug.setNonUserCodeExceptions - Archive of obsolete content
syntax debug.setnonusercodeexceptions [= bool]; remarks if this property is set to true within a given scope, the debugger can then choose whether to take some specified action on exceptions thrown inside that scope: for instance, if the developer wishes to break on user-unhandled exceptions.
Error.stackTraceLimit - Archive of obsolete content
example the following example shows how to set and then get the stack trace limit.
Archived JavaScript Reference - Archive of obsolete content
you can use the more general proxy object instead.arraybuffer.transfer()the static arraybuffer.transfer() method returns a new arraybuffer whose contents have been taken from the oldbuffer's data and then is either truncated or zero-extended by newbytelength.
Server-Side JavaScript - Archive of obsolete content
but back then, 350 mhz servers were the best you could buy, and mozilla was yet to emerge from the netscape organization to continue to advance the state of web technologies.
background-size - Archive of obsolete content
user:jürgen jeka 2009-08-09 ok, here's a page with both rules - the css is derived from the code on the page here, this is what it looks like in 3.6a2pre on linux, the background image appears on the whole page, and then again behind the main content.
Building Mozilla XForms - Archive of obsolete content
the following scheme usually works (replace {geckoversion} with the used gecko/toolkit version): <em:minversion>{geckoversion}.0</em:minversion> <em:maxversion>{geckoversion}.*</em:maxversion> for example, for the firefox 3.5 version of the extension, it might look like that: <em:minversion>1.9.1.0</em:minversion> <em:maxversion>1.9.1.*</em:maxversion> then zip the files again (or use an editor like vim that can edit files inside a zip archive).
Mozilla XForms Specials - Archive of obsolete content
that is, if instancenode is a node in an instance document, then: instancenode.getfeature("org.mozilla.xforms.instanceowner", "1.0") will return the <instance> element (in the main document) that the node belongs to.
RFE to the Custom Controls - Archive of obsolete content
output that shows the dom if output contains cdata section or text node and its data is any mozilla known language like xhtml/xul/svg then output should parse and display it (see bug 316817).
RFE to the Custom Controls Interfaces - Archive of obsolete content
if you need to have a custom control that works with complext content or you find our interfaces too limiting to create the type of control that you have in mind, then this is the right place to pass along your requirements and any usecase that you are trying to solve.
RFE to the XForms API - Archive of obsolete content
ArchiveWebXFormsRFEXForms API
if you need some additional functionality that shouldn't be exposed from the xforms element directly, then you should think which interface of the xforms element is more appropriate to expose it.
XForms Group Element - Archive of obsolete content
if a group is non-relevant, then the rendering approach used to signify non-relevance is applied to the entire content of the group.
XForms Secret Element - Archive of obsolete content
characteristics analogous widgets are <xhtml:input type="password"/> and <xul:textbox type="password"/> if the incremental attribute is present and has the value true, then the bound instance node is updated on every user input.
XForms Select Element - Archive of obsolete content
characteristics appearance attribute contains the value full there are no analogue widgets in xhtml or in xul visual grouping by choices element is supported if incremental attribute value is false then bound node is updated when item is blurred examples <xf:model> <xf:instance> <data xmlns=""> <values>g</values> </data> </xf:instance> </xf:model> <xf:select ref="/data/values" appearance="full"> <xf:choices> <xf:label>green colors</xf:label> <xf:item> <xf:label>pale green</xf:label> <xf:value>pg</xf:value> </xf:item> <xf:item> <xf:label>g...
XForms Select1 Element - Archive of obsolete content
characteristics appearance attribute contains the value full there are no analogue widgets in xhtml or in xul visual grouping by choices element is supported selection="open" attribute isn't supported if incremental attribute value is false then bound node is updated when item is blurred examples <xf:model> <xf:instance> <data xmlns=""> <values>g</values> </data> </xf:instance> </xf:model> <xf:select1 ref="/data/values"> <xf:choices> <xf:label>green colors</xf:label> <xf:item> <xf:label>pale green</xf:label> <xf:value>pg</xf:value> </xf:item> <xf:item> <xf:label>green</xf:label> ...
XForms Submit Element - Archive of obsolete content
if the bound node is irrelevant, then the submit will be hidden.
XForms Textarea Element - Archive of obsolete content
characteristics analogous widgets are <xhtml:textarea/> and <xul:textbox multiline="true"/> if the incremental attribute has the value true, then the bound instance node is updated on every user input.
XForms Trigger Element - Archive of obsolete content
if the bound node is irrelevant, then the trigger will be hidden.
Choosing Standards Compliance Over Proprietary Practices - Archive of obsolete content
product marketing must then analyze the marketability of the application/product, and then conduct in-depth technical evaluations and market research studies.
Correctly Using Titles With External Stylesheets - Archive of obsolete content
if any alternate stylesheet is selected, then the preferred stylesheet is dropped in favor of the user-selected alternate stylesheet.
Issues Arising From Arbitrary-Element hover - Archive of obsolete content
hover and non-link elements section 5.11.3 of css2 defines the three dynamic pseudo-classes (:hover, :active, and :focus) and then goes on to say: css doesn't define which elements may be in the above states, or how the states are entered and left.
Windows Media in Netscape - Archive of obsolete content
for example, the following uses dhtml behaviors to associate a set of behaviors with a span element, which is then interrogated for its version number (the script attempts to verify that the windows media player control is at version 9): <span style="behavior:url(#default#clientcaps)" id="cc"></span> <script language=javascript> var cv = cc.getcomponentversion( "{6bf52a52-394a-11d3-b153-00c04f79faa6}", "componentid" ); if (cv == null || cv == "") { top.location.href = "http://foo.bar.foo/checkref"; } ...
XUL Parser in Python - Archive of obsolete content
extending on the approach in this script, then, you could imagine a kind of introspective xul chrome that could modify and replicate itself by calling services from the xulparser and xulwriter xpcom objects.
Common causes of memory leaks in extensions - Extensions
another solution would be to use the setinterval()/settimeout() instances content windows provide, but there is a big drawback with this idea: if the user disables javascript globally or locally (such as by using an add-on like noscript), then using the content window functions won't work.
Using the DOM File API in chrome code - Extensions
components.classes["@mozilla.org/file/directory_service;1"] .getservice(components.interfaces.nsiproperties) .get("profd", components.interfaces.nsifile); dsfile.append("myfilename.txt"); var file = file.createfromnsifile(dsfile); this uses the directory service to locate the profile directory (with the location key "profd", see below for more details), then appends the name of the file we want to work with by calling nsifile.append().
Game monetization - Game development
if you want to implement iaps try to add value to the game with something players will enjoy instead of taking it out and then charging for it.
Building up a basic demo with Babylon.js - Game development
it is then positioned to the right of the cube, rotated a bit so its 3d shape can be seen, and given a yellow material.
WebVR — Virtual Reality for the Web - Game development
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) { gpositionsensor = devices[i]; break; } ...
Async scripts for asm.js - Game development
two common situations in which a script is *not* async (as defined by the html spec) are: <script async>code</script> and var script = document.createelement('script'); script.innerhtml = "code"; document.body.appendchild(script); both are counted as 'inline' scripts and get compiled and then run immediately.
Implementing game control mechanisms - Game development
if you're looking for a good introduction to phaser, then check the 2d breakout game using phaser tutorial.
Efficient animation for web games - Game development
to take a concrete example, if you start a css transition to move something from off-screen so that it is fully visible on-screen, the browser knows that the related content will end up completely visible to the user and can then pre-render that content.
Square tilemaps implementation: Static maps - Game development
if tiles were a 2d matrix, then the returned value would just be tiles[column][row].
Bounce off the walls - Game development
the code above would deal with the ball bouncing off the top edge, so now let's think about the bottom edge: if(y + dy > canvas.height) { dy = -dy; } if the ball's y position is greater than the height of the canvas (remember that we count the y values from the top left, so the top edge starts at 0 and the bottom edge is at 320 pixels, the canvas' height), then bounce it off the bottom edge by reversing the y axis movement as before.
Collision detection - Game development
update the following part of the code as indicated by the highlighted line: var bricks = []; for(var c=0; c<brickcolumncount; c++) { bricks[c] = []; for(var r=0; r<brickrowcount; r++) { bricks[c][r] = { x: 0, y: 0, status: 1 }; } } next we'll check the value of each brick's status property in the drawbricks() function before drawing it — if status is 1, then draw it, but if it's 0, then it was hit by the ball and we don't want it on the screen anymore.
Paddle and keyboard controls - Game development
if the left cursor is pressed, then the leftpressed variable is set to true, and when it is released, the leftpressed variable is set to false.
Track the score and win - Game development
then use fillstyle() to set the color of the font and filltext() to set the actual text that will be placed on the canvas, and where it will be placed.
Physics - Game development
as a result it will be launched upwards, but then fall due to the effects of gravity pulling it down.
Visual JS GE - Game development
installing modules navigate to server_instance/, then in the node.js command prompt or console enter the following installation commands: npm install mysql npm install delivery npm install express npm install mkdirp npm install socket.io npm install nodemailer@0.7.0 setting up config.js you will find config.js in the server_instance folder: all node.js applications use the same folder — server_instance.
Visual typescript game engine - Game development
client config if you want web app without any networking then setup: appusenetwork: boolean = false; you want to use communication for multiplayer but you don't want to use server database account sessions.
Accessibility tree (AOM) - MDN Web Docs Glossary: Definitions of Web-related terms
browsers then create an accessibility tree based on the dom tree, which is used by platform-specific accessibility apis for assistive technologies, such as screen readers.
Bézier curve - MDN Web Docs Glossary: Definitions of Web-related terms
the end points of the lines are then steadily moved to the next point.
CRLF - MDN Web Docs Glossary: Definitions of Web-related terms
a cr immediately followed by a lf (crlf, \r\n, or 0x0d0a) moves the cursor down to the next line and then to the beginning of the line.
Selector (CSS) - MDN Web Docs Glossary: Definitions of Web-related terms
we can then apply this css to some html, such as: <p>this is happy text.</p> <div class="warning"> be careful!
CSS preprocessor - MDN Web Docs Glossary: Definitions of Web-related terms
to use a css preprocessor, you must install a css compiler on your web server; or use the css preprocessor to compile on the development environment, and then upload compiled css file to the web server.
Client hints - MDN Web Docs Glossary: Definitions of Web-related terms
the client can then give the server information about the client's environment, and the server can determine which resources to send based on that information.
Cryptographic hash function - MDN Web Docs Glossary: Definitions of Web-related terms
cryptographic hash functions are used for authentication, digital signatures, and message authentication codes.
Cryptography - MDN Web Docs Glossary: Definitions of Web-related terms
more than just data confidentiality, cryptography also tackles identification, authentication, non-repudiation, and data integrity.
Digital certificate - MDN Web Docs Glossary: Definitions of Web-related terms
digital certificates are most commonly signed by a certificate authority, attesting to the certificate's authenticity.
Encapsulation - MDN Web Docs Glossary: Definitions of Web-related terms
encapsulation is the packing of data and functions into one component (for example, a class) and then controlling access to that component to make a "blackbox" out of the object.
First-class Function - MDN Web Docs Glossary: Definitions of Web-related terms
example | assign a function to a variable javascript const foo = function() { console.log("foobar"); } // invoke it using the variable foo(); we assigned an anonymous function in a variable, then we used that variable to invoke the function by adding parentheses () at the end.
Flex - MDN Web Docs Glossary: Definitions of Web-related terms
the items then participate in flex layout, and all of the properties defined in the css flexible box layout module may be applied.
Flex Container - MDN Web Docs Glossary: Definitions of Web-related terms
this element then becomes a flex container, and each one of its children becomes a flex item.
Fuzz testing - MDN Web Docs Glossary: Definitions of Web-related terms
fuzzing is a technique for testing software using automated tools to provide invalid or unexpected input to a program or function in a program, then checking the results to see if the program crashes or otherwise acts inappropriately.
Global object - MDN Web Docs Glossary: Definitions of Web-related terms
we created a global function called greeting, then invoked it using the window object.
Grid - MDN Web Docs Glossary: Definitions of Web-related terms
if you place content outside of this explicit grid, or if you are relying on auto-placement and the grid algorithm needs to create additional row or column tracks to hold grid items, then extra tracks will be created in the implicit grid.
Grid Areas - MDN Web Docs Glossary: Definitions of Web-related terms
i have named these with the grid-area property and then laid them out on the grid using grid-template-areas.
Grid Cell - MDN Web Docs Glossary: Definitions of Web-related terms
the five items are placed into grid cells working along an initial row of three grid cells, then creating a new row for the remaining two.
Grid Lines - MDN Web Docs Glossary: Definitions of Web-related terms
when placing an item, you can then use these names instead of the line number, as demonstrated below.
Main Axis - MDN Web Docs Glossary: Definitions of Web-related terms
these are: row row-reverse column column-reverse should you choose row or row-reverse then your main axis will run along the row in the inline direction.
Mixin - MDN Web Docs Glossary: Definitions of Web-related terms
the new class or interface then includes both the properties and methods from the mixin as well as those it defines itself.
Mutable - MDN Web Docs Glossary: Definitions of Web-related terms
on appending the "immutablestring" with a string value, following events occur: existing value of "immutablestring" is retrieved "world" is appended to the existing value of "immutablestring" the resultant value is then allocated to a new block of memory "immutablestring" object now points to the newly created memory space previously created memory space is now available for garbage collection.
POP3 - MDN Web Docs Glossary: Definitions of Web-related terms
clients usually retrieve all messages and then delete them from the server, but pop3 does allow retaining a copy on the server.
Packet - MDN Web Docs Glossary: Definitions of Web-related terms
over time the number packets can cause traversing within closed circuits, the number of pa ckets circulating would build up and then ultimately lead to the networking in failing.
Preflight request - MDN Web Docs Glossary: Definitions of Web-related terms
for example, a client might be asking a server if it would allow a delete request, before sending a delete request, by using a preflight request: options /resource/foo access-control-request-method: delete access-control-request-headers: origin, x-requested-with origin: https://foo.bar.org if the server allows it, then it will respond to the preflight request with an access-control-allow-methods response header, which lists delete: http/1.1 204 no content connection: keep-alive access-control-allow-origin: https://foo.bar.org access-control-allow-methods: post, get, options, delete access-control-max-age: 86400 the preflight response can be optionally cached for the requests created in the same url using acc...
Presto - MDN Web Docs Glossary: Definitions of Web-related terms
since then, the opera browser is based on chromium, which uses the blink layout engine.
Primitive - MDN Web Docs Glossary: Definitions of Web-related terms
these copies, existing only inside the functions' scopes, are accessible via the identifiers we specified in the functions' definitions (num for addtwo, foo for addtwo_v2) then, the functions' statements are executed: in the first function, a local num variable had been created.
Public-key cryptography - MDN Web Docs Glossary: Definitions of Web-related terms
as a result, it's common for an encryption system to use a symmetric algorithm to encrypt the message, then a public-key system to encrypt the symmetric key.
RTP (Real-time Transport Protocol) and SRTP (Secure RTP) - MDN Web Docs Glossary: Definitions of Web-related terms
the secure version of rtp, srtp, is used by webrtc, and uses encryption and authentication to minimize the risk of denial-of-service attacks and security breaches.
Recursion - MDN Web Docs Glossary: Definitions of Web-related terms
examples recursive function calls itself until condition met the following python code defines a function that takes a number, prints it, and then calls itself again with the number's value -1.
SMTP - MDN Web Docs Glossary: Definitions of Web-related terms
primary complications include supporting various authentication mechanisms (gssapi, cram-md5, ntlm, msn, auth login, auth plain, etc.), handling error responses, and falling back when authentication mechanisms fail (e.g., the server claims to support a mechanism, but doesn't).
SPA (Single-page application) - MDN Web Docs Glossary: Definitions of Web-related terms
an spa (single-page application) is a web app implemention that loads only a single web document, and then updates the body content of that single document via javascript apis such as xmlhttprequest and fetch when different content is to be shown.
Scope - MDN Web Docs Glossary: Definitions of Web-related terms
if a variable or other expression is not "in the current scope," then it is unavailable for use.
Search engine - MDN Web Docs Glossary: Definitions of Web-related terms
it then presents results to the user in order of the ranking.
Signature - MDN Web Docs Glossary: Definitions of Web-related terms
signature (security) a signature, or digital signature, is a protocol showing that a message is authentic.
State machine - MDN Web Docs Glossary: Definitions of Web-related terms
this is like the "if" statement in that if x == true then dothis else dothat is not possible.
TCP slow start - MDN Web Docs Glossary: Definitions of Web-related terms
the server sends data in tcp packets, the user's client then confirms delivery by returning acknoledgements, or acks.
Transport Layer Security (TLS) - MDN Web Docs Glossary: Definitions of Web-related terms
it is possible for both the client and server to mutually authenticate each other, if both parties provide their own individual digital certificates.
Type coercion - MDN Web Docs Glossary: Definitions of Web-related terms
examples const value1 = '5'; const value2 = 9; let sum = value1 + value2; console.log(sum); in the above example, javascript has coerced the 9 from a number into a string and then concatenated the two values together, resulting in a string of 59.
Unicode - MDN Web Docs Glossary: Definitions of Web-related terms
if you've ever seen text where characters like curly quotes (“”) were replaced with gibberish like £, then you've seen this problem, known as mojibake.
Hash - MDN Web Docs Glossary: Definitions of Web-related terms
this provides the basis for hmac's, which provide message authentication.
Loop - MDN Web Docs Glossary: Definitions of Web-related terms
an example would be the process of getting an item of data and changing it, and then making sure some condition is checked such as, if a counter has reached a prescribed number.
Prerender - MDN Web Docs Glossary: Definitions of Web-related terms
with prerendering, the content is prefetched and then rendered in the background by the browser as if the content had been rendered into an invisible separate tab.
MDN Web Docs Glossary: Definitions of Web-related terms
x breadcrumb brotli browser browsing context buffer c cache cacheable caldav call stack callback function canonical order canvas card sorting carddav caret cdn certificate authority certified challenge-response authentication character character encoding character set chrome cia cipher cipher suite ciphertext class client hints closure cms code splitting codec compile compile time computer programming conditional constant constructor...
Test your skills: CSS and JavaScript accessibility - Learn web development
if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page.
Test your skills: HTML accessibility - Learn web development
if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page.
Test your skills: WAI-ARIA - Learn web development
if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page.
What is accessibility? - Learn web development
content, such as text written using plain-language standards; focusing attention on important content; minimizing distractions, such as unnecessary content or advertisements; consistent webpage layout and navigation; familiar elements, such as underlined links blue when not visited and purple when visited; dividing processes into logical, essential steps with progress indicators; website authentication as easy as possible without compromising security; and making forms easy to complete, such as with clear error messages and simple error recovery.
A cool-looking box - Learn web development
note: if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page.
Test your skills: The Cascade - Learn web development
if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page.
Fundamental CSS comprehension - Learn web development
note: if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page.
Test your skills: Images and Form elements - Learn web development
if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page.
Test your skills: Overflow - Learn web development
if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page.
Overflowing content - Learn web development
then we add content that exceeds the allocated space.
Test your skills: The Box Model - Learn web development
if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page.
Combinators - Learn web development
general sibling combinator if you want to select siblings of an element even if they are not directly adjacent, then you can use the general sibling combinator (~).
Test your skills: Selectors - Learn web development
if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page.
Test your skills: sizing - Learn web development
if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page.
Styling tables - Learn web development
with table-layout: fixed, you can size your columns according to the width of their headings, and then deal with their content as appropriate.
Test your skills: tables - Learn web development
if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page.
Test your skills: backgrounds and borders - Learn web development
if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page.
Test your skills: values and units - Learn web development
if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page.
Test your skills: Writing Modes and Logical Properties - Learn web development
if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page.
Test your skills: Flexbox - Learn web development
if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page.
Test your skills: Grid Layout - Learn web development
if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page.
Multiple-column layout - Learn web development
cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.</p> </div> .container { column-count: 3; } change your css to use column-width as follows: .container { column-width: 200px; } the browser will now give you as many columns as it can of the size that you specify; any remaining space is then shared between the existing columns.
Test your skills: position - Learn web development
if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page.
Test your skills: Media Queries and Responsive Design - Learn web development
if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page.
Using your new knowledge - Learn web development
note: if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page.
Typesetting a community school homepage - Learn web development
note: if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page.
What are hyperlinks? - Learn web development
since then, the web has evolved to provide access to images, videos, and binary data, but these improvements have hardly changed the three pillars.
What is a Domain Name? - Learn web development
each dns server that knows about a given domain stores the information for some time before it is automatically invalidated and then refreshed (the dns server queries an authoritative server and fetches the updated information from it).
What is a web server? - Learn web development
for now, just be aware of these things: only clients can make http requests, and then only to servers.
The HTML5 input types - Learn web development
then we immediately set the output's textcontent to the current value of the input.
Sending forms through JavaScript - Learn web development
in the following example, we use the filereader api to access binary data and then build the multi-part form data request by hand: <form id="theform"> <p> <label for="thetext">text data:</label> <input id="thetext" name="mytext" value="some text data" type="text"> </p> <p> <label for="thefile">file data:</label> <input id="thefile" name="myfile" type="file"> </p> <button>send me!</button> </form> as you see, the html is a standard <form>.
Test your skills: Advanced styling - Learn web development
if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page.
Test your skills: Basic controls - Learn web development
if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page.
Test your skills: Form structure - Learn web development
if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page.
Test your skills: HTML5 controls - Learn web development
if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page.
Test your skills: Other controls - Learn web development
if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page.
Test your skills: Styling basics - Learn web development
if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page.
How the Web works - Learn web development
here it is", and then starts sending the website's files to the browser as a series of small chunks called data packets (the shop gives you your goods, and you bring them back to your house).
What will your website look like? - Learn web development
click on the tools button, then on the resulting usage rights option that appears below.
Add a hitmap on top of an image - Learn web development
then assign that name (preceded by a hash) as the value for the usemap attribute: <img src="image-map.png" alt="" usemap="#example-map-1" /> step 2: activate your hotspots in this step, put all your code inside a <map> element.
Getting started with HTML - Learn web development
in the example above, we opened the p element first, then opened the strong element.
HTML text fundamentals - Learn web development
doing it locally will probably be better, as then you'll get to save the work you are doing, whereas if you fill it in to the editable example, it will be lost the next time you open the page.
Marking up a letter - Learn web development
note: if you get stuck, then ask us for help.
Structuring a page of content - Learn web development
note: if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page.
Test your skills: Advanced HTML text - Learn web development
if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page.
Test your skills: HTML text basics - Learn web development
if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page.
Test your skills: Links - Learn web development
if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page.
Test your skills: HTML images - Learn web development
if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page.
Test your skills: Multimedia and embedding - Learn web development
if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page.
Multimedia and Embedding - Learn web development
if you've not worked through this module (or something similar), work through it first, then come back!
HTML table basics - Learn web development
LearnHTMLTablesBasics
screenreaders are then able to read out a whole row or column of data at once, which is pretty useful.
Assessment: Structuring planet data - Learn web development
if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page.
Structuring the web with HTML - Learn web development
after learning html, you can then move on to learning about more advanced topics such as: css, and how to use it to style html (for example alter your text size and fonts used, add borders and drop shadows, layout your page with multiple columns, add animations and other visual effects.) javascript, and how to use it to add dynamic functionality to web pages (for example find your location and plot it on a map, make ui elemen...
Asynchronous JavaScript - Learn web development
if you are, then you can probably skip to the introducing asynchronous javascript module.
Image gallery - Learn web development
note: if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page.
Test your skills: Events - Learn web development
if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page.
Test your skills: Strings - Learn web development
if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page.
Test your skills: variables - Learn web development
if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page.
Useful string methods - Learn web development
you'll then need to write a conditional test of the form operand1 operator operand2.
JavaScript First Steps - Learn web development
here we look at why this is useful, then explore how to create an array, retrieve, add, and remove items stored in an array, and more besides.
CSS performance optimization - Learn web development
previous overview: performance next painting an unstyled page, and then repainting it once styles are parsed would be bad user experience.
Perceived performance - Learn web development
in other words, first download everything you're going to actually show, but only the stuff you are actually using, then download the rest.
Web performance resources - Learn web development
to load css asynchronously one can simpy set the media type to print and then change to all once loaded.
What is web performance? - Learn web development
performance measurements: web performance involves measuring the actual and perceived speeds of an application, optimizing where possible, and then monitoring the performance, to ensure that what you've optimized stays optimized.
Server-side website programming first steps - Learn web development
we then provide an overview of some of the most popular server-side web frameworks, along with guidance on how to select the most suitable framework for creating your first site.
Ember interactivity: Events, classes and state - Learn web development
in the below sections we’ll do this for each component, and then walk you through how the functionality can be implemented.
Ember resources and troubleshooting - Learn web development
={{fn (mut this.somedata) (not this.somedata)}} /> whereas, without mut, a component class would be needed: import component from '@glimmer/component'; import { tracked } from '@glimmer/tracking'; import { action } from '@ember/object'; export default class example extends component { @tracked somedata = false; @action setdata(newvalue) { this.somedata = newvalue; } } which would then be called in the template like so: <checkbox @data={{this.somedata}} @onchange={{this.setdata}} /> due to the conciseness of using mut, it may be desireable to reach for it.
Framework main features - Learn web development
your application updates this copy of the dom, then compares it to the "real" dom — the dom that is actually rendered for your users — in order to decide what to render.
Learn web development
frameworks and tooling: after mastering the essentials of vanilla html, css, and javascript, you should learn about client-side web development tools, and then consider digging into client-side javascript frameworks, and server-side website programming.
Accessibility API cross-reference
<h> is also available but its use is not recommended because of lack of suitable tools - and the heading level is undefined click on this thing and then click on the item for tooltip style help helpballoon n/a n/a n/a editable field that allows user to assign a key combination hotkeyfield n/a n/a n/a graphic that indicates something, such as an arrow indicator n/a n/a n/a abstract role - a generic type of widget that allows user input.
Accessibility information for UI designers and developers
your content can then be better consumed by users with low vision and people with color deficiencies.
Links and Resources
online accessibility validators there are now a few available and excellent online accessibility validators which check single webpages according to checkpoints of wcag guidelines and then reports errors or warnings.
Software accessibility: Where are we today?
for example to make a capital letter, first press the shift key, release it, then press the letter to be capitalized.
Mozilla’s UAAG evaluation report
(p2) p can turn off scripting, but then no event processing is available 9.6 show event handlers.
Index
675 creating an appealing add-on listing add-ons, beginner, guide, webextension, publishing there are two essential steps to getting people to use your add-on: they need to discover your add-on and open the listing page, then the listing page needs to encourage them to click the add to firefox button.
Adding a new word to the en-US dictionary
add and remove words in the dictionary file, then quit the editor.
Command line options
if you don't specify a profile name then the profile manager is opened instead.
Creating JavaScript callbacks in components
the component can then call methods on the observer interface to signal the external code when predefined events occur.
Debugging Chrome
i was then able to run pix on d3dretrace.
Debugging JavaScript
this can be a security risk, especially if you also set the devtools.debugger.force-local preference to false.) then, the browser toolbox displays the available tools for debugging.
Debugging OpenGL
linux64-debug, then find the build link on the right hand side (this would be target.tar.bz2 for linux, target.dmg for macos, and target.zip for windows).
Debugging Table Reflow
lame-paint-metrics lame-reflow-metrics disable-resize-opt these options can be combined with a comma separated list messages generated by the reflow switch: block(div)(1)@00be5ac4: reflowing dirty lines computedwidth=9000 computedheight=1500 this message is generated inside of nsresult nsblockframe::reflowdirtylines(nsblockreflowstate& astate) it first shows the block id and address and then the computed width and height from the htmlreflowstate.
Debugging update problems
that url might look something like: https://aus3.mozilla.org/update/3/firefox/12.0a1/20120106040225/darwin_x86_64-gcc3-u-i386-x86_64-shark/nightly-profiling/darwin%2010.8.0/default/default/update.xml?force=1 you can then request this url manually to see what's inside.
Adding APIs to the navigator object
this adds a new api, mycomponent, to the navigator object, which you can then access as navigator.mycomponent.
Configuring Build Options
you then need to use the ac_add_app_options with the specified names to enable different applications in each object directory.
Updating NSPR or NSS in mozilla-central
moz_arg_with_bool(system-nss, [ --with-system-nss use system installed nss], _use_system_nss=1 ) if test -n "$_use_system_nss"; then am_path_nss(3.16.1, [moz_native_nss=1], [ac_msg_error([you don't have nss installed or your version is too old])]) fi commit the update: $ hg commit -a in order to eliminate any problems related to how nss and nspr are built differently in firefox than they are standalone, you should push your commit to try first.
pymake
type touch .profile using any appropriate text editor open .profile and add the following line in the file (assuming your mozilla-central is at c:/mozilla-central, if not, adjust your path accordingly.) alias pymake=c:/mozilla-central/build/pymake/make.py save your .profile edit and close the shell, then restart the shell.
Callgraph
given the knowledge that evil() does evil things, one could then determine foo() also does evil things.
Creating Custom Events That Can Pass Data
as of gecko 1.8, if your event names do not start with "nsdom" and their interfaces do not start with "nsidom" then you can forget about passing data.
ESLint
for example: in windows 10, if you have installed node.js on "c:\nodejs", then the command should look like: export path=$path:/c/nodejs enabling eslint for a new directory remove the directory from .eslintignore (in the base directory of the repository) fix errors that occur when running ./mach eslint path/to/dir, see also the no-undef rules below.
Inner and outer windows
then add to that the concept of frames, whereby a document in a window can itself contain other documents, which in turn can contain more documents.
Commenting IDL for better documentation
@returns description if the method returns something then this should be included.
Contributing to the Mozilla code base
we'll be integrating some information from these pages soon, but until then you may find them interesting in their current form: a guide to learning the mozilla codebase a beginner's guide to spidermonkey, mozilla's javascript engine mozilla platform development cheatsheet (archive.org) ...
Listening to events on all tabs
if any registered progress listener returns false from this method then the attempt to refresh will be blocked.
Communicating with frame scripts
l sendsyncmessage() function: // frame script sendsyncmessage("my-addon@me.org:my-e10s-extension-message"); when a chrome script receives a synchronous message, it should return a value from its message listener: // chrome script messagemanager.addmessagelistener("my-addon@me.org:my-e10s-extension-message", listener); function listener(message) { return "value from chrome"; } this value is then presented to the frame script in the return value of sendsyncmessage().
Blocked: All storage access requests
the permission can be changed or removed by: going to preferences > content blocking in the custom content blocking section, selecting a value other than all cookies for the cookies item if the resource that is being blocked doesn't need authentication, you can fix the warning message by adding a crossorigin="anonymous" attribute to your element.
Blocked: All third-party storage access requests
the permission can be changed or removed by: going to preferences > content blocking and either adding an exception with the manage exceptions… button choosing the custom content blocking and unchecking the cookies checkbox if the resource that is being blocked doesn't need authentication, you can fix the warning message by adding a crossorigin="anonymous" attribute to the relevant element.
Blocked: Storage access requests from trackers
the permission can be changed or removed by: going to preferences > content blocking and either adding an exception with the manage exceptions… button choosing the custom content blocking and unchecking the tracker checkbox if the blocked resource doesn't need authentication, you can fix the warning message by adding a crossorigin="anonymous" attribute to the relevant element.
HTMLIFrameElement.addNextPaintListener()
note: the handler will receive the event once and then be thrown away.
HTMLIFrameElement.getStructuredData()
examples var browser = document.queryselector('iframe'); browser.addeventlistener('mozbrowserloadend',function() { var request = browser.getstructureddata(); request.onsuccess = function() { console.log(request.result); } }); running this code in a browser api app and then loading up a page that contains microdata (such as the website of british alt-country band salter cane) will result in a json object being returned, along the lines of: { "items": [ { "type":["http://microformats.org/profile/hcard"], "properties":{"fn":["chris askew"], "n":[ { "properties": { "given-name":["c...
mozbrowseractivitydone
if the activity has a returnvalue set to true, then the activity is consumed when postresult or posterror is invoked on the activity by the receiving app.
Browser API
mozbrowserusernameandpasswordrequired sent when an http authentification is requested.
overflow-clip-box
prior to firefox 29, this behavior was hardcoded; since then it uses this property that can be used elsewhere too.
MozBeforePaint
with that value in hand, you can then schedule all your subsequent animation frames.
Overview of Mozilla embedding APIs
internally, this function tries to convert the nsisupports argument into an nsiinterfacerequestor and then calls getinterface(...) to retrieve the requested interface.
Gecko SDK
the gecko sdk, also known as the xulrunner sdk, is a set of xpidl files, headers and tools to develop xpcom components which can then in turn e.g.
Gecko versions and application versions
note that after gecko 2.0, both firefox and thunderbird versions are from then on the same as the gecko version number, at gecko 5.0.
Getting from Content to Layout
these items are then examined in relation to the location in the content tree that is being modified and either the relevant frames are created/destroyed or the logic moves up to the parent frame.
Hacking with Bonsai
the build team will then pull the 8:00 am tree, and build it on a subset of the platforms, linux, win32 & macppc.
How to add a build-time test
for standalone executables, if one sets up the right variables, then the rules.mk file will do lots of magic and most of the heavy lifting.
How to implement a custom autocomplete search component
s, null); listener.onsearchresult(this, autocomplete_result); }, /** * stops an asynchronous search that is in progress */ stopsearch: function() { }, queryinterface: xpcomutils.generateqi([ ci.nsiautocompletesearch ]) }; // the following line is what xpcom uses to create components const nsgetfactory = xpcomutils.generatensgetfactory([ providerautocompletesearch ]); then register your xpcom component.
IPDL Type Serialization
!readparam(amsg, aiter, &(aresult->j))) return false; for (int i = 0; i < 4; ++i) if (!readparam(amsg, aiter, &(aresult->k[i]))) return false; return true; } }; } // namespace ipc once you have a serializer for a type, you can serialize a collection of it (ex: an nstarray<examplestruct>) by simply declaring "using nstarray<examplestruct>;' in your ipdl file, then using it in a ipc method.
Implementing QueryInterface
you won't be able to catch calls to queryinterface on the aggregated objects, which may then return wrong interfaces.
AddonListener
addonlisteners can be registered with addaddonlistener() and will then receive notification of changes to the add-ons currently installed.
AddonManager
if apath is empty then the uri to the root of the contained files will be returned.
AddonUpdateChecker
if all you care about is finding the newest version for an addon then you probably want to use findupdates() instead.
TypeListener
typelisteners can be registered with addtypelistener() and will then receive notification as addontype are registered and unregistered.
Add-on Manager
these will pass an addoninstall instance to the callback, which can then be used to install the add-on: components.utils.import("resource://gre/modules/addonmanager.jsm"); addonmanager.getinstallforurl("http://www.foo.com/test.xpi", function(ainstall) { // ainstall is an instance of addoninstall ainstall.install(); }, "application/x-xpinstall"); the progress of addoninstalls can be monitored using an installlistener.
Dict.jsm
var mydict = new dict(); mydict.set("name", "john smith"); mydict.set("email", "jsmith@example.com"); mydict.set("phone", "650-555-1234"); working with existing keys you can then check to see if a given key exists: if (mydict.has("email")) { /* an "email" key exists on the object */ } ...
DownloadLastDir.jsm
to use this, you first need to import the code module into your javascript scope: components.utils.import("resource://gre/modules/downloadlastdir.jsm"); if you are using addon sdk, you can import the code module as: let { cu } = require("chrome"); let downloadlastdir = cu.import("resource://gre/modules/downloadlastdir.jsm").downloadlastdir; once you've imported the module, you can then use the downloadlastdir object it exports.
DownloadTarget
if that metadata is no longer available and the file has been deleted, then this value is zero.
FxAccountsOAuthClient.jsm
the fxaccountsoauthclient.jsm javascript module provides a way for browser services to authenticate with the firefox accounts oauth server.
FxAccountsProfileClient.jsm
examples using the fxaccountsprofileclient chrome code let client = new fxaccountsprofileclient({ serverurl: "https://profile.accounts.firefox.com/v1", token: "fxa_oauth_bearer_token", }); client.fetchprofile().then(profile => console.log(profile)); error handling the fxaccountsprofileclient.jsm normalizes request and client errors into fxaccountsprofileclienterror object.
Geometry.jsm
to use these routines, you first need to import the code module into your javascript scope: components.utils.import("resource://gre/modules/geometry.jsm"); once you've imported the module, you can then use the point and rect classes.
Http.jsm
to achieve this, you can obtain an xhr object by calling httprequest and then call its overridemimetype() with a preferred mime-type.
ISO8601DateUtils.jsm
to use this, you first need to import the code module into your javascript scope: components.utils.import("resource://gre/modules/iso8601dateutils.jsm"); once you've imported the module, you can then use the iso8601dateutils object it exports.
PerfMeasurement.jsm
note: these values are all zeroed (or set to -1, for events not being measured) when you initialize the perfmeasurement object, then they are not zeroed again unless you explicitly call the reset() method.
PopupNotifications.jsm
to use this, you first need to import the code module into your javascript scope: components.utils.import("resource://gre/modules/popupnotifications.jsm"); once you've imported the module, you can then use the popupnotifications object it exports; this object provides methods for creating and displaying popup notification panels.
PromiseWorker.jsm
lve argument and therefore this will reject the main thread promise'); } } main thread file bootstrap.js const { utils: cu } = components; const { basepromiseworker } = cu.import('resource://gre/modules/promiseworker.jsm', {}); var myworker = new basepromiseworker('chrome://path/to/content/myworker.js'); var promise_domyfunctrue = myworker.post('resolvetest', [true]); promise_domyfunctrue.then( function(aval) { console.log('fullfilled - promise_domyfunctrue - ', aval); }, function(areason) { console.error('rejected - promise_domyfunctrue - ', areason); } ).catch( function(acaught) { console.error('caught - promise_domyfunctrue - ', acaught); } ); var promise_domyfuncfalse = myworker.post('resolvetest', [false]); promise_domyfuncfalse.the...
Services.jsm
to use it, you first need to import the code module into your javascript scope: const {services} = chromeutils.import("resource://gre/modules/services.jsm"); then you can obtain references to services by simply accessing them from the services object exported by the code module.
Timer.jsm
to use timer.jsm, first import it: components.utils.import("resource://gre/modules/timer.jsm"); then call settimeout and cleartimeout just as you would in a dom window, for example: let timeoutid = settimeout(function() { console.log("hello!"); }, 500); cleartimeout(timeoutid); similarly, you can use setinterval and clearinterval like so: let intervalid = setinterval(function() { console.log("happening every 500ms!"); }, 500); clearinterval(intervalid); ...
openLocationLastURL.jsm
to use this, you first need to import the code module into your javascript scope: components.utils.import("resource:///modules/openlocationlasturl.jsm"); once you've imported the module, you can then use the openlocationlasturl object it exports.
source-editor.jsm
you can then use this value to detect when the contents of the text are different from your most recent save.
Index
mercurial allows localizers to work locally (on their machines) and then push (an hg term) changes to a remote repository, which usually is hosted on the mozilla servers (hg.mozilla.org).
Localization and Plurals
people using the extension can then copy/paste this input.
Localizing extension metadata on addons.mozilla.org
create an account and then, using the “basic open-ended question” template, follow the instructions to upload the text of your amo page.
Localizing with Mercurial
mercurial allows localizers to work locally (on their machines) and then push (an hg term) changes to a remote repository, which usually is hosted on the mozilla servers (hg.mozilla.org).
QA phase
for instance, if you have finished translating all the .dtd and .properties files in your x-testing/browser/chrome/browser/ directory, then you should run these commands: $ hg status $ hg commit -m "translated browser/chrome/browser/" $ hg outgoing $ hg push http://hg.mozilla.org/l10n-central/x-testing note that due to the distributed nature of hg, hg commit saves the changes locally (i.e., in your computer's hg repository).
Localization quick start guide
as you near the end of this guide, you should be able to make a change to firefox in your local setting and then see that change in the firefox interface.
gettext
in the po file, msgctxt looks like this: msgctxt "button label" msgid "log in" msgstr "" msgctxt "dialog title" msgid "log in" msgstr "" you can add context to your strings by passing an additional argument to the gettext function call and then having xgettext extract it as the context.
Mozilla MathML Status
if only the main features of an element are implemented then its section is marked as supported but details of unsupported attributes are specified below.
Mozilla Style System
the style contexts then provide the api for computed style data by allowing retrieval of a set of style structs, each of which contains the computed values of a set of css properties.
Activity Monitor, Battery Status Menu and top
if a laptop is closed for several hours and then reopened, those hours are not included in the calculation.) battery status menu when you click on the battery icon in the os x menu bar you get a drop-down menu that includes a list of “apps using significant energy”.
JS::PerfMeasurement
it will not have any more bits set than were set in the mask passed to the constructor, but if the os cannot or will not measure all of the requested events, then only those events that will actually be measured have their bits set.
Measuring performance using the PerfMeasurement.jsm code module
the first thing you need to do is to import the module into your scope: components.utils.import("resource://gre/modules/perfmeasurement.jsm") you can then create a perfmeasurement object.
Refcount tracing and balancing
if the leak comes from a smart pointer that is logged in the xpcom_mem_comptr_log, then find-comptr-leakers.pl will find the exact stack for you, and you don't have to look at trees.
tools/power/rapl
if the processor does not support gpu or ram estimates then " n/a " will be printed in the relevant column instead of a number, and it will contribute zero to the total.
Performance
that log can then be replayed against firefox's default memory allocator independently or through another replace-malloc library, allowing the testing of other allocators under the exact same workload.
Profile Manager
you'll be prompted for the location of the archive, and then for the name of the profile you'd like to create from the archive.
Firefox Sync
it uses firefox accounts for account, authentication and key management.
L20n HTML Bindings
you can then embed localization resources right in your html.
Localization Use Cases
in the javascript code, the developer needs to pass sizeinfo.unit instead of a localized value: function showformatedsize(element, l10nid, size) { // … element.textcontent = document.l10n.get(l10nid, { size: sizeinfo.size, unit: sizeinfo.unit }); } and then use the $unit variable verbatim in the english message: <availablesize "{{ $size }} {{ $unit }} available"> in french, the localizer can then use the value of $unit to match it against a translated abbreviation, like so: <_unitedemesure { b: "o", kb: "ko", mb: "mo", gb: "go", tb: "to" }> <availablesize "il reste {{ $size }} {{ _unitedemesure[unit] }}"> similarly, other local var...
Midas
if no action has occurred in the document, then this command will have no effect.
About NSPR
hoare in monitors: an operating system structuring concept , communications of the acm, 17(10), october 1974 and then formalized by xerox' mesa programming language ("mesa language manual", j.g.
Creating a Cookie Log
close out of the command prompt/shell/terminal, and then launch firefox normally.
I/O Functions
it is then possible to scan the chain of layers and find a layer that one recognizes and therefore predict that it will implement a desired protocol.
NSPR LOG FILE
if nspr_log_file is not in the environment, then log output is written to stdout or stderr, depending on the platform.
PLHashNumber
a hash function maps a key to a hash number, which is then used to compute the index of the bucket.
PRDescIdentity
it is then possible to scan the chain of layers and find a layer that one recognizes, then predict that it will implement a desired protocol.
PRErrorCode
if nspr's error handling is adopted by calling clients, then some sort of partitioning of the namespace will have to be employed.
PRFileMap
then sections of the file can be mapped into memory by passing the prfilemap pointer to pr_memmap.
PRStaticLinkTable
if, during initialization, such entries are manually created, then future attempts to link to the symbols can be treated in a consistent fashion.
PR_AtomicSet
description pr_atomicset first reads the value of var, then updates it with the supplied value.
PR_Available
the error code can then be retrieved via pr_geterror.
PR_Available64
the error code can then be retrieved via pr_geterror.
PR_CNotify
if a thread is waiting on the monitor (having called pr_cwait), then that thread is made ready.
PR_CNotifyAll
all of the threads waiting on the state change are then scheduled to reenter the monitor.
PR_Delete
if the function fails, the error code can then be retrieved via pr_geterror.
PR_FindSymbolAndLibrary
this function is equivalent to calling first pr_loadlibrary, then pr_findsymbol.
PR_GetUniqueIdentity
if you're creating a custom i/o layer, cache the result, and then use that cached result every time you call pr_createiolayerstub.
PR ImportTCPSocket
for example, on posix systems, nspr will put the native file descriptor (an int) in non-blocking mode by calling fcntl to set the o_nonblock file status flag on the native file descriptor, and then nspr will call socket functions such as recv, send, and poll on the native file descriptor.
PR_JoinThread
if pr_jointhread is not called on the same thread as pr_createthread, then it is the caller's responsibility to ensure that pr_createthread has completed.
PR_JoinThreadPool
waits for all threads in a thread pool to complete, then releases resources allocated to the thread pool.
PR_NewLogModule
if the environment variable nspr_log_modules contains the specified name, then the associated level value from the variable is associated with the new prlogmoduleinfo structure.
PR NewProcessAttr
description this function creates a new prprocessattr structure that specifies the attributes of a new process, then returns a pointer to the structure.
PR_PopIOLayer
if the object to be removed is found, pr_popiolayer returns a pointer to the removed object the object then becomes the responsibility of the caller.
PR_Seek
the error code can then be retrieved with pr_geterror.
PR_Seek64
the error code can then be retrieved with pr_geterror.
PR_WaitCondVar
the value pr_interval_no_wait causes the thread to release the lock, possibly causing a rescheduling within the runtime, then immediately attempt to reacquire the lock and resume.
PR_WaitForPollableEvent
blocks the calling thread until the pollable event is set, and then atomically unsetting the event before returning.
PR_WaitSemaphore
if the value of the semaphore is 0, the function blocks until the value becomes > 0, then the semaphore is decremented and the function returns.
Running NSPR tests
then you can detect regressions of the new version by comparing its test results with the benchmark.
CERT_FindCertByIssuerAndSN
certcertdbhandle *handle, certissuerandsn *issuerandsn ); parameters handle in pointer to a certcertdbhandle representing the certificate database to look in issuerandsn in pointer to a certissuerandsn that must be properly formed to contain the issuer name and the serial number (see [example]) description this function creates a certificate key using the issuerandsn and it then uses the key to find the matching certificate in the database.
JSS
MozillaProjectsNSSJSS
if you are planning to just use jss jce provider as a bridge to nss's fips validated pkcs#11 module, then the sunpkcs11 jce provider may do all that you need.
NSS 3.12.4 release notes
if one is upper case and the other is lower case, then the ascii non-alphanumeric characters between z and a will also be in range.
NSS 3.12.5 release_notes
if the string parameter is null (as opposed to empty, zero length), then the softoken default is used.
NSS_3.12_release_notes.html
bug 337088: coverity 405, pk11_paramtoalgid() in mozilla/security/nss/lib/pk11wrap/pk11mech.c bug 339907: oaep_xor_with_h1 allocates and leaks sha1cx bug 341122: coverity 633 sftk_destroyslotdata uses slot->slotlock then checks it for null bug 351140: coverity 995, potential crash in ecgroup_fromnameandhex bug 362278: lib/util includes header files from other nss directories bug 228190: remove unnecessary nss_enable_ecc defines from manifest.mn bug 412906: remove sha.c and sha.h from lib/freebl bug 353543: valgrind uninitialized memory read in nsspkiobjectcollection_addinstances bug 377548: nss qa test program ce...
NSS 3.15.1 release notes
the hash function used in the signature for tls 1.2 client authentication must be the hash function of the tls 1.2 prf, which is always sha-256 in nss 3.15.1.
NSS 3.19.2 release notes
applications that requested or attempted to use keys smaller then the minimum size would fail.
NSS 3.23 release notes
sha-256 fingerprint: a1:33:9d:33:28:1a:0b:56:e5:57:d3:d3:2b:1c:e7:f9:36:7e:b0:94:bd:5f:a7:2a:7e:50:04:c8:de:d7:ca:fe cn = certum trusted network ca 2 sha-256 fingerprint: b6:76:f2:ed:da:e8:77:5c:d3:6c:b0:f6:3c:d1:d4:60:39:61:f4:9e:62:65:ba:01:3a:2f:03:07:b6:d0:b8:04 the following ca certificate had the email trust bit turned on cn = actalis authentication root ca sha-256 fingerprint: 55:92:60:84:ec:96:3a:64:b9:6e:2a:be:01:ce:0b:a8:6a:64:fb:fe:bc:c7:aa:b5:af:c1:55:b3:7f:d7:60:66 security fixes in nss 3.23 bug 1245528 / cve-2016-1950 - fixed a heap-based buffer overflow related to the parsing of certain asn.1 structures.
NSS 3.24 release notes
update sslauthtype to define a larger number of authentication key types.
NSS 3.25.1 release notes
previously, with rare server configurations, an md5 signature algorithm might have been selected for client authentication and caused the client to abort the connection soon after.
NSS 3.25 release notes
removed the limitation that allowed nss to only support certificate_verify messages that used the same signature hash algorithm as the prf when using tls 1.2 client authentication.
NSS 3.26.2 release notes
previously, with rare server configurations, an md5 signature algorithm might have been selected for client authentication and caused the client to abort the connection soon after.
NSS 3.27 release notes
cn = juur-sk, o = as sertifitseerimiskeskus sha256 fingerprint: ec:c3:e9:c3:40:75:03:be:e0:91:aa:95:2f:41:34:8f:f8:8b:aa:86:3b:22:64:be:fa:c8:07:90:15:74:e9:39 cn = ebg elektronik sertifika hizmet sağlayıcısı sha-256 fingerprint: 35:ae:5b:dd:d8:f7:ae:63:5c:ff:ba:56:82:a8:f0:0b:95:f4:84:62:c7:10:8e:e9:a0:e5:29:2b:07:4a:af:b2 cn = s-trust authentication and encryption root ca 2005:pn sha-256 fingerprint: 37:d8:dc:8a:f7:86:78:45:da:33:44:a6:b1:ba:de:44:8d:8a:80:e4:7b:55:79:f9:6b:f6:31:76:8f:9f:30:f6 o = verisign, inc., ou = class 1 public primary certification authority sha-256 fingerprint: 51:84:7c:8c:bd:2e:9a:72:c9:1e:29:2d:2a:e2:47:d7:de:1e:3f:d2:70:54:7a:20:ef:7d:61:0f:38:b8:84:2c o = verisi...
NSS 3.33 release notes
fixes cve-2017-7805, a potential use-after-free in tls 1.2 server, when verifying client authentication.
NSS 3.36.4 release notes
bugs fixed in nss 3.36.4 bug 1461731 - fix crash on macos related to authentication tokens, e.g.
NSS 3.37.3 release notes
bug 1461731 - fix crash on macos related to authentication tokens, e.g.
NSS 3.39 release notes
nss will use rsa-pss keys to authenticate in tls.
NSS 3.44 release notes
with netscape certificate sequences 1533616 - sdb_getattributevaluenolock should make at most one sql query, rather than one for each attribute 1531236 - provide accessor for certcertificate.dercert 1536734 - lib/freebl/crypto_primitives.c assumes a big endian machine 1532384 - in nss test certificates, use @example.com (not @bogus.com) 1538479 - post-handshake messages after async server authentication break when using record layer separation 1521578 - x25519 support in pk11pars.c 1540205 - freebl build fails with -dnss_disable_chachapoly 1532312 - post-handshake auth doesn't interoperate with openssl 1542741 - certutil -f crashes with segmentation fault 1546925 - allow preceding text in try comment 1534468 - expose chacha20 primitive 1418944 - quote cc/cxx variables passed to ns...
NSS 3.46 release notes
of integers of different signs: 'int' and 'unsigned long' bug 1564714 - print certutil commands during setup bug 1565013 - hacl image builder times out while fetching gpg key bug 1563786 - update hacl-star docker image to pull specific commit bug 1559012 - improve gcm perfomance using pmull2 bug 1528666 - correct resumption validation checks bug 1568803 - more tests for client certificate authentication bug 1564284 - support profile mobility across windows and linux bug 1573942 - gtest for pkcs11.txt with different breaking line formats bug 1575968 - add strsclnt option to enforce the use of either ipv4 or ipv6 bug 1549847 - fix nss builds on ios bug 1485533 - enable nss_ssl_tests on taskcluster this bugzilla query returns all the bugs fixed in nss 3.46: https://bugzilla.mozilla.
NSS 3.53 release notes
(bug 1618404, bug 1621159) if a builtin certificate has a cka_nss_server_distrust_after timestamp before the sct or notbefore date of a certificate that builtin issued, then clients can elect not to trust it.
NSS Config Options
isallow=all allow=sha1:sha256:secp256r1:secp384r1:min-rsa=2048:min-dh=1024" a policy that enables the aes ciphersuites and the secp256/384 curves: config="allow=aes128-cbc:aes128-gcm::hmac-sha1:sha1:sha256:sha384:rsa:ecdhe-rsa:secp256r1:secp384r1" turn off md5 config="disallow=md5" turn off md5 and sha1 only for ssl config="disallow=md5(ssl):sha1(ssl)" disallow values are parsed first, and then allow values, independent of the order in which they appear.
NSS Sample Code sample2
if you choose something else, then data padding is the * application's responsibility */ ciphermech = ckm_des_cbc_pad; slot = pk11_getbestslot(ciphermech, null); /* slot = pk11_getinternalkeyslot(); is a simpler alternative but in * theory, it *may not* return the optimal slot for the operation.
NSS Sample Code sample5
pvtkey = null; int modulus_len, i, outlen; char *buf1 = null; char *buf2 = null; char *pubkstr = base64_encoded_subjectpublickeyinfo; char *pvtkstr = base64_encoded_privatekeyinfo; secitem der; secitem nickname; pk11slotinfo *slot = null; /* initialize nss * you need to explicitly authenticate to the internal token if you use * nss_init insteadf of nss_nodb_init * invoke this after getting the internal token handle * pk11_authenticate(slot, pr_false, null); */ rv = nss_nodb_init("."); if (rv != secsuccess) { fprintf(stderr, "nss initialization failed (err %d)\n", pr_geterror()); goto cleanup; } /* get internal slot */ slot = pk11_...
NSS Sample Code sample6
the symmetric keys can then be used * without ever exposing them in the clear.
nss tech note4
secitem_freeitem(&data.maxusers, pr_false); } } some miscellaneous helper functions compare two secitems (e.g., two oids) prbool secitem_itemsareequal(const secitem *a, const secitem *b); interpreting a secitem value as an integer if secitem *item->len <=4, then int value = der_getinteger(item); interpreting a secitem value as a string use string copy functions to copy item->len bytes from item->data and null terminate explicitly some higher level extension functions get a specific extension from the list of extensions, given the extension tag secstatus cert_findcertextension (certcertif...
nss tech note5
if you choose something else, then data padding is the application's responsibility.
nss tech note6
if your application modifies nss binaries for any reason after they were built, then : the fips 140 mode of operation will no longer work, because the chk files will no longer match the softoken and freebl shared libraries .
Notes on TLS - SSL 3.0 Intolerant Servers
for instance, to check https://bugzilla.mozilla.org/, then visit http://toolbar.netcraft.com/site_rep...a.mozilla.org/.
Installation guide
this is done here: http://lxr.mozilla.org/security/sour...platlibs.mk#53 53 ifeq ($(os_arch), linux) 54 ifeq ($(use_64), 1) 55 extra_shared_libs += -wl,-rpath,'$$origin/../lib64:$$origin/../lib' 56 else 57 extra_shared_libs += -wl,-rpath,'$$origin/../lib' 58 endif 59 endif for example, if you install certutil in /foo/bar/nss/bin and the .so's in /foo/bar/nss/lib, then you only need to add /foo/bar/nss/bin to your path; you don't need to set ld_library_path.
FC_InitToken
specifically, fc_inittoken() initializes or clears the key database, removes the password, and then marks all the user certs in the certificate database as non-user certs.
FC_Login
ckr_user_type_invalid the token can't authenticate the user because there is no key database or the user's password isn't initialized.
NSC_InitToken
specifically, nsc_inittoken() initializes or clears the key database, removes the password, and then marks all the user certs in the certificate database as non-user certs.
NSC_Login
ckr_user_type_invalid the token can't authenticate the user because there is no key database or the user's password isn't initialized.
NSS tools : cmsutil
if this is the first encrypted message for that set of recipients, a new enveloped message will be created that you can then use for future messages (encrypt only).
NSS tools : crlutil
the key and certificate management process generally begins with creating keys in the key database, then generating and managing certificates in the certificate database(see certutil tool) and continues with certificates expiration or revocation.
OLD SSL Reference
upgraded documentation may be found in the current nss reference ssl reference newsgroup: mozilla.dev.tech.crypto writer: sean cotter manager: wan-teh chang chapter 1 overview of an ssl application ssl and related apis allow compliant applications to configure sockets for authenticated, tamper-proof, and encrypted communications.
NSS Tools certutil-tasks
(bugfix) listing provate keys does not work: requires password authentication.
NSS Tools cmsutil
if this is the first encrypted message for that set of recipients, a new enveloped message will be created that you can then use for future messages (encrypt only).
NSS Tools crlutil
the key and certificate management process generally begins with creating keys in the key database, then generating and managing certificates in the certificate database(see certutil tool) and continues with certificates expiration or revocation.
NSS Tools modutil
if the current platform cannot be found in the list of supported platforms, then the forwardcompatible list is checked for any platforms that have the same os and architecture in an earlier version.
NSS tools : cmsutil
MozillaProjectsNSStoolscmsutil
if this is the first encrypted message for that set of recipients, a new enveloped message will be created that you can then use for future messages (encrypt only).
NSS tools : crlutil
MozillaProjectsNSStoolscrlutil
the key and certificate management process generally begins with creating keys in the key database, then generating and managing certificates in the certificate database(see certutil tool) and continues with certificates expiration or revocation.
NSS tools : signver
MozillaProjectsNSStoolssignver
if the prefix sql: is not used, then the tool assumes that the given databases are in the old format.
The Necko HTTP module
rfc 2617 for the http/1.1 basic and digest authentication specifications.
Proxies in Necko
this proxy info will only be used if it specifies a socks proxy, through which the connection is then made.
Pork Tool Development
then any post-location variables refer to "foo" and pre-location variables refer to "my_foo".
Pork Tools
then nuke the declaration // nsresult rv; // move outparam to lhs var = getter(); // detect ns_ensure_success immediately following // and change it to an equivalent ns_ensure_true ns_ensure_true(var, ns_error_failure); // case 2 var = getter(); // case 3, eliminate rv2 decl given that it's not used elsewhere var = getter(); ns_ensure_true(var, ns_error_failure) } ...
Rhino downloads archive
if you are looking for js.jar for xslt or for ibm's bean scripting framework (bsf), please read the following note and then download one of the zip files above and unzip it.
Rhino FAQ
for instance, to create an array of java.lang.string of length five, do var stringarray = java.lang.reflect.array.newinstance(java.lang.string, 5); then if you wish to assign the string "hi" to the first element, simply execute stringarray[0] = "hi".
Rhino JavaScript compiler
the resulting java class files can then be loaded and executed at another time, providing a convenient method for transferring javascript, and for avoiding translation cost.
Rhino optimization
if the optimization package is not available, then optimization acts as if it is always -1.
Rhino overview
then, the class of the code that called to request the restricted action can be obtained by looking an appropriate index into the class context array.
Performance Hints
however, if you don't intend for any other function to access these variables, then storing them globally is probably wrong anyway (what if you called another function that had a loop like the one in sum!).
SpiderMonkey compartments
spidermonkey simply assumes that all objects referenced from outside the compartment are live, and then walks the object graph inside the compartment.
Getting SpiderMonkey source code
to do this, cd into the base directory you'd like to check out the code into, then enter the following command at your command line: cvs -d :pserver:anonymous@cvs-mirror.mozilla.org:/cvsroot login when prompted, enter the password anonymous.
64-bit Compatibility
for example, consider this code: #define pointer_tagbits 3 static inline uintptr_t unmaskpointer(uintptr_t v) { return v & ~pointer_tagbits; } the value 3 will be inverted to 0xfffffffc, then zero-extended to 0x00000000fffffffc - a subtle and nasty bug, assuming it is unintended.
Exact Stack Rooting
if we have a method taking handle<value>*, then out->setobject(foo) will not work as expected.
Self-hosted builtins in SpiderMonkey
e.g., if receiver is an object that content has access to, then callfunction(receiver.fun, receiver) wouldn't be guaranteed to work, because content might have changed the value of receiver.fun, so callcontentfunction(receiver.fun, receiver) has to be used.
JS::CallArgs
then, when an eventual release making that change occurs, porting efforts will require changing methods' signatures but won't require invasive changes to the methods' implementations, potentially under time pressure.
JS::CloneFunctionObject
if the class of funobj is not function, then js::clonefunctionobject returns funobj itself.
JS::Evaluate
if it is non-null, then on success, the result value is stored in *rval.
JS::Handle
first, when several such functions call each other then redundant rooting of multiple copies of the gc thing can be avoided.
JS::PersistentRooted
if there is any path from that referent back to the js object, then the c++ object containing the persistentrooted will not be destructed, and the whole blob of objects will not be freed, even if there are no references to them from the outside.
JS::SetLargeAllocationFailureCallback
the allocation will then be retried (and may still fail.) js::setlargeallocationfailurecallback sets a callback function for it.
JS::SourceBufferHolder
if ownership is not given to the sourcebufferholder, then the memory must be kept alive until the js compilation is complete.
JS::Value
the solution is to tell spidermonkey that you're using the object, then tell it again when you're done.
JSCheckAccessOp
jscheckaccessop implementations generally work by using jsdbgapi functions such as js_frameiterator and js_stackframeprincipals to obtain the principals of the code attempting the checked operation, then examining those principals and comparing them with the system's security policy.
JSObjectOps.enumerate
then it iterates over obj's defined properties, walking the internal data structure they're stored in.
JS_BufferIsCompilableUnit
the intent is to support interactive compilation - accumulate lines in a buffer until js_bufferiscompilableunit is true, then pass it to the compiler.
JS_ClearContextThread
description an application that creates or uses a jscontext in one thread, then uses or destroys it in another thread, must use js_clearcontextthread and js_setcontextthread to transfer the jscontext safely from one thread to the other.
JS_CloneFunctionObject
if the class of funobj is not function, then js_clonefunctionobject returns funobj itself.
JS_ConvertArguments
for example, if format is "biob", then js_convertarguments converts the first js value in argv into a bool, the second value into a double, the third value into a jsobject *, and the last value into a bool.
JS_DecompileFunction
if you decompile a function that does not make a native c call, then the text created by js_decompilefunction is a complete function declaration suitable for re-parsing.
JS_DefineFunction
it creates the new function object as though by calling js_newfunction, then makes it a method of obj as though by calling js_defineproperty.
JS_DefineProperty
if attrs contains the jsprop_getter (or jsprop_setter) flag, then getter (or setter) must point to a javascript function, not a c/c++ function.
JS_DefinePropertyWithTinyId
for example, if a property named "color" is defined with tiny id 10, then the javascript expressions obj[10] and obj.color will both result in int_to_jsval(10) being passed to jsclass.getproperty as the id parameter.
JS_DeleteProperty
then one of the following cases applies: if obj has no property with the given name or id, or if obj inherits the specified property from its prototype, then obj's jsclass.delproperty hook is called.
JS_EncodeString
if js_cstringsareutf8 is true, then the returned string of js_encodestring is utf-8, and the conversion is lossless.
JS_Enumerate
the property ids would then become unreachable and could be collected.
JS_EvaluateScript
if it is non-null, then on success, the result value is stored in *rval.
JS_GetFunctionId
if no smart name could be guessed for the function, then null is returned.
JS_GetGlobalForObject
for example, if the function refers to a global variable foo, then foo is a property of the object returned by js_getglobalforobject.
JS_GetNaNValue
in fact, it is not even equal to itself: if x is nan, then x != x.
JS_GetOwnPropertyDescriptor
if desc->obj is null, then this property was not found on the prototype chain.
JS_GetPrivate
casting that pointer to the desired type and using it could then cause a crash or worse.
JS_GetPropertyDescriptor
if desc->obj is null, then this property was not found on the prototype chain.
JS_GetReservedSlot
description if a jsclass has jsclass_has_reserved_slots(n) in its flags, with n > 0, or has a non-null jsclass.reserveslots callback, then objects of that class have n reserved slots in which the application may store data.
JS_GetRuntimePrivate
it is especially useful for storing data which callbacks may then easily access.
JS_GetStringBytes
if js_cstringsareutf8 is true, then the returned string is utf-8, and the conversion is lossless.
JS_Init
it is currently not possible to initialize spidermonkey multiple times (that is, calling js_init, jsapi methods, then js_shutdown in that order, then doing so again).
JS_LeaveLocalRootScopeWithResult
if there is an enclosing local root scope, then rval is transferred to it.
JS_NewCompartmentAndGlobalObject
description js_newcompartmentandglobalobject creates a new compartment, and then creates a new global object as the first object in that compartment.
JS_NewStringCopyZ
description js_newstringcopyz allocates space for a new javascript string and its underlying storage, and then copies the contents of a null-terminated character array, s, into the new string.
JS_ObjectIsFunction
description js_objectisfunction tests whether obj is a function object (faster than comparing obj's class name to function, but equivalent unless someone has overwritten the function identifier with a different constructor and then created instances using that constructor that might be passed in as obj).
JS_PreventExtensions
before then, js_preventextensions did not accept a succeeded argument; in those cases where *succeeded would be set to false, js_preventextensions would throw a typeerror and return false.
JS_PushArguments
for example, if format is "biob", then there must be four arguments after format.
JS_ReportError
the callback must then return js_false to cause the exception to be propagated to the calling script.
JS_SaveExceptionState
that object may then be used to restore again the context using js_restoreexceptionstate, or discarded using js_dropexceptionstate.
JS_ScheduleGC
at this point, if zeal is one of the types that trigger periodic collection, then nextscheduled is reset to the value of frequency.
JS_SetCallReturnValue2
this reference value can then be used as an lvalue in script.
JS_SetGCCallback
but the javascript engine will then detect that gc is already happening and will not actually do a nested gc cycle in this case.
JS_SetPropertyAttributes
then, if the property exists, but is associated with a different object, js_setpropertyattributes returns js_true.
JS_ShutDown
it is currently not possible to initialize spidermonkey multiple times (that is, calling js_init, then other jsapi methods, then js_shutdown in that order, then doing so again).
JS_StringHasLatin1Chars
clients can use js_stringhaslatin1chars and can then call either the latin1* or twobyte* functions.
JS_SuspendRequest
since then, a jsruntime is tied to the thread that created it; it may not be accessed by any other thread.
JS_THREADSAFE
then use js_readstructuredclone on the other side to turn the serialized data back into javascript objects, strings, and so on.
JS_malloc
then it frees the region at p and returns a pointer to the new region.
Property attributes
if the property is also jsprop_permanent, then certain aspects of inheriting the property via the prototype chain are affected.
SpiderMonkey 1.8.5
instead, jsvals should be converted to their c equivalents with the appropriate jsval_to_* macro and then compared.
SpiderMonkey 1.8.7
instead, jsvals should be converted to their c equivalents with the appropriate jsval_to_* macro and then compared.
SpiderMonkey 1.8
specifically, if a property lookup first calls a resolve hook which does not define the property, then finds the property on a prototype, that result can be cached.
Running Automated JavaScript Tests
the next time it is run, it will run only the tests in the given filename, and then will write the list of tests that failed when it is done.
SavedFrame
asynccause if this stack frame is the asyncparent of other stack frames, then this is a string representing the type of asynchronous call by which this frame invoked its children.
Setting up CDT to work on SpiderMonkey
if you want to use ccache: select "c/c++ general", then "preprocessor include patterns".
TPS Password Lists
used for http authentication passwords.
Zest runtimes
python no code available yet if you are interested in working on an existing or new zest runtime then please get in touch via the zest group.
Using RAII classes in Mozilla
however, there are some variations for special cases: first, if the constructor (otherwise) takes no arguments, then you have to use the moz_guard_object_notifier_only_param macro instead.
A Web PKI x509 certificate primer
*.yourcompany.com) but you want others outside of your organization to be able to browse to your website using https without having to manually import a root certificate, then you can get an ssl certificate from one of the cas who already have a root certificate included in the major browsers.
Gecko object attributes
sort if "ascending" or "descending", then child items within the container are currently sorted as indicated.
Gecko Roles
role_popup_menu a temporary window that is usually used to offer the user a list of choices, and then hides when the user selects one of those choices.
Gecko states
if this second state is defined, then clients can communicate the information about the object to users.
AT Development
then comtypes gives access to msaa and iaccessible2.
Embedded Dialog API
applications which implement merely the simplest, base gecko windowing api will then have a mixture of xul and native windows.
The Places database
there are several ways for orphans to be created, including calling markpageastyped and then never visiting the page.
Places Developer Guide
getservice(components.interfaces.nspiplacesdatabase).dbconnection; } and then to get the a redirected visit_id from another visit_id: function getfromvisit(visit_id) { var sql = <cdata><![cdata[ select from_visit from moz_places, moz_historyvisits where moz_historyvisits.id = :visit_id and moz_places.id = moz_historyvisits.place_id; ]]></cdata>.tostring(); var sql_stmt = getplacesdbconn.createstatement(sql); sql_stmt.params.visit_id = visit_id; var fro...
Places Expiration
on idle on idle it expires a larger chunk of pages, then timed expiration is stopped.
Retrieving part of the bookmarks tree
before accessing the children of any result container, you must first open it, and then you can iterate the children.
Using the Places annotation service
but then again you won't know if the exception meant that the annotation did not exist or something else is broken.
Using the Places history service
the parameters within on query as anded together as in executequery(), then the results of the different queries in the array are ored together.
Using the Places livemark service
the update timer fires immediately, and then every 15 minutes thereafter.
places.sqlite Database Troubleshooting
then open an sqlite shell: my_work_folder> sqlite3 places.sqlite-corrupt sqlite> pragma integrity_check; if the result is ok, this guide won't help; stop here and please file a bug.
Accessing the Windows Registry Using XPCOM
if you are writing an extension that only needs to support firefox 1.5 or newer, then you only need to read this section.
Aggregating the In-Memory Datasource
then the queryinterface() will be forwarded back to you, and we'll recurse off to infinity (and beyond!...
Bundling multiple binary components
the stub component is an xpcom component itself and when registered by xpcom, the code would sniff the runtime version and operating system then the stub load the appropriate "real" xpcom component for the current configuration.
XPCOM array guide
MozillaTechXPCOMGuideArrays
when the array can or should be modified, then use nsimutablearray: // array is read-only because it uses nsiarray void printsize(nsiarray* elements) { pruint32 count; elements->getlength(&count); printf("there are %d elements.\n", count); } // using nsimutablearray, so callee may modify void tweakarray(nsimutablearray* elements) { elements->removeelementat(0); elements->appendelement(newelement, pr_false); } while it is usually...
Packaging WebLock
if you are installing weblock in an gecko-based application for which xpinstall is not available, then you will have to devise a separate installation scheme.
Making cross-thread calls using runnables
each runnable represents a task which can then be dispatched to another thread for execution.
XPCOM hashtable guide
in their implementation, hashtables take the key and apply a mathematical hash function to randomize the key and then use the hash to find the location in the hashtable.
Detailed XPCOM hashtable guide
in their implementation, hashtables take the key and apply a mathematical hash function to randomize the key and then use the hash to find the location in the hashtable.
mozilla::services namespace
to use it, you first need to include the header into your c++ file: #include "mozilla/services.h" then you can obtain references to services by simply accessing them from the mozilla::services namespace.
XPCOM guide
MozillaTechXPCOMGuide
ocument attempts to help them do so, first by explaining the underlying concepts, and second by describing a number of common javascript patterns that cause leaks.creating xpcom componentsthis guide is about gecko, and about creating xpcom components for gecko-based applications.how to build an xpcom component in javascriptif you are looking for add-on sdk solution for xpcom javascript components then check out platform/xpcom module first.inheriting from implementation classesgiven that idl interfaces map to abstract classes in c++, a common problem when dealing with idl is when you have an idl inheritance hierarchy, and a corresponding c++ implementation hierarchy, you run into multiple inheritance.
Components.classes
if the given element in the components.classes object is not registered on the machine then trying to access it will generate a javascript warning in strict mode and the value returned will be the javascript value undefined.
Components.interfaces
for example, assume we have the following interface declaration: interface nsifoo : nsisupports { const pruint32 myflag = 5; }; the constant myflag can then be accessed using var myflag = components.interfaces.nsifoo.myflag; ...
Components.lastResult
if (e instanceof components.interfaces.nsixpcexception) { // we might do something interesting here with the exception object var rv = e.result; } else { // if we don't know how to handle it then rethrow throw e; } } ...
Components.returnCode
if the javascript code needs to signal failure then that is done by throwing an exception.
Components.utils.createObjectIn
: value }; } var myobject = components.utils.createobjectin(mywindow); var proplist = { name: genpropdesc("name"), date: genpropdesc("date"), id: genpropdesc("id"), func: genpropdesc(function() { alert("called func!"); }) }; object.defineproperties(myobject, proplist); components.utils.makeobjectpropsnormal(myobject); this sets up the new object in the scope of the object mywindow, then adds properties by calling object.defineproperties(), then normalizes them by calling components.utils.makeobjectpropsnormal().
Components.utils.evalInWindow
if this is just native (for example, a dom node), then the function relies on xraywrappers to wrap the returned content, otherwise the result is structured-cloned.
Components.utils.getGlobalForObject
an object whose corresponding global object is to be retrieved; non-optional, must be object-valued example var obj = {}; function foo() { } var global = this; var g1 = components.utils.getglobalforobject(foo); var g2 = components.utils.getglobalforobject(obj); // g1 === global, g2 === global, g1 === g2 // in a script in another window var global2 = this; function bar() { } var obj2 = {}; // then, assuming bar refers to the function defined in that other window: var o1 = components.utils.getglobalforobject(bar); var o2 = components.utils.getglobalforobject(obj2); // o1 === global2, o2 === global2 ...
Components.utils.getWeakReference
and then later on it is matched in the array and used.
Components.utils.unload
if the javascript code module has not yet been imported then this method will do nothing.
Using components
commonly, we start our scripts like so: var cc = components.classes; var ci = components.interfaces; if we want to get a hold of a component, we then do something like: var rc = cc["@mozilla.org/registry;1"]; var rs = rc.getservice(ci.nsiregistry); see also: xpcshell -- how to get a command line interface to javascript more info as was already stated, it is common to start addon scripts like: var cc = components.classes; var ci = components.interfaces; there is also another way to start, which is exactly equivalent to the above.
XPConnect wrappers
if you call 'tostring()' and get "[xpconnect wrapped nsifoo]" then the reference is to a xpcwrappednative object with interface nsifoo.
appShellService
then again, there's a much easier way; one of the xpcshell extensions is a quit function: quit(3) ...
XPCShell Reference
for example, if you created anobject with a property named value and then called clear(anobject), the property value would no longer exist.
Monitoring HTTP activity
pe == nsihttpactivityobserver.activity_type_http_transaction) { switch(aactivitysubtype) { case nsihttpactivityobserver.activity_subtype_response_header: // received response header break; case nsihttpactivityobserver.activity_subtype_response_complete: // received complete http response break; } } } }; then you need to install your activity observer.
Observer Notifications
if your component requires access to the user profile, or any services which require access to the profile (preferences, bookmarks, and so on) then a common pattern is to register with the nsicategorymanager for the app-startup topic which can be done in the component's registration code, and then in that notification register with the observer service for the profile-after-change notification.
NS_ConvertASCIItoUTF16
if size_type(-1) is passed for newlen, then the current length of the string is used.
NS_ConvertUTF16toUTF8
if size_type(-1) is passed for newlen, then the current length of the string is used.
NS_ConvertUTF8toUTF16
if size_type(-1) is passed for newlen, then the current length of the string is used.
NS_LossyConvertUTF16toASCII
if size_type(-1) is passed for newlen, then the current length of the string is used.
nsACString
if used with xpidl, then the character encodings of the corresponding xpidl data types applies.
nsACString_internal
if size_type(-1) is passed for newlen, then the current length of the string is used.
nsAString
if used with xpidl, then the character encodings of the corresponding xpidl data types applies.
nsAString_internal
if size_type(-1) is passed for newlen, then the current length of the string is used.
nsAdoptingCString
if size_type(-1) is passed for newlen, then the current length of the string is used.
nsAdoptingString
if size_type(-1) is passed for newlen, then the current length of the string is used.
nsAutoString
if size_type(-1) is passed for newlen, then the current length of the string is used.
nsCAutoString
if size_type(-1) is passed for newlen, then the current length of the string is used.
nsCString
if size_type(-1) is passed for newlen, then the current length of the string is used.
nsDependentCString
if size_type(-1) is passed for newlen, then the current length of the string is used.
nsDependentCSubstring
if size_type(-1) is passed for newlen, then the current length of the string is used.
nsDependentString
if size_type(-1) is passed for newlen, then the current length of the string is used.
nsDependentSubstring
if size_type(-1) is passed for newlen, then the current length of the string is used.
nsEmbedCString
if equal to pr_uint32_max, then adata is assumed to be null-terminated.
nsEmbedString
if equal to pr_uint32_max, then adata is assumed to be null-terminated.
nsFixedCString
if size_type(-1) is passed for newlen, then the current length of the string is used.
nsFixedString
if size_type(-1) is passed for newlen, then the current length of the string is used.
Realloc
remarks if aptr is non-null, then its contents will be unchanged to the minimum of the old and new sizes.
nsMemory
however, if you use these functions in your xpcom component, and if you link to the xpcom glue library, then your component will only have a runtime dependency on the frozen xpcom api.
nsPromiseFlatCString
if size_type(-1) is passed for newlen, then the current length of the string is used.
nsPromiseFlatString
if size_type(-1) is passed for newlen, then the current length of the string is used.
nsString
if size_type(-1) is passed for newlen, then the current length of the string is used.
nsXPIDLCString
if size_type(-1) is passed for newlen, then the current length of the string is used.
nsXPIDLString
if size_type(-1) is passed for newlen, then the current length of the string is used.
IAccessibleEditableText
this method is equivalent to calling first deletetext() with the two indices and then calling inserttext() with the replacement text at the start index.
imgIEncoder
the alternative is to use startimageencode(), call addimageframe() one or more times, and then finish initialization with endimageencode().
mozIPlacesAutoComplete
match_boundary_anywhere 1 match first on word boundaries, and if we do not get enough results, then match anywhere in each searchable term.
mozIRegistry
one could then make the nsrepository itself a service and permit full (?!) de-coupling of xpcom modules from the xpcom implementation.
mozIStorageService
and then the database can be opened again with the mozistorageservice.opendatabase() method.
mozIStorageStatementWrapper
you can then wrap that statement with a wrapper, which implements nsixpcscriptable and provides scriptable helpers letting you execute the statement as a function, access bind variables by name as properties, etc.
nsIAccessNode
if the dom node for this access node is "accessible", then a queryinterface to nsiaccessible will succeed.
GetChildAtPoint
if the point is in neither the current accessible or a child, then null will be returned.
nsIAccessible
relations many accessibles are linked with each other, for example, if one accessible gives the accessible name for another accessible (for example, html:label and html control) then these accessibles are related, please refer to relations documentation for more information.
nsIAccessibleDocument
if a <div> is contenteditable, then it has its own document, with iseditable == true.
nsIAccessibleHyperLink
also, state_focused should then be set on the accessible for this link.
nsIAccessibleRole
role_popup_menu 83 a temporary window that is usually used to offer the user a list of choices, and then hides when the user selects one of those choices.
nsIAccessibleStates
if this second state is defined, then clients can communicate the information about the object to users.
nsIAccessibleTable
if both row and column index are valid then the corresponding accessible object is returned that represents the requested cell regardless of whether the cell is currently visible (on the screen).
nsIAccessibleText
if set < 0 then caret will be placed at the end of the text.
nsIAccessibleTreeCache
if is is null then the primary column is used.
nsIAuthPrompt
netwerk/base/public/nsiauthprompt.idlscriptable this interface allows the networking layer to pose a user/password prompt to obtain the values needed for authentication.
nsIBlocklistPrompt
the prompt is then responsible for soft-blocking any addons that need to be afterwards.
nsIBrowserSearchService
this is not an issue if your code is executed in reaction to a user interaction, as initialization is complete by then, but this is an issue if your code is executed during startup.
nsIClipboardDragDropHookList
note: if this implementation is not present in the list then removal will be ignored.
nsICycleCollectorListener
1.0 66 introduced gecko 2.0 inherits from: nsisupports last changed in gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) the order of calls will be call to begin(); then for every node in the graph a call to noteobject() and calls to noteedge() for every edge starting at that node; then a call to begindescriptions(); then for every black node in the cycle collector graph a call to either describerefcountedobject() or to describegcedobject(); and then a call to end().
nsIDBChangeListener
the calling function stores the value of astatus, changes the header ahdrtochange, then calls onhdrpropertychanged again with aprechange false.
nsIDNSService
if this parameter is null, then onlookupcomplete will be called on an unspecified thread (possibly recursively).
nsIDOMNSHTMLDocument
for instance, if there is a selection and part of the selected text is bold, then then bold command is in an indeterminate state.
nsIDOMStorageEventObsolete
if the value of the domain attribute is "#session", then the session storage has changed.
nsIDOMWindowUtils
you can then use that object with dom methods that use the file api.
nsIDOMXPathEvaluator
ssion createexpression(in domstring expression, in nsidomxpathnsresolver resolver) nsidomxpathnsresolver creatensresolver(in nsidomnode noderesolver); nsisupports evaluate(in domstring expression, in nsidomnode contextnode, in nsidomxpathnsresolver resolver, in unsigned short type, in nsisupports result) methods createexpression() creates an nsidomxpathexpression which can then be used for (repeated) evaluations.
nsIDOMXULElement
click() unless the element is disabled, sends mouse events that simulate the effect of clicking the mouse on the element, then calls the docommand() method.
nsIDataSignatureVerifier
apublickey the public part of the key used for signing, der encoded then base64 encoded.
nsIDebug
if no debugger is running then this usually results in a program crash.
nsIDirIndexListener
they can then be transformed into an output format (such as rdf, html and so on) inherits from: nsisupports last changed in gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0) method overview void onindexavailable(in nsirequest arequest, in nsisupports actxt, in nsidirindex aindex); void oninformationavailable(in nsirequest arequest, in nsisupports actxt, in astring ainfo); methods onindexavailable() called for each directory entry.
getFile
if false, then the directory service will not cache the results of this method.
nsIDownloadManager
if you want to both add and start a download, you need to create an nsiwebbrowserpersist object, call this method, set the progresslistener to the returned nsidownload object, and then call the nsiwebbrowserpersist.saveuri() method.
nsIDownloadProgressListener
inherits from: nsisupports last changed in gecko 1.9.1 (firefox 3.5 / thunderbird 3.0 / seamonkey 2.0) to use simply implement this interface in your code, then call nsidownloadmanager.addlistener() to start listening.
nsIDownloader
if an explicit download location is specified then the resulting file will not be deleted, and it will be the callers responsibility to keep track of the file, and so on.
nsIErrorService
if no key is registered for the specified nsresult, then the caller should use the nsresult's code (obtained with ns_error_get_code) instead.
nsIEventTarget
if this method succeeds, then the event will be dispatched on the target thread.
nsIFeedProcessor
the caller must then call the processor's nsistreamlistener methods to drive the parsing process.
nsIFilePicker
the filter appended first will be used to display the nsifilepicker dialog, the user may then select another from the list.
nsIFileProtocolHandler
if the nsifile is a local file, then the result will be a file:// url string.
nsIFrameScriptLoader
if this function is called on a chromemessagebroadcaster (for example, a global frame message manager or a window message manager) then: loadframescript() will load the frame script independently into each applicable frame: every open frame in the given window for the window message manager, or every frame in every window for the global message manager if aallowdelayedload is true, then the script will also be loaded into any applicable new frames opened after the loadframescript() call.
nsIGlobalHistory3
if they do so, then callers must call nsiglobalhistory2.adduri() upon getting the ns_error_not_implemented result.
nsIHTMLEditor
adeleteselection delete the selection before inserting if adeleteselection is pr_false, then the element is inserted after the end of the selection for all element except named anchors, which insert before the selection.
nsIHTTPHeaderListener
the browser will then qi this streamlistener to see if it implements nsihttpheaderlistener.
nsIHttpServer
if the handler throws an * exception during server operation, fallback is to the genericized error * handler (the x00 version), then to 500, using a user-defined error * handler if one exists or the server default handler otherwise.
nsIIDNService
this combines two operations: running the rfc 3490 "tounicode" operation on the original string, then converting the resulting unicode string into utf-8 format.
nsIInputStream
if a stream is at end-of-file, but not closed, then this method returns 0 bytes available.
nsIJetpack
if the message was sent synchronously from the jetpack process via callmessage(), then the return value of this function is passed back to the jetpack process.
nsILoginManagerStorage
this method is called by the login manager when looking for saved logins that might apply to a form or authentication request.
nsIMemoryReporter
1.0 66 introduced gecko 1.9 inherits from: nsisupports last changed in gecko 8.0 (firefox 8.0 / thunderbird 8.0 / seamonkey 2.5) any piece of code that wishes to allow its memory use to be monitored may create an nsimemoryreporter object and then register it by calling nsimemoryreportermanager.registerreporter().
nsIMessageListener
if the message was sent from a frame script using a nsicontentframemessagemanager, then this property is the xul <browser> element for the frame from which the message was sent.
nsIMicrosummaryService
if its value is null, then it's an async refresh, and the caller should register itself as an nsimicrosummaryobserver via nsimicrosummary.addobserver() to find out when the refresh completes.
nsIModule
if the component module is native (that is, as part of a dll), then this method may be called to determine whether or not the dll may be unloaded from memory.
nsIMsgAccount
exceptions thrown ns_error_already_opened if it is called more then once removeidentity() removes an identity from this account.
nsIMsgDBHdr
if you want to know whether the message is the root of an ignored subthread then you should check for the ignored flag.
nsIMsgDatabase
the idea is that you create a new header, fill in its properties, and then call addnewhdrtodb.
nsIMsgIncomingServer
loginatstartup boolean logonfallback boolean maxmessagesize long offlinesupportlevel long password acstring passwordpromptrequired boolean if the password for the server is available either via authentication in the current session or from password manager stored entries, return false.
nsIMsgSearchSession
to create an instance, use: var searchsession = components.classes["@mozilla.org/messenger/searchsession;1"] .createinstance(components.interfaces.nsimsgsearchsession); to use the instance append search terms, set the scope, and then call search().
nsINavBookmarkObserver
in this situation, you should not attempt to get any properties, since this will result in the automatic regeneration of properties that will then be leaked into the database, causing trouble later.
nsINavBookmarksService
if ownsweak is true, then aobserver must implement nsisupportsweakreference, and the bookmark service will keep a weak reference to the observer.
nsINavHistoryResult
the viewer then tells the actual view object what to do.
nsINavHistoryResultObserver
the observer can then pause updates or events until the batch is completed, so that it won't handle the large number of updates that are about to be notified.
nsINavHistoryService
if ownsweak is true, then aobserver must implement nsisupportsweakreference, and the history service will keep a weak reference to the observer.
Component; nsIPrefBranch
note: if a preference was manually set to a value that equals the default value, then the preference no longer has a user set value, i.e.
nsIPrintingPrompt
you can then fly you own dialog and then properly fill in the printsettings object before calling nsiwebbrowserprint's print method.
nsIProcessScriptLoader
if aallowdelayedload is true, then the script will also be loaded into any new child processes created after the loadprocessscript() call.
nsIProtocolHandler
if this is null, then utf-8 encoding is assumed and no character transformation is not performed.
nsIProxyInfo
if a nsiproxyinfo is reported as failed via nsiprotocolproxyservice.getfailoverforproxy(), then the failed proxy will not be used again for this many seconds.
nsIRequest
note: this will prevent proxy authentications from working, so use this flag with caution.
nsISHEntry
if either contentviewer or windowstate are null, then all of the following members are cleared/reset: contentviewer, sticky, windowstate, viewerbounds, childshells, refreshurilist.
nsIScriptableInputStream
warning: if the data contains a null byte, then this method will return a truncated string.
nsIServerSocketListener
if the server socket was manually closed, then this value will be ns_binding_aborted.
nsISpeculativeConnect
then call speculativeconnect() to let the networking layer know what you might be doing in the future.
nsIStreamConverter
it will then convert that data from type x to your desired output type and return converted data to you via the nsistreamlistener you passed in by calling its nsistreamlistener.ondataavailable() method.
nsIStringBundleOverride
if there is no custom-strings.txt file then the service will fail to load.
nsISupports proxies
if you have created the object yourself and then created the proxy, please note that you will have at least a refcount of 2 (one for the proxy and one for the created object which you passed into getproxyobject, plus any other refcounts which you may have).
nsITaskbarPreview
note: changing this value is computationally expensive for tab previews, because doing so causes the proxy window to be destroyed and rebuilt, then re-registered with the taskbar.
nsIThreadEventFilter
you should implement this interface and its acceptevent() method, then pass the object implementing it as the filter.
nsITimer
if the callback takes a long time, then the next callback will be scheduled immediately afterward, but only once, unlike type_repeating_precise.
nsIToolkitProfileService
the profile list file is constructed in memory, then written out as one large chunk, in order to reduce the risk of the profile list file being corrupted by disk errors.
nsITraceableChannel
.nsistreamlistener) || aiid.equals(ci.nsisupports)) { return this; } throw cr.ns_nointerface; } }; var httpresponseobserver = { observe: function(asubject, atopic, adata) { var newlistener = new tracinglistener(); asubject.queryinterface(ci.nsitraceablechannel); newlistener.originallistener = asubject.setnewlistener(newlistener); /////// end - do not edit newlistener.promisedone.then( function() { // no error happened console.log('yay response done:', newlistener.responsebody); }, function(areason) { // promise was rejected, right now i didnt set up rejection, but i should listen to on abort or bade status code then reject maybe } ).catch( function(acatch) { console.error('something went wrong, a typo by dev probably:', acatch); } ); } }...
nsITreeColumn
cycler boolean if true, then the column is a cycler column.
nsIUpdate
toolkit/mozapps/update/nsiupdateservice.idlscriptable an interface that describes an object representing an available update to the current application - this update may have several available patches from which one must be selected to download and install, for example we might select a binary difference patch first and attempt to apply that, then if the application process fails fall back to downloading a complete file-replace patch.
nsIUploadChannel
in the case of http, if this parameter is non-empty, then its value will replace any existing content-type header on the http request.
nsIUserInfo
to get the service, use: var userinfo = components.classes["@mozilla.org/userinfo;1"] .getservice(components.interfaces.nsiuserinfo); you can then look at the userinfo object's attributes to learn what the system knows about the user.
nsIWebBrowserChrome2
if statustype is status_link, then this may be a dom node corresponding to the source of the link.
nsIWebProgressListener2
note: if any progress value is unknown, then its value is replaced with -1.
nsIXSLTProcessor
if a document node then the document can contain either a xslt stylesheet or a lre stylesheet.
nsIXULAppInfo
example display the application and the gecko version in an alert box: var info = components.classes["@mozilla.org/xre/app-info;1"] .getservice(components.interfaces.nsixulappinfo); alert("application version: " + info.version + "\n" + "gecko version: " + info.platformversion); example this example here uses nsixulappinfo to get the version of the current browser and then compares it: example - compare current browser version see also using nsixulappinfo nsixulruntime get thunderbird version firefox code snippets ...
nsIXULTemplateQueryProcessor
the builder will then call compilequery() for each query in the template to compile the queries.
nsIZipReader
then you can copy and paste this code in scratchpad to run it.
NS_CStringAppendData
if equal to pr_uint32_max, then adata is assumed to be null-terminated.
NS_CStringInsertData
if equal to pr_uint32_max, then adata is assumed to be null-terminated.
NS_CStringSetData
if equal to pr_uint32_max, then adata is assumed to be null-terminated.
NS_CStringSetDataRange
if equal to pr_uint32_max, then adata is assumed to be null-terminated.
NS_StringAppendData
if equal to pr_uint32_max, then adata is assumed to be null-terminated.
NS_StringInsertData
if equal to pr_uint32_max, then adata is assumed to be null-terminated.
NS_StringSetData
if equal to pr_uint32_max, then adata is assumed to be null-terminated.
NS_StringSetDataRange
if equal to pr_uint32_max, then adata is assumed to be null-terminated.
Warnings
when you do not use an index, all the results from the query have to first be fetched, and then those results are sorted.
Frequently Asked Questions
for example, the assertion occurs when you convert the pointer to the object to a raw pointer to that interface, then assign the raw pointer to another nscomptr for that interface.
Using nsIClassInfo
if you use a c++ class which implements nsiclassinfo from javascript, then you don't have to explicitly call queryinterface on the javascript object to access the object's interfaces.
Using nsIDirectoryService
in order to change these locations using nsifilelocator and still be able to use the same components directory as an existing mozilla installation, you had to make a component with the same id as nsifilelocator and then, after auto-registering components, manually register your own and replace the existing one -- all in all, a big pain.
Using the Gecko SDK
if your component does not use any of the glue classes or functions, then you do not need to link against the glue library.
Working with out parameters
assuming you have an object called transferable, you would invoke gettransferdata() as follows: var adata = {}; var adatalen = {}; transferable.gettransferdata("text/unicode", adata, adatalen); var data = adata.value; var datalen = adatalen.value; as you can see, after the call to gettransferdata(), the out values are then contained in the value properties of adata and adatalen.
XPCOM category image-sniffing-services
if mozilla's built-in image code cannot identify an image, then any xpcom components implementing the nsicontentsniffer interface may register under the "image-sniffing-services" category, and will be queried to determine the mime type of the image being downloaded.
nsCOMPtr versus RefPtr
in the future, more base classes might be added to t that would then cause unrelated code to break, which would be very confusing.
xptcall FAQ
these stubs forward calls to a shared function whose job it is to use the typelib information to extract the parameters from the platform specific calling convention to build an array of variants to hold the parameters and then call an inherited method which can then do whatever it wants with the call.
XPCOM
you'll have to turn to the xpcom newsgroup or another experienced nscomptr user, or find the answer by experimentation.using nsiclassinfoif you use a c++ class which implements nsiclassinfo from javascript, then you don't have to explicitly call queryinterface on the javascript object to access the object's interfaces.using nsidirectoryservicensdirectoryservice implements the nsiproperties interface.
Generating xpt on Windows
assuming you installed your xulrunner sdk at <mozsdkdir>, you then need to issue a command similar to c:\working-dir> <mozsdkdir>\sdk\bin\typelib.py <inputfile.idl> -o <outputfile.xpt> -i <mozsdkdir>\idl ...
XUL Overlays
MozillaTechXULOverlays
the layout engine loads any overlay files and then flows the resulting xul document, so problems associated with incremental insertion in menus, boxes, tables, and forms are avoided.
Address book sync client design
then apply the server changes back // to the local database (updating the crc's in the process).
Cached compose window FAQ
we could just hide it on send, and then show it on the next compose.
Creating a gloda message query
you find these by first finding a message and then accessing its "conversation" attribute.
Gloda examples
instead you need to do two queries, first to get the "identity" object for an email address and then to get the messages.
Mail composition back end
(it's a minor difference.) prbool dont_deliver_p, - if "dont_deliver_p" is false, then we actually deliver the message to the smtp and/or nntp server nsmsgdelivermode mode, - mode is the delivery mode.
Thunderbird Configuration Files
this will depend on which distribution you use), navigate to the profile folder, and right-click in some empty space on the right pane, then select new document > empty document.
Finding the code for a feature
then i use mxr and look for "cmd_tag".
Access Window
register a timer window.setinterval( function() { alert('foobar'); }, 60000); //execute the function once very minute if you periodically need to perform a certain action then you can use the setinterval function, it will then call this function every x milliseconds, in this case every 60000ms or one minute.
Filter Incoming Mail
by example, setting it to lower case subject = subject.tolocalelowercase(); // then we rebuild a subject objet by rencoding the string // and assign it to the message headers and we're done amsghdr.subject = mimeconvert.encodemimepartiistr_utf8(subject, false, "utf-8", 0, 72); } } }; function init() { var notificationservice = components.classes["@mozilla.org/messenger/msgnotificationservice;1"] .getservice(components.interfaces.nsimsgfoldernotifica...
Using the Multiple Accounts API
then he or she must use myisp's smtp server, no matter what identity they will be sending mail with.
libmime content type handlers
the primary * purpose of these handlers will be to represent the attached data in a * viewable html format that is useful for the user * * note: these will all register by their content type prefixed by the * following: mimecth:text/vcard * * libmime will then use nscomponentmanager::contractidtoclsid() to * locate the appropriate content type handler */ #ifndef nsimimecontenttypehandler_h_ #define nsimimecontenttypehandler_h_ typedef struct { prbool force_inline_display; } contenttypehandlerinitstruct; #include "prtypes.h" #include "nsisupports.h" #include "mimecth.h" // {20dabd99-f8b5-11d2-8ee0-00a024a7d144} #define ns_imim...
Toolkit version format
if at some point a version part of one version string is greater than the corresponding version part of another version string, then the first version string is greater than the other one.
Using C struct and pointers
the call to structtype() returns a ctype object, and we then apply the new operator to it to create a specific instance of this newly defined type - a javascript representation of the c struct.
Declaring and Using Callbacks
this can all be done in a single line of code, like so: var callback = ctypes.functiontype(...).ptr(function(...) {...}); note: the use of .ptr() here isn't a method call; we're accessing a property that dynamically creates a callable object, and then invoking the result.
Working with ArrayBuffers
pixelbuffer.tostring(); // "ctypes.uint8_t.ptr(ctypes.uint64("0x352e0000"))" var imgwidth = 400; var imgheight = 400; var myimgdat = new imagedata(imgwidth, imgheight); method 1: passing arraytype cdata to uint8clampedarray.prototype.set one method is to get into a js-ctypes array, and then set it into the imagedata, as illustrated by the following code example.
ArrayType
exceptions thrown typeerror type is not a ctype, or type.size is undefined.if the length is specifed but if it is not a valid one,then it is also thrown rangeerror the size of the resulting array can't be represented as both a size_t and as a javascript number.
Int64
the string is then converted into the corresponding 64-bit integer value.
UInt64
the string is then converted into the corresponding 64-bit integer value.
Browser Side Plug-in API - Plugins
npn_getauthenticationinfo this function is called by plug-ins to get http authentication information from the browser.
Streams - Plugins
the stream processes all byte-range requests, and then is placed in seek mode (either explicitly in npp_newstream, or implicitly by a call to npn_requestread).
URLs - Plugins
for protocols in which the headers must be distinguished from the body, such as http, the buffer or file should contain the headers, followed by a blank line, then the body.
Version, UI, and Status Information - Plugins
it then uses the netscape_minor version number to find out if the windowless feature, represented by the npvers_has_windowless constant, is supported.
Gecko Plugin API Reference - Plugins
npn_getauthenticationinfo this function is called by plug-ins to get http authentication information from the browser.
Introduction to DOM Inspector - Firefox Developer Tools
the dom inspector keeps track of all the windows that are open, so to inspect the dom of a particular window in the dom inspector, simply access that window as you would normally and then choose its title from this dynamically updated menulist.
DOM Inspector - Firefox Developer Tools
you can install the sidebar panel via edit > preferences > advanced > dom inspector, then simply open up the inspector panel and visit a website.
Application - Firefox Developer Tools
if you can’t see it there, you can enable it by going to the "three dot" menu and selecting settings (also accessible by pressing f1), then checking the application checkbox under default developer tools.
Debug eval sources - Firefox Developer Tools
this source is then listed in the source list pane, and can be opened and debugged like any other source.
Open the debugger - Firefox Developer Tools
press the menu button ( ), select "developer", then "debugger".
Search - Firefox Developer Tools
press shift + ctrl + f (windows and linux) or shift + cmd + f (macos) and then enter the string you are trying to find.
Set watch expressions - Firefox Developer Tools
to set a watch expression, expand the watch expressions sidebar, then click "add watch expression." type the expression you'd like to watch into the text field.
Set a conditional breakpoint - Firefox Developer Tools
you'll then see a textbox where you can enter the expression.
Set a logpoint - Firefox Developer Tools
(either press esc or select the elipsis menu (...) and then click show split console.) when should you use logpoints?
Tutorial: Show Allocations Per Call Path - Firefox Developer Tools
makefactory('div'); var spanfactory = makefactory('span'); function divsandspans() { for (i = 0; i < 10; i++) { var div = divfactory('div #' + i); div.appendchild(spanfactory('span #' + i)); document.body.appendchild(div); } } function dodivsandspans() { divsandspans(); } </script> open the browser console (menu button > developer > browser console), and then evaluate the expression demotrackallocations() in the browser console.
Debugger-API - Firefox Developer Tools
cross-thread, cross-process, and cross-device tools must use debugger to observe the debuggee from within the same thread, and then handle any needed communication themselves.
All keyboard shortcuts - Firefox Developer Tools
shift + f4 shift + f4 run scratchpad code ctrl + r cmd + r ctrl + r run scratchpad code, display the result in the object inspector ctrl + i cmd + i ctrl + i run scratchpad code, insert the result as a comment ctrl + l cmd + l ctrl + l re-evaluate current function ctrl + e cmd + e ctrl + e reload the current page, then run scratchpad code ctrl + shift + r cmd + shift + r ctrl + shift + r save the pad ctrl + s cmd + s ctrl + s open an existing pad ctrl + o cmd + o ctrl + o create a new pad ctrl + n cmd + n ctrl + n close scratchpad ctrl + w cmd + w ctrl + w pretty print the code in scratchpad ctrl + p cmd + p ctrl ...
Measure a portion of the page - Firefox Developer Tools
when you hold the mouse button down and then drag, you'll start to draw a rectangle, with its x, y, and diagonal dimensions displayed.
DOM allocation example - Firefox Developer Tools
< toolbarcount; i++) { var toolbar = createtoolbar(); container.appendchild(toolbar); } } createtoolbars(); a simple pseudocode representation of how this code operates looks like this: createtoolbars() -> createtoolbar() // called 200 times, creates 1 div element each time -> createtoolbarbutton() // called 20 times per toolbar, creates 1 span element each time in total, then, it creates 200 htmldivelement objects, and 4000 htmlspanelement objects.
Memory - Firefox Developer Tools
it then provides a number of views of the heap that can show you which objects account for memory usage and exactly where in your code you are allocating memory.
Performance Analysis - Firefox Developer Tools
(alternatively, if you have only just opened the network monitor, so it's not yet populated with the list of requests, you'll get a stopwatch icon in the main window.) the network monitor then loads the site twice: once with an empty browser cache, and once with a primed browser cache.
Examine Event Listeners - Firefox Developer Tools
the inspector shows the word "event" next to elements in the html pane, that have event listeners bound to them: click the icon, then you'll see a popup listing all the event listeners bound to this element: each line contains: a right-pointing arrowhead; click to expand the row and show the listener function source code a curved arrow pointing to a stack; click it to show the code for the handler in the debugger the name of the event for which a handler was attached to this element the name and line number for the listener; you can also click here to expand the row and view the listener function source code a label indicating whether the event bubbles a label indicating the system that defines the event.
CSS Grid Inspector: Examine grid layouts - Firefox Developer Tools
when you select the checkbox for the subgrid, the lines for the parent grid are displayed also displayed; if the checkbox for the parent grid is unselected, then its lines are translucent.
Select an element - Firefox Developer Tools
click the element to select it: starting in firefox 52, if you shift + click the element, then it is selected but the picker stays active.
Sorting algorithms comparison - Firefox Developer Tools
its call graph looks like this: sortall() // (generate random array, then call sort) x 200 -> sort() // sort with each algorithm, log the result -> bubblesort() -> swap() -> selectionsort() -> swap() -> quicksort() -> partition() the implementations of the sorting algorithms in the program are taken from https://github.com/nzakas/computer-science-in-javascript/ and are used under th...
Performance - Firefox Developer Tools
the tool then shows you an overview of the things the browser was doing to render your site over the profile, and a graph of the frame rate over the profile.
Shader Editor - Firefox Developer Tools
javascript code running in the page then sends them for compilation using the webgl apis, and they're executed on the device's gpu when needed.
Cookies - Firefox Developer Tools
you can edit cookies by double-clicking inside cells in the table widget and editing the values they contain, and add new cookies by clicking the "plus" (+) button and then editing the resulting new row to the value you want.
Local Storage / Session Storage - Firefox Developer Tools
finally, you can add new storage items by clicking the "plus" (+) button and then editing the resulting new row to the value you want.
Storage Inspector - Firefox Developer Tools
under "cache storage", objects are organized by origin and then by the name of the cache: indexeddb objects are organized by origin, then by database name, then by object store name: with the cookies, local storage, and session storage types, there's only one level in the hierarchy, so stored items are listed directly under each origin: you can click on each item in the tree to expand or collapse its children.
Web Console Helpers - Firefox Developer Tools
for example, if you type "2+2 <enter>", then "$_ <enter>", the console will print 4.
Rich output - Firefox Developer Tools
then you can paste it into a document.
AbsoluteOrientationSensor - Web APIs
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(); ...
AbstractWorker - Web APIs
this code snippet demonstrates the creation of a new worker using the worker() constructor; it also shows how to then send a message to the worker.
AnalyserNode.fftSize - Web APIs
example the following example shows basic usage of an audiocontext to create an analysernode, then requestanimationframe and <canvas> to collect time domain data repeatedly and draw an "oscilloscope style" output of the current audio input.
AnalyserNode.frequencyBinCount - Web APIs
example the following example shows basic usage of an audiocontext to create an analysernode, then requestanimationframe and <canvas> to collect frequency data repeatedly and draw a "winamp bargraph style" output of the current audio input.
AnalyserNode.getByteFrequencyData() - Web APIs
example the following example shows basic usage of an audiocontext to create an analysernode, then requestanimationframe and <canvas> to collect frequency data repeatedly and draw a "winamp bargraph style" output of the current audio input.
AnalyserNode.getByteTimeDomainData() - Web APIs
return value void | none example the following example shows basic usage of an audiocontext to create an analysernode, then requestanimationframe and <canvas> to collect time domain data repeatedly and draw an "oscilloscope style" output of the current audio input.
AnalyserNode.getFloatTimeDomainData() - Web APIs
example the following example shows basic usage of an audiocontext to create an analysernode, then requestanimationframe and <canvas> to collect time domain data repeatedly and draw an "oscilloscope style" output of the current audio input.
AnalyserNode.maxDecibels - Web APIs
example the following example shows basic usage of an audiocontext to create an analysernode, then requestanimationframe and <canvas> to collect frequency data repeatedly and draw a "winamp bargraph style" output of the current audio input.
AnalyserNode.minDecibels - Web APIs
example the following example shows basic usage of an audiocontext to create an analysernode, then requestanimationframe and <canvas> to collect frequency data repeatedly and draw a "winamp bargraph style" output of the current audio input.
AnalyserNode.smoothingTimeConstant - Web APIs
example the following example shows basic usage of an audiocontext to create an analysernode, then requestanimationframe and <canvas> to collect frequency data repeatedly and draw a "winamp bargraph style" output of the current audio input.
AnalyserNode - Web APIs
basic usage the following example shows basic usage of an audiocontext to create an analysernode, then requestanimationframe and <canvas> to collect time domain data repeatedly and draw an "oscilloscope style" output of the current audio input.
Animation.finished - Web APIs
examples the following code waits until all animations running on the element elem have finished, then deletes the element from the dom tree: promise.all( elem.getanimations().map( function(animation) { return animation.finished } ) ).then( function() { return elem.remove(); } ); specifications specification status comment web animationsthe definition of 'animation.finished' in that specification.
Animation.updatePlaybackRate() - Web APIs
examples a speed selector component would benefit from smooth updating of updateplaybackrate(), as demonstrated below: speedselector.addeventlistener('input', evt => { cartoon.updateplaybackrate(parsefloat(evt.target.value)); cartoon.ready.then(() => { console.log(`playback rate set to ${cartoon.playbackrate}`); }); }); specifications specification status comment web animationsthe definition of 'updateplaybackrate()' in that specification.
Attr.namespaceURI - Web APIs
WebAPIAttrnamespaceURI
if the namespaceuri returns the xul namespace and the localname returns "browser", then the node is understood to be a xul <browser/>.
AudioBuffer.copyFromChannel() - Web APIs
example this example creates a new audio buffer, then copies the samples from another channel into it.
AudioBuffer.getChannelData() - Web APIs
example in the following example we create a two second buffer, fill it with white noise, and then play it via an audiobuffersourcenode.
AudioBuffer - Web APIs
once put into an audiobuffer, the audio can then be played by being passed into an audiobuffersourcenode.
AudioBufferSourceNode.start() - Web APIs
using this parameter is functionally identical to calling start(when, offset) and then calling stop(when+duration).
AudioBufferSourceNode - Web APIs
examples in this example, we create a two-second buffer, fill it with white noise, and then play it using an audiobuffersourcenode.
AudioConfiguration - Web APIs
} }; // check support and performance navigator.mediacapabilities.decodinginfo(mediaconfig).then(result => { console.log('this configuration is ' + (result.supported ?
AudioContext.createMediaStreamDestination() - Web APIs
after that, the stop event fires, a new blob is made of type opus — which contains the data in the chunks array, and a new window (tab) is then opened that points to a url created from the blob.
AudioContext.resume() - Web APIs
susresbtn.onclick = function() { if(audioctx.state === 'running') { audioctx.suspend().then(function() { susresbtn.textcontent = 'resume context'; }); } else if(audioctx.state === 'suspended') { audioctx.resume().then(function() { susresbtn.textcontent = 'suspend context'; }); } } specifications specification status comment web audio apithe definition of 'resume()' in that specification.
AudioNode.disconnect() - Web APIs
if this value is an audioparam, then the connection to that audioparam is terminated, and the node's contributions to that computed parameter become 0 going forward once the change takes effect.
AudioParam.setValueAtTime() - Web APIs
when the buttons are pressed, the currgain variable is incremented/decremented by 0.25, then the setvalueattime() method is used to set the gain value equal to currgain, one second from now (audioctx.currenttime + 1.) // create audio context var audiocontext = window.audiocontext || window.webkitaudiocontext; var audioctx = new audiocontext(); // set basic variables for example var myaudio = document.queryselector('audio'); var pre = document.queryselector('pre'); var myscript = docume...
AudioParamDescriptor - Web APIs
if the underlying audioworkletprocessor has a parameterdescriptors static getter, then the returned array of objects based on this dictionary is used internally by audioworkletnode constructor to populate its parameters property accordingly.
AudioScheduledSourceNode.stop() - Web APIs
if no time is specified, then the sound stops playing immediately.
AudioTrack.enabled - Web APIs
the element's audio tracks are then scanned through using the javascript foreach() method (although the audiotracks property of a media element isn't actually a javascript array, it can be accessed like one for the most part).
AudioTrack.language - Web APIs
this could then be used to build a user interface for selecting the language the user would like to listen to while watching a movie, for example.
AudioTrack - Web APIs
usage notes to get an audiotrack for a given media element, use the element's audiotracks property, which returns an audiotracklist object from which you can get the individual tracks contained in the media: var el = document.queryselector("video"); var tracks = el.audiotracks; you can then access the media's individual tracks using either array syntax or functions such as foreach().
AudioWorkletGlobalScope - Web APIs
the class can then be used by creating an audioworkletnode, providing its registered name.
AudioWorkletNode - Web APIs
you can then use their values in the associated audioworkletprocessor.
AudioWorkletProcessor - Web APIs
ters) { const output = outputs[0] output.foreach(channel => { for (let i = 0; i < channel.length; i++) { channel[i] = math.random() * 2 - 1 } }) return true } } registerprocessor('white-noise-processor', whitenoiseprocessor) next, in our main script file we'll load the processor, create an instance of audioworkletnode, passing it the name of the processor, then connect the node to an audio graph.
BaseAudioContext.createAnalyser() - Web APIs
example the following example shows basic usage of an audiocontext to create an analyser node, then use requestanimationframe() to collect time domain data repeatedly and draw an "oscilloscope style" output of the current audio input.
BaseAudioContext.createBufferSource() - Web APIs
example in this example, we create a two second buffer, fill it with white noise, and then play it via an audiobuffersourcenode.
BaseAudioContext.createDelay() - Web APIs
if you just press the play buttons, the loops will start immediately; if you slide the sliders up to the right, then press the play buttons, a delay will be introduced, so the looping sounds don't start playing for a short amount of time.
BaseAudioContext.createGain() - Web APIs
example the following example shows basic usage of an audiocontext to create a gainnode, which is then used to mute and unmute the audio when a mute button is clicked by changing the gain property value.
BaseAudioContext.createScriptProcessor() - Web APIs
if it's not passed in, or if the value is 0, then the implementation will choose the best buffer size for the given environment, which will be a constant power of 2 throughout the lifetime of the node.
BaseAudioContext.createStereoPanner() - Web APIs
we then use an oninput event handler to change the value of the stereopannernode.pan parameter and update the pan value display when the slider is moved.
BaseAudioContext.listener - Web APIs
the listener property of the baseaudiocontext interface returns an audiolistener object that can then be used for implementing 3d audio spatialization.
BaseAudioContext - Web APIs
baseaudiocontext.createbiquadfilter() creates a biquadfilternode, which represents a second order filter configurable as several different common filter types: high-pass, low-pass, band-pass, etc baseaudiocontext.createbuffer() creates a new, empty audiobuffer object, which can then be populated by data and played via an audiobuffersourcenode.
BasicCardRequest - Web APIs
request.show().then(function(instrumentresponse) { // do something with the response from the ui.
BasicCardResponse.billingAddress - Web APIs
request.show().then(function(instrumentresponse) { // do something with the response from the ui.
BasicCardResponse.cardNumber - Web APIs
request.show().then(function(instrumentresponse) { // do something with the response from the ui.
BasicCardResponse.cardSecurityCode - Web APIs
request.show().then(function(instrumentresponse) { // do something with the response from the ui.
BasicCardResponse.cardholderName - Web APIs
request.show().then(function(instrumentresponse) { // do something with the response from the ui.
BasicCardResponse.expiryMonth - Web APIs
request.show().then(function(instrumentresponse) { // do something with the response from the ui.
BasicCardResponse.expiryYear - Web APIs
request.show().then(function(instrumentresponse) { // do something with the response from the ui.
BasicCardResponse - Web APIs
request.show().then(function(instrumentresponse) { // do something with the response from the ui.
BatteryManager.charging - Web APIs
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
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
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
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
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 recommendation initial defi...
BatteryManager.onchargingtimechange - Web APIs
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 candidate recommendat...
BatteryManager.ondischargingtimechange - Web APIs
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 candidate reco...
BatteryManager.onlevelchange - Web APIs
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.dischargi...
Battery Status API - Web APIs
navigator.getbattery().then(function(battery) { function updateallbatteryinfo(){ updatechargeinfo(); updatelevelinfo(); updatecharginginfo(); updatedischarginginfo(); } updateallbatteryinfo(); battery.addeventlistener('chargingchange', function(){ updatechargeinfo(); }); function updatechargeinfo(){ console.log("battery charging?
Using the Beacon API - Web APIs
ge = function(event) { var msg = event.data; // log worker's send status console.log("worker reply: sendbeacon() status = " + msg); }; } this code snippet is for the worker (worker-using.js): onmessage = function(event) { var msg = event.data; // split the url and data from the message var url = msg[0]; var data = msg[1]; // if the browser supports worker sendbeacon(), then send the beacon; otherwise // return failure message to the global context if (self.navigator.sendbeacon) { var status = self.navigator.sendbeacon(url, data); postmessage(status ?
BeforeInstallPromptEvent - Web APIs
example window.addeventlistener("beforeinstallprompt", function(e) { // log the platforms provided as options in an install prompt console.log(e.platforms); // e.g., ["web", "android", "windows"] e.userchoice.then(function(choiceresult) { console.log(choiceresult.outcome); // either "accepted" or "dismissed" }, handleerror); }); ...
BiquadFilterNode.getFrequencyResponse() - Web APIs
we create a <ul> element in our html to contain our results, and grab a reference to it in our javascript: <p>biquad filter frequency response for: </p> <ul class="freq-response-output"> </ul> var freqresponseoutput = document.queryselector('.freq-response-output'); finally, after creating our biquad filter, we use getfrequencyresponse() to generate the response data and put it in our arrays, then loop through each data set and output them in a human-readable list at the bottom of the page: var biquadfilter = audioctx.createbiquadfilter(); biquadfilter.type = "lowshelf"; biquadfilter.frequency.value = 1000; biquadfilter.gain.value = range.value; ...
Blob.arrayBuffer() - Web APIs
WebAPIBlobarrayBuffer
syntax var bufferpromise = blob.arraybuffer(); blob.arraybuffer().then(buffer => /* process the arraybuffer */); var buffer = await blob.arraybuffer(); parameters none.
Blob.size - Web APIs
WebAPIBlobsize
example this example uses an <input> element of type file to ask the user for a group of files, then iterates over those files outputting their names and lengths in bytes.
Blob.text() - Web APIs
WebAPIBlobtext
syntax var textpromise = blob.text(); blob.text().then(text => /* do something with the text */); var text = await blob.text(); parameters none.
Blob.type - Web APIs
WebAPIBlobtype
example this example asks the user to select a number of files, then checks each file to make sure it's one of a given set of image file types.
Bluetooth.getAvailability() - Web APIs
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!
BluetoothCharacteristicProperties.writeWithoutResponse - Web APIs
specifications specification status comment web bluetooththe definition of 'authenticatedsignedwrites' in that specification.
connectGATT() - Web APIs
syntax instanceofbluetoothdevice.connectgatt().then(function(bluetoothgattremoteserver) { ...
BluetoothRemoteGATTCharacteristic.getDescriptor() - Web APIs
syntax bluetoothremotegattcharacteristic.getdescriptor(bluetoothdescriptoruuid).then(function(bluetoothgattdescriptor) { ...
BluetoothRemoteGATTCharacteristic.getDescriptors() - Web APIs
syntax bluetoothremotegattcharacteristic.getdescriptors(bluetoothdescriptoruuid).then(function(bluetoothgattdescriptors[]) { ...
BluetoothRemoteGATTCharacteristic.readValue() - Web APIs
syntax bluetoothremotegattcharacteristic.readvalue().then(function(dataview) { ...
BluetoothRemoteGATTCharacteristic.startNotifications() - Web APIs
syntax bluetoothremotegattcharacteristic.startnotifications().then(function(bluetoothremotegattcharacteristic) { ...
BluetoothRemoteGATTCharacteristic.stopNotifications() - Web APIs
syntax bluetoothremotegattcharacteristic.stopnotifications().then(function(bluetoothremotegattcharacteristic) { ...
BluetoothRemoteGATTCharacteristic.writeValue() - Web APIs
syntax bluetoothremotegattcharacteristic.writevalue(value).then(function() { ...
readValue() - Web APIs
syntax bluetoothremotegattdescriptor.readvalue().then(function(value[]) { ...
writeValue() - Web APIs
syntax bluetoothremotegattdescriptor.writevalue(array[]).then(function() { ...
BluetoothRemoteGATTServer.connect() - Web APIs
syntax bluetoothremotegattserver.connect() .then(function(bluetoothremotegattserver) { ...
BluetoothRemoteGATTServer.getPrimaryService() - Web APIs
syntax bluetoothremotegattserver.getprimaryservice(bluetoothserviceuuid).then(function(bluetoothgattservice) { ...
BluetoothRemoteGATTServer.getPrimaryServices() - Web APIs
syntax bluetoothremotegattserver.getprimaryservices(bluetoothserviceuuid).then(function(bluetoothgattservices) { ...
getCharacteristic() - Web APIs
syntax bluetoothgattserviceinstance.getcharacteristic(characteristic).then(function(bluetoothgattcharacteristic) { ...
getCharacteristics() - Web APIs
syntax bluetoothgattserviceinstance.getcharacteristics(characteristics).then(function(bluetoothgattcharacteristic[]) { ...
getIncludedService() - Web APIs
syntax bluetoothgattserviceinstance.getincludedservice(service).then(function(bluetoothgattservice) { ...
getIncludedServices() - Web APIs
syntax bluetoothgattserviceinstance.getincludedservice(service).then(function(bluetoothgattservice) { ...
Body - Web APIs
WebAPIBody
html content <img class="my-image" src="https://udn.realityripple.com/samples/46/29059a2b39.png"> js content const myimage = document.queryselector('.my-image'); fetch('https://upload.wikimedia.org/wikipedia/commons/7/77/delete_key1.jpg') .then(res => res.blob()) .then(res => { const objecturl = url.createobjecturl(res); myimage.src = objecturl; }); specifications specification status comment fetchthe definition of 'body' in that specification.
BudgetService.getBudget() - Web APIs
syntax var apromise = budgetservice.getbudget(); apromise.then(function(budgetstate[]){ ...
BudgetService.getCost() - Web APIs
syntax var apromise = budgetservice.getcost(operation); apromise.then(function(somedouble){ ...
BudgetService.reserve() - Web APIs
syntax var apromise = budgetservice.reserve(operation); apromise.then(function(boolean){ ...
CSSImageValue - Web APIs
we then get() the background-image from the stylemap and stringify it: // get the element const button = document.queryselector( 'button' ); // retrieve all computed styles with computedstylemap() const allcomputedstyles = button.computedstylemap(); // return the cssimagevalue example console.log( allcomputedstyles.get('background-image') ); console.log( allcomputedstyles.get('background-image').tostr...
CSSMathSum - Web APIs
examples we create an element with a width determined using a calc() function, then console.log() the operator and values, and dig into the values a bit.
CSSMathValue.operator - Web APIs
interface value cssmathsum "sum" cssmathproduct "product" cssmathmin "min" cssmathmax "max" cssmathclamp "clamp" cssmathnegate "negate" cssmathinvert "invert" examples we create an element with a width determined using a calc() function, then console.log() the operator.
CSSMathValue - Web APIs
examples we create an element with a width determined using a calc() function, then console.log() the operator.
CSSPositionValue - Web APIs
let replacedel = document.getelementbyid( 'image' ); let position = new csspositionvalue( css.px(35), css.px(40) ); replacedel.attributestylemap.set( 'object-position', position ); console.log( position.x.value, position.y.value ); console.log( replacedel.computedstylemap().get('object-position') ); we set the object-position property, then check the values returned.
CSSStyleSheet.addRule() - Web APIs
usage notes this method is implemented by browsers by constructing a string using the template literal `${selector}{${styleblock}}`, then passing it into the standard insertrule() method.
CSSStyleSheet.cssRules - Web APIs
examples individual rules within the stylesheet can then be accessed by index: let rulelist = document.stylesheets[0].cssrules; for (let i=0; i < rulelist.length; i++) { processrule(rulelist[i]); } rules can also be accessed using for...of: let rulelist = document.stylesheets[0].cssrules; for (let rule of rulelist) { processrule(rule); } however, because cssrule is not a proper array, you can't use foreach().
CSSStyleSheet.insertRule() - Web APIs
/*else*/ return originalinsertrule.call( this, // the sheet to be changed selectorandrule.substring(0, openbracketpos), // the selector selectorandrule.substring(closebracketpos), // the rule arguments[3] // the insert index ); } // works by if the char code is a backslash, then isescaped // gets flipped (xor-ed by 1), and if it is not a backslash // then isescaped gets xored by itself, zeroing it isescaped ^= newcharcode===92?1:isescaped; // 92 = "\\".charcodeat(0) } // else, there is no unescaped bracket return originalinsertrule.call(this, selectorandrule, "", arguments[2]); }; } })(cssstylesheet.prototype); specificat...
CSSUnitValue.unit - Web APIs
WebAPICSSUnitValueunit
examples the following creates a csspositionvalue from individual cssunitvalue constructors, then queries the cssunitvalue.unit.
CSSUnitValue.value - Web APIs
examples the following creates a csspositionvalue from individual cssunitvalue constructors, then queries the cssunitvalue.value.
CSSUnparsedValue.length - Web APIs
examples in this example we employ the cssunparsedvalue.cssunparsedvalue() constructor, then query the length: let values = new cssunparsedvalue( ['1em', '#445566', '-45px'] ); console.log( values.length ) // 3 specifications specification status comment css typed om level 1the definition of 'length' in that specification.
Using dynamic styling information - Web APIs
using the setattribute method note that you can also change style of an element by getting a reference to it and then use its setattribute method to specify the css property and its value.
CSS Typed Object Model API - Web APIs
it is also generally faster, as values can be directly manipulated and then cheaply translated back into underlying values without having to both build and parse strings of css.
CanvasGradient.addColorStop() - Web APIs
the gradient is then used to fill a rectangle.
CanvasRenderingContext2D.clearRect() - Web APIs
the clearrect() method then erases part of the canvas.
CanvasRenderingContext2D.createLinearGradient() - Web APIs
three color stops between the gradient's start and end points are then created.
CanvasRenderingContext2D.createPattern() - Web APIs
we then apply it to the fill style of our primary canvas, and fill that canvas with the pattern.
CanvasRenderingContext2D.createRadialGradient() - Web APIs
three color stops between the gradient's two circles are then created.
CanvasRenderingContext2D.currentTransform - Web APIs
a rectangle is then drawn using that transformation.
CanvasRenderingContext2D.fill() - Web APIs
the fill() method is then used to render the object to the canvas.
CanvasRenderingContext2D.fillRect() - Web APIs
this is often useful for creating a background, on top of which other things may then be drawn.
CanvasRenderingContext2D.font - Web APIs
let f = new fontface('test', 'url(x)'); f.load().then(function() { // ready to use the font in a canvas context }); specifications specification status comment html living standardthe definition of 'canvasrenderingcontext2d.font' in that specification.
CanvasRenderingContext2D.getImageData() - Web APIs
example getting image data from a canvas this example draws a rectangle, and then uses getimagedata() to grab a portion of the canvas.
CanvasRenderingContext2D.moveTo() - Web APIs
both sub-paths are then rendered with a single stroke() call.
CanvasRenderingContext2D.rect() - Web APIs
the path is then rendered using the fill() method.
CanvasRenderingContext2D.resetTransform() - Web APIs
syntax void ctx.resettransform(); examples resetting the matrix this example draws a rotated rectangle after modifying the matrix, and then resets the matrix using the resettransform() method.
CanvasRenderingContext2D.scale() - Web APIs
a non-scaled rectangle is then drawn for comparison.
CanvasRenderingContext2D.stroke() - Web APIs
examples a simple stroked rectangle this example creates a rectangle using the rect() method, and then draws it to the canvas using stroke().
CanvasRenderingContext2D.textAlign - Web APIs
for example, if textalign is "center", then the text's left edge will be at x - (textwidth / 2).
CanvasRenderingContext2D.transform() - Web APIs
note: see also the settransform() method, which resets the current transform to the identity matrix and then invokes transform().
CanvasRenderingContext2D.translate() - Web APIs
an unmoved square of the same size is then drawn for comparison.
CanvasRenderingContext2D - Web APIs
canvasrenderingcontext2d.settransform() resets the current transform to the identity matrix, and then invokes the transform() method with the same arguments.
Compositing example - Web APIs
dark parts on the base layer become darker, and light parts become lighter.', 'retains the darkest pixels of both layers.', 'retains the lightest pixels of both layers.', 'divides the bottom layer by the inverted top layer.', 'divides the inverted bottom layer by the top layer, and then inverts the result.', 'a combination of multiply and screen like overlay, but with top and bottom layer swapped.', 'a softer version of hard-light.
Compositing and clipping - Web APIs
0); for (var i = 0; i < 9; i++) { ctx.rotate(math.pi / 5); if (i % 2 === 0) { ctx.lineto((r / 0.525731) * 0.200811, 0); } else { ctx.lineto(r, 0); } } ctx.closepath(); ctx.fill(); ctx.restore(); } <canvas id="canvas" width="150" height="150"></canvas> draw(); in the first few lines of code, we draw a black rectangle the size of the canvas as a backdrop, then translate the origin to the center.
Optimizing canvas - Web APIs
you can then render the offscreen image to your primary canvas as often as needed, without unnecessarily repeating the steps needed to generate it in the first place.
Using channel messaging - Web APIs
when our button is clicked, we prevent the form from submitting as normal and then send the value entered in our text input to the iframe via the messagechannel.
Channel Messaging API - Web APIs
you could then respond by sending a message back to the original document using messageport.postmessage.
Client.url - Web APIs
WebAPIClienturl
example self.addeventlistener('notificationclick', function(event) { console.log('on notification click: ', event.notification.tag); event.notification.close(); // this looks to see if the current is already open and // focuses if it is event.waituntil(clients.matchall({ type: 'window' }).then(function(clientlist) { for (var i = 0; i < clientlist.length; i++) { var client = clientlist[i]; if (client.url == '/' && 'focus' in client) return client.focus(); } if (clients.openwindow) return clients.openwindow('/'); })); }); specifications specification status comment service workersthe definition of 'url' in that specificati...
Clipboard.readText() - Web APIs
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
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.getType() - Web APIs
then utilizing the clipboarditem.types property to set the gettype() argument and return the corresponding blob object.
ClipboardItem.types - Web APIs
then checking the types property for available types before utilizing the clipboarditem.gettype() method to return the blob object.
ClipboardItem - Web APIs
then utilizing the clipboarditem.types property to set the gettype() argument and return the corresponding blob object.
Clipboard API - Web APIs
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.
Console.profile() - Web APIs
WebAPIConsoleprofile
you can optionally supply an argument to name the profile and this then enables you to stop only that profile if multiple profiles being recorded.
Console.profileEnd() - Web APIs
if console.profileend() is passed a profile name, and it matches the name of a profile being recorded, then that profile is stopped.
Console.timeStamp() - Web APIs
WebAPIConsoletimeStamp
you can optionally supply an argument to label the timestamp, and this label will then be shown alongside the marker.
ConstantSourceNode() - Web APIs
example in this example, an audio context is created, then a constantsourcenode is established with its offset initialized to 0.5.
ConstantSourceNode - Web APIs
then the constantsourcenode is created by calling audiocontext.createconstantsource(), and the gain parameters of each of the two gain nodes are connected to the constantsourcenode.
Constraint validation API - Web APIs
reportvalidity() htmlformelement method checks the element's value against its constraints and also reports the validity status; if the value is invalid, it fires an invalid event at the element, returns false, and then reports the validity status to the user in whatever way the user agent has available.
ContentIndex.add() - Web APIs
WebAPIContentIndexadd
syntax contentindex.add(contentdescription).then(...); parameters contentdescription the item registered is an object containing the following data: id: a unique string identifier.
ContentIndex.delete() - Web APIs
syntax contentindex.delete(id).then(...); parameters this method receives no parameters.
ContentIndex - Web APIs
examples feature detection and interface access here we get a reference to the serviceworkerregistration, then check for the index property, which gives us access to the content index interface.
ContentIndexEvent.id - Web APIs
self.addeventlistener('contentdelete', (event) => { console.log(event.id); // logs content index id, which can then be used to determine what content to delete from your cache }); specifications specification status comment unknownthe definition of 'id' in that specification.
ContentIndexEvent - Web APIs
self.addeventlistener('contentdelete', (event) => { console.log(event.id); // logs content index id, which can then be used to determine what content to delete from your cache }); specifications specification status comment unknownthe definition of 'contentindexevent' in that specification.
ConvolverNode.buffer - Web APIs
that audio recording could then be used as the buffer.
ConvolverNode.normalize - Web APIs
if normalize is set to false, then the convolution will be rendered with no pre-processing/scaling of the impulse response.
CredentialsContainer.create() - Web APIs
web authentication: an api for accessing public key credentials level 1 recommendation initial definition.
CredentialsContainer.preventSilentAccess() - Web APIs
the preventsilentaccess() method of the credentialscontainer interface sets a flag that specifies whether automatic log in is allowed for future visits to the current origin, then returns an empty promise.
CredentialsContainer.store() - Web APIs
syntax credentialscontainer.store(credential).then(function(credential) { ...
Crypto.subtle - Web APIs
WebAPICryptosubtle
the crypto.subtle read-only property returns a subtlecrypto which can then be used to perform low-level cryptographic operations.
CustomElementRegistry.whenDefined() - Web APIs
const undefinedelements = container.queryselectorall(':not(:defined)'); const promises = [...undefinedelements].map( button => customelements.whendefined(button.localname) ); // wait for all the children to be upgraded, // then remove the placeholder.
CustomEvent - Web APIs
this interface inherits methods from its parent, event: event.createevent() creates a new event, which must then be initialized by calling its initevent() method.
DOMHighResTimeStamp - Web APIs
if neither of the above determines the time origin, then the time origin is the time at which the navigation responsible for creating the window's current document took place.
DOMImplementation.createHTMLDocument() - Web APIs
lines 5 and 6 create a new paragraph element with some simple content, and then lines 8–12 handle inserting the new paragraph into the new document.
DOMMatrixReadOnly.flipX() - Web APIs
<svg width="100" height="100" viewbox="-50 0 100 100"> <path fill="red" d="m 0 50 l 50 0 l 50 100 z" /> <path id="flipped" fill="blue" d="m 0 50 l 50 0 l 50 100 z" /> </svg> this javascript first creates an identity matrix, then uses the `flipx()` method to create a new matrix, which is then applied to the blue triangle, inverting it across the x-axis.
DOMMatrixReadOnly.translate() - Web APIs
examples this svg contains two squares, one red and one blue, each positioned at the document origin: <svg width="250" height="250" viewbox="0 0 50 50"> <rect width="25" height="25" fill="red" /> <rect id="transformed" width="25" height="25" fill="blue" /> </svg> the following javascript first creates an identity matrix, then uses the translate() method to create a new, translated matrix — which is then applied to the blue square as a transform.
DOMPoint.DOMPoint() - Web APIs
WebAPIDOMPointDOMPoint
examples this example creates a dompoint representing the top-left corner of the current window, then creates a second point based on the first, which is then offset by 100 pixels both vertically and horizontally.
DOMPoint - Web APIs
WebAPIDOMPoint
in the following snippet, the pose of the xr device (such as a vr headset or phone with ar capabilities) can be retrieved by calling using xrframe.getviewerpose() during an xrsession animation frame, then accessing the resulting xrpose's transform property, which contains two dompointreadonly attributes: position as a vector and orientation as a quaternion.
DOMPointReadOnly.fromPoint() - Web APIs
that point is then used as the input for frompoint() to create a new point, newpoint.
DOMPointReadOnly.toJSON() - Web APIs
example this example creates a dompoint object representing the top-left corner of the current window, in screen coordinates, then converts that to json.
DOMRect.DOMRect() - Web APIs
WebAPIDOMRectDOMRect
examples to create a new domrect, you could run a line of code like so: mydomrect = new domrect(0,0,100,100); // running 'mydomrect' in the console would then return // domrect { x: 0, y: 0, width: 100, height: 100, top: 0, right: 100, bottom: 100, left: 0 } specifications specification status comment geometry interfaces module level 1the definition of 'domrect()' in that specification.
DOMRectReadOnly() - Web APIs
examples to create a new dompoint, you could run a line of code like so: const mydomrect = new domrectreadonly(0, 0, 100, 100) // running 'mydomrect' in the console would then return // domrect { x: 0, y: 0, width: 100, height: 100, top: 0, right: 100, bottom: 100, left: 0 } specifications specification status comment geometry interfaces module level 1the definition of 'domrectreadonly()' in that specification.
DOMTokenList.add() - Web APIs
WebAPIDOMTokenListadd
we then add a new token to the list, and write the list into the <span>'s node.textcontent.
DOMTokenList.contains() - Web APIs
we then test for the existence of "c" in the list, and write the result into the <span>'s node.textcontent.
DOMTokenList.entries() - Web APIs
we when retrieve an iterator containing the key/value pairs using entries(), then iterate through each one using a for...of loop, writing them to the <span>'s node.textcontent.
DOMTokenList.item() - Web APIs
WebAPIDOMTokenListitem
we then retrieve the last item in the list using item(tokenlist.length - 1), and write it into the <span>'s node.textcontent.
DOMTokenList.keys() - Web APIs
WebAPIDOMTokenListkeys
we when retrieve an iterator containing the keys using values(), then iterate through those keys using a for ...
DOMTokenList.length - Web APIs
examples in the following example we retrieve the list of classes set on a <span> element as a domtokenlist using element.classlist, then write the length of the list to the <span>'s node.textcontent.
DOMTokenList.remove() - Web APIs
we then remove a token from the list, and write the list into the <span>'s node.textcontent.
DOMTokenList.replace() - Web APIs
we then replace a token in the list, and write the list into the <span>'s node.textcontent.
DOMTokenList.value - Web APIs
syntax tokenlist.value; value a domstring examples in the following example we retrieve the list of classes set on a <span> element as a domtokenlist using element.classlist, then write the value of the list to the <span>'s node.textcontent.
DOMTokenList.values() - Web APIs
we when retrieve an iterator containing the values using values(), then iterate through those values using a for ...
DOMTokenList - Web APIs
examples in the following simple example, we retrieve the list of classes set on a <p> element as a domtokenlist using element.classlist, add a class using domtokenlist.add(), and then update the node.textcontent of the <p> to equal the domtokenlist.
DataTransfer.clearData() - Web APIs
html <span class="tweaked" id="source" draggable="true"> select this element, drag it to the drop zone and then release the selection to move the element.
DataTransfer.effectAllowed - Web APIs
lowed = " + ev.datatransfer.effectallowed); ev.preventdefault(); // set the dropeffect to move ev.datatransfer.dropeffect = "move" } </script> <body> <h1>examples <code>datatransfer</code>.{<code>dropeffect</code>, <code>effectallowed</code>} properties</h1> <div> <p id="source" ondragstart="dragstart_handler(event);" draggable="true"> select this element, drag it to the drop zone and then release the selection to move the element.</p> </div> <div id="target" ondrop="drop_handler(event);" ondragover="dragover_handler(event);">drop zone</div> </body> </html> specifications specification status comment html living standardthe definition of 'effectallowed' in that specification.
DataTransfer.setData() - Web APIs
child(document.getelementbyid(data)); // clear the drag data cache (for all formats/types) ev.datatransfer.cleardata(); } </script> <body> <h1>examples of <code>datatransfer</code>: <code>setdata()</code>, <code>getdata()</code>, <code>cleardata()</code></h1> <div> <p id="source" ondragstart="dragstart_handler(event);" draggable="true"> select this element, drag it to the drop zone and then release the selection to move the element.</p> </div> <div id="target" ondrop="drop_handler(event);" ondragover="dragover_handler(event);">drop zone</div> </body> </html> specifications specification status comment html living standardthe definition of 'setdata()' in that specification.
DataTransfer.types - Web APIs
if any files are included in the drag operation, then one of the types will be the string files.
DataTransferItemList.DataTransferItem() - Web APIs
the dropeffect to move ev.datatransfer.dropeffect = "move" } function dragend_handler(ev) { console.log("dragend"); var datalist = ev.datatransfer.items; // clear any remaining drag data datalist.clear(); } html <div> <p id="source" ondragstart="dragstart_handler(event);" ondragend="dragend_handler(event);" draggable="true"> select this element, drag it to the drop zone and then release the selection to move the element.</p> </div> <div id="target" ondrop="drop_handler(event);" ondragover="dragover_handler(event);">drop zone</div> css div { margin: 0em; padding: 2em; } #source { color: blue; border: 1px solid black; } #target { border: 1px solid black; } result drag and drop demo link specifications specification status comment ...
DataTransferItemList.add() - Web APIs
html <div> <p id="source" ondragstart="dragstart_handler(event);" ondragend="dragend_handler(event);" draggable="true"> select this element, drag it to the drop zone and then release the selection to move the element.</p> </div> <div id="target" ondrop="drop_handler(event);" ondragover="dragover_handler(event);">drop zone</div> css div { margin: 0em; padding: 2em; } #source { color: blue; border: 1px solid black; } #target { border: 1px solid black; } javascript function dragstart_handler(ev) { console.log("dragstart"); // add this element's id to th...
DataTransferItemList.clear() - Web APIs
html <div> <p id="source" ondragstart="dragstart_handler(event);" ondragend="dragend_handler(event);" draggable="true"> select this element, drag it to the drop zone and then release the selection to move the element.</p> </div> <div id="target" ondrop="drop_handler(event);" ondragover="dragover_handler(event);">drop zone</div> css div { margin: 0em; padding: 2em; } #source { color: blue; border: 1px solid black; } #target { border: 1px solid black; } javascript function dragstart_handler(ev) { console.log("dragstart"); // add...
DataTransferItemList.length - Web APIs
the dropeffect to move ev.datatransfer.dropeffect = "move" } function dragend_handler(ev) { console.log("dragend"); var datalist = ev.datatransfer.items; // clear any remaining drag data datalist.clear(); } html <div> <p id="source" ondragstart="dragstart_handler(event);" ondragend="dragend_handler(event);" draggable="true"> select this element, drag it to the drop zone and then release the selection to move the element.</p> </div> <div id="target" ondrop="drop_handler(event);" ondragover="dragover_handler(event);">drop zone</div> css div { margin: 0em; padding: 2em; } #source { color: blue; border: 1px solid black; } #target { border: 1px solid black; } result drag and drop demo link specifications specification status comment ...
DataTransferItemList.remove() - Web APIs
tems; for (var i = 0; i < datalist.length; i++) { datalist.remove(i); } // clear any remaining drag data datalist.clear(); } html <h1>example uses of <code>datatransferitemlist</code> methods and property</h1> <div> <p id="source" ondragstart="dragstart_handler(event);" ondragend="dragend_handler(event);" draggable="true"> select this element, drag it to the drop zone and then release the selection to move the element.</p> </div> <div id="target" ondrop="drop_handler(event);" ondragover="dragover_handler(event);">drop zone</div> css div { margin: 0em; padding: 2em; } #source { color: blue; border: 1px solid black; } #target { border: 1px solid black; } specifications specification status comment html li...
DedicatedWorkerGlobalScope.postMessage() - Web APIs
inside the handler a calculation is done from which a result message is created; this is then sent back to the main thread using postmessage(workerresult); onmessage = function(e) { console.log('message received from main script'); var workerresult = 'result: ' + (e.data[0] * e.data[1]); console.log('posting message back to main script'); postmessage(workerresult); } in the main script, onmessage would have to be called on a worker object, whereas inside the worker script you ju...
DelayNode.delayTime - Web APIs
if you just press the play buttons, the loops will start immediately; if you slide the sliders up to the right, then press the play buttons, a delay will be introduced, so the looping sounds don't start playing for a short amount of time.
DelayNode - Web APIs
WebAPIDelayNode
if you just press the play buttons, the loops will start immediately; if you slide the sliders up to the right, then press the play buttons, a delay will be introduced, so the looping sounds don't start playing for a short amount of time.
Using light sensors - Web APIs
the code alerts the user that they are working in a dark environment and then changes the page's background to a darker color.
DeviceOrientationEvent.DeviceOrientationEvent() - Web APIs
if the later, then options.absolute should be true.
Document.adoptNode() - Web APIs
the node can then be inserted into the current document.
Document.applets - Web APIs
WebAPIDocumentapplets
since then, calling document.applets in those browsers always returns an empty htmlcollection.
Document.createCDATASection() - Web APIs
example var docu = new domparser().parsefromstring('<xml></xml>', 'application/xml') var cdata = docu.createcdatasection('some <cdata> data & then some'); docu.getelementsbytagname('xml')[0].appendchild(cdata); alert(new xmlserializer().serializetostring(docu)); // displays: <xml><![cdata[some <cdata> data & then some]]></xml> notes this will only work with xml, not html documents (as html documents do not support cdata sections); attempting it on an html document will throw not_supported_err.
Document.createElementNS() - Web APIs
ments||" onload="init()"> <script type="application/javascript"><![cdata[ let container; let newdiv; let txtnode; function init(){ container = document.getelementbyid("containerbox"); newdiv = document.createelementns("http://www.w3.org/1999/xhtml", "div"); txtnode = document.createtextnode("this is text that was constructed dynamically with createelementns and createtextnode then inserted into the document using appendchild."); newdiv.appendchild(txtnode); container.appendchild(newdiv); } ]]></script> <vbox id="containerbox" flex="1"> <html:div> the script on this page will add dynamic content below: </html:div> </vbox> </page> the example given above uses inline script which is not recommended in xhtml documents.
Document.createEvent() - Web APIs
the returned object should be first initialized and can then be passed to eventtarget.dispatchevent.
Document.createExpression() - Web APIs
this method compiles an xpathexpression which can then be used for (repeated) evaluations.
Document.createTouchList() - Web APIs
in following code snippet, some touch objects are created for the target element and those touch points are then used to create some touchlist objects.
Document.createTreeWalker() - Web APIs
example the following example goes through all nodes in the body, reduces the set of nodes to elements, simply passes through as acceptable each node (it could reduce the set in the acceptnode() method instead), and then makes use of tree walker iterator that is created to advance through the nodes (now all elements) and push them into an array.
Document.execCommand() - Web APIs
clearauthenticationcache clears all authentication credentials from the cache.
Document.exitFullscreen() - Web APIs
document.onclick = function (event) { if (document.fullscreenelement) { document.exitfullscreen() .then(() => console.log("document exited form full screen mode")) .catch((err) => console.error(err)) } else { document.documentelement.requestfullscreen(); } } note: for a more complete example, see the example in element.requestfullscreen().
Document.fonts - Web APIs
WebAPIDocumentfonts
examples doing operation after all fonts are loaded document.fonts.ready.then(function() { // any operation that needs to be done only after all the fonts // have finished loading can go here.
Document: gotpointercapture event - Web APIs
it then calls setpointercapture() on the element on a pointerdown event, which will trigger gotpointercapture.
Document.hasStorageAccess() - Web APIs
examples document.hasstorageaccess().then(hasaccess => { if (hasaccess) { // storage access has been granted already.
Document: keydown event - Web APIs
by clicking in it), then try pressing some keys.</p> <p id="log"></p> document.addeventlistener('keydown', logkey); function logkey(e) { log.textcontent += ` ${e.code}`; } onkeydown equivalent document.onkeydown = logkey; specifications specification status ui events working draft ...
Document: keypress event - Web APIs
<p>press inside this iframe first to focus it, then try pressing keys on the keyboard.</p> <p id="log"></p> const log = document.getelementbyid('log'); document.addeventlistener('keypress', logkey); function logkey(e) { log.textcontent += ` ${e.code}`; } onkeypress equivalent document.onkeypress = logkey; specifications specification status ui events working draft ...
Document: keyup event - Web APIs
by clicking in it), then try pressing some keys.</p> <p id="log"></p> const log = document.getelementbyid('log'); document.addeventlistener('keyup', logkey); function logkey(e) { log.textcontent += ` ${e.code}`; } onkeyup equivalent document.onkeyup = logkey; specifications specification status ui events working draft ...
Document.mozSetImageElement() - Web APIs
it creates a new <canvas> with the width and height set to 100 pixels, then draws into it a 50 by 50 pixel square.
Document: pointercancel event - Web APIs
the pointercancel event is fired when the browser determines that there are unlikely to be any more pointer events, or if after the pointerdown event is fired, the pointer is then used to manipulate the viewport by panning, zooming, or scrolling.
Document.querySelectorAll() - Web APIs
if the array is empty (that is, its length property is 0), then no matches were found.
Document.rootElement - Web APIs
syntax const element = document.rootelement notes if the document is a non-empty svg document, then the rootelement will be an svgsvgelement, identical to the documentelement.
Document.selectedStyleSheetSet - Web APIs
setting the value of this property is equivalent to calling document.enablestylesheetsforset() with the value of currentstylesheetset, then setting the value of laststylesheetset to that value as well.
Document: transitionend event - Web APIs
in the case where a transition is removed before completion, such as if the transition-property is removed or display is set to none, then the event will not be generated.
Document.write() - Web APIs
WebAPIDocumentwrite
if the document.write() call is embedded within an inline html <script> tag, then it will not call document.open().
Document.xmlVersion - Web APIs
to detect this, you can create an element with its name in lower case, then check to see if it gets converted into all upper case (in which case the document is in the non-xml html mode): if (document.createelement("foo").tagname == "foo") { /* document is not xml */ } specifications http://www.w3.org/tr/dom-level-3-cor...ument3-version this has been removed from dom core level 4wd ...
Document - Web APIs
WebAPIDocument
the document interface is extended with the xpathevaluator interface: document.createexpression() compiles an xpathexpression which can then be used for (repeated) evaluations.
DocumentFragment - Web APIs
usage notes a common use for documentfragment is to create one, assemble a dom subtree within it, then append or insert the fragment into the dom using node interface methods such as appendchild() or insertbefore().
Introduction to the DOM - Web APIs
this function creates a new h1 element, adds text to that element, and then adds the h1 to the tree for this document: <html> <head> <script> // run this function when the document is loaded window.onload = function() { // create a couple of elements in an otherwise empty html page const heading = document.createelement("h1"); const heading_text = document.createtextnode("big head!"); heading.appendchild(heading_t...
Using the W3C DOM Level 1 Core - Web APIs
mple, the following document <html> <head> <title>my document</title> </head> <body> <h1>header</h1> <p>paragraph</p> </body> </html> has a dom tree that looks like this: (note that, although the above tree is similar to the above document's dom tree, it's not identical, as the actual dom tree preserves whitespace.) when a web browser parses an html document, it builds a dom tree and then uses it to display the document.
DragEvent - Web APIs
WebAPIDragEvent
the user initiates a drag by placing a pointer device (such as a mouse) on the touch surface and then dragging the pointer to a new location (such as another dom element).
EffectTiming.iterations - Web APIs
defaults to 1, meaning the animation sequence plays through once then stops automatically.
Element.animate() - Web APIs
WebAPIElementanimate
the element interface's animate() method is a shortcut method which creates a new animation, applies it to the element, then plays the animation.
Element.attachShadow() - Web APIs
you can see that we use attachshadow() in the middle of the code to create a shadow root, which we then attach our custom element's contents to.
Element.classList - Web APIs
WebAPIElementclassList
this can then be used to manipulate the class list.
Element.clientLeft - Web APIs
when layout.scrollbar.side preference is set to 1 or to 3 and when the text-direction is set to rtl, then the vertical scrollbar is positioned on the left and this impacts the way clientleft is computed.
Element.clientTop - Web APIs
WebAPIElementclientTop
(actually might be math.round(parsefloat()).) for example, if the computed "border-top-width" is zero, then clienttop is also zero.
Element.closest() - Web APIs
WebAPIElementclosest
atchesselector || element.prototype.webkitmatchesselector; } if (!element.prototype.closest) { element.prototype.closest = function(s) { var el = this; do { if (element.prototype.matches.call(el, s)) return el; el = el.parentelement || el.parentnode; } while (el !== null && el.nodetype === 1); return null; }; } however, if you really do require ie 8 support, then the following polyfill will do the job very slowly, but eventually.
Element: compositionend event - Web APIs
yes interface compositionevent event handler property none examples const inputelement = document.queryselector('input[type="text"]'); inputelement.addeventlistener('compositionend', (event) => { console.log(`generated characters were: ${event.data}`); }); live example html <div class="control"> <label for="name">on macos, click in the textbox below,<br> then type <kbd>option</kbd> + <kbd>`</kbd>, then <kbd>a</kbd>:</label> <input type="text" id="example" name="example"> </div> <div class="event-log"> <label>event log:</label> <textarea readonly class="event-log-contents" rows="8" cols="25"></textarea> <button class="clear-log">clear</button> </div> css body { padding: .2rem; display: grid; grid-template-areas: "control log"; } .co...
Element: compositionstart event - Web APIs
yes interface compositionevent event handler property none examples const inputelement = document.queryselector('input[type="text"]'); inputelement.addeventlistener('compositionstart', (event) => { console.log(`generated characters were: ${event.data}`); }); live example html <div class="control"> <label for="name">on macos, click in the textbox below,<br> then type <kbd>option</kbd> + <kbd>`</kbd>, then <kbd>a</kbd>:</label> <input type="text" id="example" name="example"> </div> <div class="event-log"> <label>event log:</label> <textarea readonly class="event-log-contents" rows="8" cols="25"></textarea> <button class="clear-log">clear</button> </div> css body { padding: .2rem; display: grid; grid-template-areas: "control log"; } .co...
Element: compositionupdate event - Web APIs
yes interface compositionevent event handler property none examples const inputelement = document.queryselector('input[type="text"]'); inputelement.addeventlistener('compositionupdate', (event) => { console.log(`generated characters were: ${event.data}`); }); live example html <div class="control"> <label for="name">on macos, click in the textbox below,<br> then type <kbd>option</kbd> + <kbd>`</kbd>, then <kbd>a</kbd>:</label> <input type="text" id="example" name="example"> </div> <div class="event-log"> <label>event log:</label> <textarea readonly class="event-log-contents" rows="8" cols="25"></textarea> <button class="clear-log">clear</button> </div> css body { padding: .2rem; display: grid; grid-template-areas: "control log"; } .co...
Element.getAnimations() - Web APIs
promise.all( elem.getanimations({ subtree: true }) .map(animation => animation.finished) ).then(() => elem.remove()); specifications specification status comment web animationsthe definition of 'animatable.getanimations()' in that specification.
Element.getBoundingClientRect() - Web APIs
if all the element's border-boxes are empty, then a rectangle is returned with a width and height of zero and where the top and left are the top-left of the border-box for the first css box (in content order) for the element.
Element.insertAdjacentElement() - Web APIs
when one is clicked, it becomes selected and you can then press the insert before and insert after buttons to insert new divs before or after the selected element using insertadjacentelement().
Element.insertAdjacentText() - Web APIs
you can enter some text into the form element, then press the insert before and insert after buttons to insert it before or after the existing paragraph text using insertadjacenttext().
Element: keydown event - Web APIs
<input placeholder="click here, then press down a key." size="40"> <p id="log"></p> const input = document.queryselector('input'); const log = document.getelementbyid('log'); input.addeventlistener('keydown', logkey); function logkey(e) { log.textcontent += ` ${e.code}`; } onkeydown equivalent input.onkeydown = logkey; specifications specification status ui events working draft ...
Element: keyup event - Web APIs
<input placeholder="click here, then press and release a key." size="40"> <p id="log"></p> const input = document.queryselector('input'); const log = document.getelementbyid('log'); input.addeventlistener('keyup', logkey); function logkey(e) { log.textcontent += ` ${e.code}`; } onkeyup equivalent input.onkeyup = logkey; specifications specification status ui events working draft ...
Element.namespaceURI - Web APIs
if the namespaceuri returns the xul namespace and the localname returns "browser", then the node is understood to be a xul <browser/>.
Element.part - Web APIs
WebAPIElementpart
here the part attribute is used to find the shadow parts, and the part property is then used to change the part identifiers of each tab so the correct styling is applied to the active tab when tabs are clicked.
Element.querySelector() - Web APIs
the resulting elements are then examined to see if they are descendants of baseelement.
Element.querySelectorAll() - Web APIs
if the array is empty (that is, its length property is 0), then no matches were found.
Element.requestFullscreen() - Web APIs
if the element has been detached from the original document, then the document receives these events instead.
Element.scrollIntoViewIfNeeded() - Web APIs
if the element is already within the visible area of the browser window, then no scrolling takes place.
Element.scrollLeft - Web APIs
if the element's direction is rtl (right-to-left), then scrollleft is 0 when the scrollbar is at its rightmost position (at the start of the scrolled content), and then increasingly negative as you scroll towards the end of the content.
Element.scrollTop - Web APIs
WebAPIElementscrollTop
when an element's content does not generate a vertical scrollbar, then its scrolltop value is 0.
Element.setAttributeNodeNS() - Web APIs
terleft">one</div> // <div id="two">two</div> var myns = "http://www.mozilla.org/ns/specialspace"; var d1 = document.getelementbyid("one"); var d2 = document.getelementbyid("two"); var a = d1.getattributenodens(myns, "special-align"); d2.setattributenodens(a.clonenode(true)); alert(d2.attributes[1].value) // returns: `utterleft' notes if the specified attribute already exists on the element, then that attribute is replaced with the new one and the replaced one is returned.
Element.shadowRoot - Web APIs
from here we use standard dom traversal techniques to find the <style> element inside the shadow dom and then update the css found inside it: function updatestyle(elem) { const shadow = elem.shadowroot; const childnodes = array.from(shadow.childnodes); childnodes.foreach(childnode => { if (childnode.nodename === 'style') { childnode.textcontent = ` div { width: ${elem.getattribute('l')}px; height: ${elem.getattribute('l')}px; background-color: ${ele...
Element.tagName - Web APIs
WebAPIElementtagName
if an xml document includes a tag "<sometag>", then the tagname property's value is "sometag".
Event.cancelable - Web APIs
WebAPIEventcancelable
if the event is not cancelable, then its cancelable property will be false and the event listener cannot stop the event from occurring.
Event.currentTarget - Web APIs
if you console.log() the event object, storing it in a variable, and then look for the currenttarget key in the console, its value will be null.
Event.eventPhase - Web APIs
WebAPIEventeventPhase
this process starts with the window, then document, then the htmlhtmlelement, and so on through the elements until the target's parent is reached.
ExtendableEvent - Web APIs
resources to pre-fetch:', urlstoprefetch); event.waituntil( caches.open(current_caches['prefetch']).then(function(cache) { return cache.addall(urlstoprefetch.map(function(urltoprefetch) { return new request(urltoprefetch, {mode: 'no-cors'}); })).then(function() { console.log('all resources have been fetched and cached.'); }); }).catch(function(error) { console.error('pre-fetching failed:', error); }) ); }); important: when fetching resources, it's v...
FeaturePolicy.allowedFeatures() - Web APIs
// first, get the feature policy object const featurepolicy = document.featurepolicy // then query feature for specific const allowed = featurepolicy.allowedfeatures() for (const directive of allowed){ console.log(directive) } specifications specification status comment feature policythe definition of 'allowsfeature' in that specification.
FeaturePolicy.allowsFeature() - Web APIs
// first, get the feature policy object const featurepolicy = document.featurepolicy // then query feature for specific const allowed = featurepolicy.allowsfeature("camera") if (allowed){ console.log("fp allows camera.") } else { console.log("fp does not allows camera.") } specifications specification status comment feature policythe definition of 'allowsfeature' in that specification.
FeaturePolicy.getAllowlistForFeature() - Web APIs
// first, get the feature policy object const featurepolicy = document.featurepolicy // then query feature for specific const allowlist = featurepolicy.getallowlistforfeature("camera") for (const origin of allowlist){ console.log(origin) } specification specification status comment feature policythe definition of 'getallowlistforfeature' in that specification.
FetchEvent.clientId - Web APIs
the clients.get() method could then be passed this id to retrieve the associated client.
FileReader.result - Web APIs
WebAPIFileReaderresult
it works by creating a filereader object and creating a listener for load events such that when then file is read, the result is obtained and passed to the callback function provided to read().
FileSystemEntry.fullPath - Web APIs
example this example shows a function which is called with a file system; it then gets a filesystemfileentry for a file named data.json and returns its full path.
FileSystemEntry.getParent() - Web APIs
then moveto() is used to rename the file within that directory.
FileSystemEntry.toURL() - Web APIs
return value a domstring containing a url that can then be used as a document reference in html content, or an empty string if the url can't be generated (such as if the file system implementation doesn't support tourl()).
FileSystemFileEntry.createWriter() - Web APIs
this blob is then output to the filewriter object to be written to the file.
File and Directory Entries API support in Firefox - Web APIs
there are only two ways to get access to file system entries at this time: the <input> element, using the htmlinputelement.webkitentries property to access an array of filesystementry objects describing file system entries you can then read.
File and Directory Entries API - Web APIs
if the result isn't null, then it's a dropped file or directory, and you can use file system calls to work with it.
FontFaceSet.ready - Web APIs
WebAPIFontFaceSetready
syntax fontfaceset.ready.then(function(fontfaceset) { // ...
FormData - Web APIs
WebAPIFormData
the formdata interface provides a way to easily construct a set of key/value pairs representing form fields and their values, which can then be easily sent using the xmlhttprequest.send() method.
FormDataEvent() - Web APIs
this would then be accessed through the formdataevent.formdata property.
FullscreenOptions.navigationUI - Web APIs
let elem = document.documentelement; elem.requestfullscreen({ navigationui: "show" }).then({}).catch(err => { alert(`an error occurred while trying to switch into full-screen mode: ${err.message} (${err.name})`); }); the promise's resolve handler does nothing, but if the promise is rejected, an error message is displayed by calling alert().
Fullscreen API - Web APIs
note: use the fullscreenelement property on the document or shadowroot instead; if it's not null, then it's an element currently being displayed in full-screen mode.
GainNode.gain - Web APIs
WebAPIGainNodegain
example the following example shows basic usage of an audiocontext to create a gainnode, which is then used to mute and unmute the audio when a mute button is clicked by changing the gain property value.
GainNode - Web APIs
WebAPIGainNode
example the following example shows basic usage of an audiocontext to create a gainnode, which is then used to mute and unmute the audio when a mute button is clicked by changing the gain property value.
GamepadHapticActuator.pulse() - Web APIs
syntax gamepadhapticactuatorinstance.pulse(value, duration).then(function(result) { ...
Geolocation API - Web APIs
if they accept, then the browser will use the best available functionality on the device to access this information (for example, gps).
GlobalEventHandlers.ondrag - Web APIs
ragover_handler(ev) { console.log("dragover"); ev.preventdefault(); } </script> <body> <h1>examples of <code>ondrag</code>, <code>ondrop</code>, <code>ondragstart</code>, <code>ondragover</code></h1> <div> <!-- <div class="source"> --> <p id="source" ondrag="drag_handler(event);" ondragstart="dragstart_handler(event);" draggable="true"> select this element, drag it to the drop zone and then release the selection to move the element.</p> </div> <div id="target" ondrop="drop_handler(event);" ondragover="dragover_handler(event);">drop zone</div> </body> </html> specifications specification status comment html living standardthe definition of 'ondrag' in that specification.
GlobalEventHandlers.ondragend - Web APIs
el.ondragleave = dragleave_handler; el.ondragend = dragend_handler; el.ondragexit = dragexit_handler; } </script> <body onload="init();"> <h1>examples of <code>ondragenter</code>, <code>ondragleave</code>, <code>ondragend</code>, <code>ondragexit</code></h1> <div> <p id="source" ondragstart="dragstart_handler(event);" draggable="true"> select this element, drag it to the drop zone and then release the selection to move the element.</p> </div> <div id="target" ondrop="drop_handler(event);" ondragover="dragover_handler(event);">drop zone</div> </body> </html> specifications specification status comment html living standardthe definition of 'ondragend' in that specification.
GlobalEventHandlers.ondragenter - Web APIs
el.ondragleave = dragleave_handler; el.ondragend = dragend_handler; el.ondragexit = dragexit_handler; } </script> <body onload="init();"> <h1>examples of <code>ondragenter</code>, <code>ondragleave</code>, <code>ondragend</code>, <code>ondragexit</code></h1> <div> <p id="source" ondragstart="dragstart_handler(event);" draggable="true"> select this element, drag it to the drop zone and then release the selection to move the element.</p> </div> <div id="target" ondrop="drop_handler(event);" ondragover="dragover_handler(event);">drop zone</div> </body> </html> specifications specification status comment html living standardthe definition of 'ondragenter' in that specification.
GlobalEventHandlers.ondragexit - Web APIs
el.ondragleave = dragleave_handler; el.ondragend = dragend_handler; el.ondragexit = dragexit_handler; } </script> <body onload="init();"> <h1>examples of <code>ondragenter</code>, <code>ondragleave</code>, <code>ondragend</code>, <code>ondragexit</code></h1> <div> <p id="source" ondragstart="dragstart_handler(event);" draggable="true"> select this element, drag it to the drop zone and then release the selection to move the element.</p> </div> <div id="target" ondrop="drop_handler(event);" ondragover="dragover_handler(event);">drop zone</div> </body> </html> specifications specification status comment html living standardthe definition of 'ondragexit' in that specification.
GlobalEventHandlers.ondragleave - Web APIs
el.ondragleave = dragleave_handler; el.ondragend = dragend_handler; el.ondragexit = dragexit_handler; } </script> <body onload="init();"> <h1>examples of <code>ondragenter</code>, <code>ondragleave</code>, <code>ondragend</code>, <code>ondragexit</code></h1> <div> <p id="source" ondragstart="dragstart_handler(event);" draggable="true"> select this element, drag it to the drop zone and then release the selection to move the element.</p> </div> <div id="target" ondrop="drop_handler(event);" ondragover="dragover_handler(event);">drop zone</div> </body> </html> specifications specification status comment html living standardthe definition of 'ondragleave' in that specification.
GlobalEventHandlers.ondragover - Web APIs
mentbyid(data)); } function dragover_handler(ev) { console.log("dragover"); ev.preventdefault(); } </script> <body> <h1>examples of <code>ondrag</code>, <code>ondrop</code>, <code>ondragstart</code>, <code>ondragover</code></h1> <div> <p id="source" ondrag="drag_handler(event);" ondragstart="dragstart_handler(event);" draggable="true"> select this element, drag it to the drop zone and then release the selection to move the element.</p> </div> <div id="target" ondrop="drop_handler(event);" ondragover="dragover_handler(event);">drop zone</div> </body> </html> specifications specification status comment html living standardthe definition of 'ondragover' in that specification.
GlobalEventHandlers.ondragstart - Web APIs
mentbyid(data)); } function dragover_handler(ev) { console.log("dragover"); ev.preventdefault(); } </script> <body> <h1>examples of <code>ondrag</code>, <code>ondrop</code>, <code>ondragstart</code>, <code>ondragover</code></h1> <div> <p id="source" ondrag="drag_handler(event);" ondragstart="dragstart_handler(event);" draggable="true"> select this element, drag it to the drop zone and then release the selection to move the element.</p> </div> <div id="target" ondrop="drop_handler(event);" ondragover="dragover_handler(event);">drop zone</div> </body> </html> specifications specification status comment html living standardthe definition of 'ondragstart' in that specification.
GlobalEventHandlers.ondrop - Web APIs
; } function dragover_handler(ev) { console.log("dragover"); ev.preventdefault(); } </script> <body> <h1>examples of <code>ondrag</code>, <code>ondrop</code>, <code>ondragstart</code>, <code>ondragover</code></h1> <div class="source"> <p id="source" ondrag="drag_handler(event);" ondragstart="dragstart_handler(event);" draggable="true"> select this element, drag it to the drop zone and then release the selection to move the element.</p> </div> <div id="target" ondrop="drop_handler(event);" ondragover="dragover_handler(event);">drop zone</div> </body> </html> specifications specification status comment html living standardthe definition of 'ondrop' in that specification.
GlobalEventHandlers.onloadend - Web APIs
examples html content <img src="myimage.jpg"> javascript content // 'loadstart' fires first, then 'load', then 'loadend' image.addeventlistener('load', function(e) { console.log('image loaded'); }); image.addeventlistener('loadstart', function(e) { console.log('image load started'); }); image.addeventlistener('loadend', function(e) { console.log('image load finished'); }); ...
GlobalEventHandlers.onloadstart - Web APIs
examples html content <img src="myimage.jpg"> javascript content // 'loadstart' fires first, then 'load', then 'loadend' image.addeventlistener('load', function(e) { console.log('image loaded'); }); image.addeventlistener('loadstart', function(e) { console.log('image load started'); }); image.addeventlistener('loadend', function(e) { console.log('image load finished'); }); specifications specification status comment html living standardthe definition of ...
GlobalEventHandlers.ontransitioncancel - Web APIs
ck = function() { box.style.display = 'none'; timeout = window.settimeout(appear, 2000); function appear() { box.style.display = 'block'; } } box.ontransitioncancel = function(event) { console.log('transitioncancel fired after ' + event.elapsedtime + ' seconds.'); } result the resulting content looks like this: notice what happens when you hover your mouse cursor over the box, then move it away.
GlobalEventHandlers.ontransitionend - Web APIs
let box = document.queryselector(".box"); box.ontransitionrun = function(event) { box.innerhtml = "zooming..."; } box.ontransitionend = function(event) { box.innerhtml = "done!"; } result the resulting content looks like this: notice what happens when you hover your mouse cursor over the box, then move it away.
Audio() - Web APIs
if it's htmlmediaelement.have_enough_data, then there's enough data available that, given the current download rate, you should be able to play the audio through to the end without interruption.
HTMLAudioElement - Web APIs
examples basic usage you can create a htmlaudioelement entirely with javascript using the audio() constructor: var audioelement = new audio('car_horn.wav'); then you can invoke the play() method on the element audioelement.play(); a common gotcha is trying to play an audio element immediately on page load.
HTMLCanvasElement.toDataURL() - Web APIs
if the requested type is not image/png, but the returned value starts with data:image/png, then the requested type is not supported.
HTMLElement: animationcancel event - Web APIs
it then sets the element's display property to none, which will trigger the animationcancel event.
HTMLElement: change event - Web APIs
try entering something into the field below, and then click somewhere else to trigger the event.
HTMLElement.click() - Web APIs
WebAPIHTMLElementclick
this event then bubbles up to elements higher in the document tree (or event chain) and fires their click events.
HTMLElement: gotpointercapture event - Web APIs
it then calls setpointercapture() on the element on a pointerdown event, which will trigger gotpointercapture.
inert - Web APIs
WebAPIHTMLElementinert
according to the spec: when a node is inert, then the user agent must act as if the node was absent for the purposes of targeting user interaction events, may ignore the node for the purposes of text search user interfaces (commonly known as "find in page"), and may prevent the user from selecting text in that node.
HTMLElement.innerText - Web APIs
as a getter, it approximates the text the user would get if they highlighted the contents of the element with the cursor and then copied it to the clipboard.
HTMLElement.offsetHeight - Web APIs
if the element is hidden (for example, by setting style.display on the element or one of its ancestors to "none"), then 0 is returned.
HTMLElement.offsetWidth - Web APIs
if the element is hidden (for example, by setting style.display on the element or one of its ancestors to "none"), then 0 is returned.
HTMLElement: pointercancel event - Web APIs
the pointercancel event is fired when the browser determines that there are unlikely to be any more pointer events, or if after the pointerdown event is fired, the pointer is then used to manipulate the viewport by panning, zooming, or scrolling.
HTMLElement: transitionend event - Web APIs
in the case where a transition is removed before completion, such as if the transition-property is removed or display is set to none, then the event will not be generated.
HTMLElement - Web APIs
as a getter, it approximates the text the user would get if they highlighted the contents of the element with the cursor and then copied it to the clipboard.
HTMLFormElement.elements - Web APIs
<form id="my-form"> <input type="text" name="username"> <input type="text" name="full-name"> <input type="password" name="password"> </form> var inputs = document.getelementbyid("my-form").elements; var inputbyindex = inputs[0]; var inputbyname = inputs["username"]; accessing form controls this example gets the form's element list, then iterates over the list, looking for <input> elements of type "text" so that some form of processing can be performed on them.
HTMLFormElement.name - Web APIs
if your <form> element contains an element named name then that element overrides the form.name property, so that you can't access it.
HTMLFormElement: submit event - Web APIs
examples this example uses eventtarget.addeventlistener() to listen for form submit, and logs the current event.timestamp whenever that occurs, then prevents the default action of submitting the form.
HTMLHyperlinkElementUtils.host - Web APIs
the htmlhyperlinkelementutils.host property is a usvstring containing the host, that is the hostname, and then, if the port of the url is nonempty, a ':', and the port of the url.
HTMLHyperlinkElementUtils - Web APIs
htmlhyperlinkelementutils.host this is a usvstring containing the host, that is the hostname, and then, if the port of the url is not empty (which can happen because it was not specified or because it was specified to be the default port of the url's scheme), a ':', and the port of the url.
HTMLImageElement.isMap - Web APIs
the browser then fetches that url from the server and displays or downloads it depending on the value of the download attribute.
HTMLImageElement.loading - Web APIs
preventing element shift during image lazy loads when an image whose loading has been delayed by the loading attribute being set to lazy is finally loaded, the browser will determine the final size of the <img> element based on the style and intrinsic size of the image, then reflow the document as needed to update the positions of elements based on any size change made to the element to fit the image.
HTMLImageElement.srcset - Web APIs
this is followed by a comma (,) character and then a condition descriptor that indicates the circumstances in which the indicated image should be used.
HTMLImageElement.x - Web APIs
then it looks at that <tr> (table row) element's cells property to get a list of the cells in that row.
HTMLImageElement.y - Web APIs
then it looks at that <tr> (table row) element's cells property to get a list of the cells in that row.
HTMLInputElement.setSelectionRange() - Web APIs
syntax element.setselectionrange(selectionstart, selectionend [, selectiondirection]); parameters if selectionend is less than selectionstart, then both are treated as the value of selectionend.
HTMLInputElement.webkitdirectory - Web APIs
pic1000.jpg pic1004.jpg pic1044.jpg don's 40th birthday pic2343.jpg pic2344.jpg pic2355.jpg pic2356.jpg vacations mars pic5533.jpg pic5534.jpg pic5556.jpg pic5684.jpg pic5712.jpg if the user chooses photoalbums, then the list reported by files will contain file objects for every file listed above—but not the directories.
HTMLKeygenElement - Web APIs
if this message is not the empty string, then the element is suffering from a custom validity error, and does not validate.
HTMLLegendElement - Web APIs
if the legend has a fieldset element as its parent, then this attribute returns the same value as the form attribute on the parent fieldset element.
HTMLMarqueeElement - Web APIs
if truespeed is true, then those values are not ignored.
HTMLMediaElement: canplay event - Web APIs
bubbles no cancelable no interface event target element default action none event handler property globaleventhandlers.oncanplay specification html5 media examples these examples add an event listener for the htmlmediaelement's canplay event, then post a message when that event handler has reacted to the event firing.
HTMLMediaElement: canplaythrough event - Web APIs
bubbles no cancelable no interface event target element default action none event handler property globaleventhandlers.oncanplaythrough specification html5 media examples these examples add an event listener for the htmlmediaelement's canplaythrough event, then post a message when that event handler has reacted to the event firing.
HTMLMediaElement.captureStream() - Web APIs
the stream can then be used for other purposes—like a source for streaming over webrtc, to allow sharing prerecorded videos with another person during a video call.
HTMLMediaElement: durationchange event - Web APIs
bubbles no cancelable no interface event target element default action none event handler property globaleventhandlers.ondurationchange specification html5 media examples these examples add an event listener for the htmlmediaelement's durationchange event, then post a message when that event handler has reacted to the event firing.
HTMLMediaElement: emptied event - Web APIs
bubbles no cancelable no interface event target element default action none event handler property globaleventhandlers.onemptied specification html5 media examples these examples add an event listener for the htmlmediaelement's emptied event, then post a message when that event handler has reacted to the event firing.
HTMLMediaElement: ended event - Web APIs
bbles no cancelable no interface event target element default action none event handler property globaleventhandlers.onended specification html5 media this event is also defined in media capture and streams and web audio api examples these examples add an event listener for the htmlmediaelement's ended event, then post a message when that event handler has reacted to the event firing.
HTMLMediaElement.load() - Web APIs
usage notes calling load() aborts all ongoing operations involving this media element, then begins the process of selecting and loading an appropriate media resource given the options specified in the <audio> or <video> element and its src attribute or child <source> element(s).
HTMLMediaElement: loadeddata event - Web APIs
examples these examples add an event listener for the htmlmediaelement's loadeddata event, then post a message when that event handler has reacted to the event firing.
HTMLMediaElement: loadedmetadata event - Web APIs
examples these examples add an event listener for the htmlmediaelement's loadedmetadata event, then post a message when that event handler has reacted to the event firing.
HTMLMediaElement.networkState - Web APIs
examples this example will listen for the audio element to begin playing and then check if it is still loading data.
HTMLMediaElement: pause event - Web APIs
general info bubbles no cancelable no interface event target element default action none event handler property globaleventhandlers.onpause specification html5 media examples these examples add an event listener for the htmlmediaelement's pause event, then post a message when that event handler has reacted to the event firing.
HTMLMediaElement.play() - Web APIs
it then sets up an event handler for the click event on the play toggle button and attempts to automatically begin playback by calling playvideo().
HTMLMediaElement: play event - Web APIs
bubbles no cancelable no interface event target element default action none event handler property globaleventhandlers.onplay specification html5 media examples these examples add an event listener for the htmlmediaelement's play event, then post a message when that event handler has reacted to the event firing.
HTMLMediaElement: playing event - Web APIs
bubbles no cancelable no interface event target element default action none event handler property globaleventhandlers.onplaying specification html5 media examples these examples add an event listener for the htmlmediaelement's playing event, then post a message when that event handler has reacted to the event firing.
HTMLMediaElement: ratechange event - Web APIs
bubbles no cancelable no interface event target element default action none event handler property globaleventhandlers.onratechange specification html5 media examples these examples add an event listener for the htmlmediaelement's ratechange event, then post a message when that event handler has reacted to the event firing.
HTMLMediaElement.readyState - Web APIs
it will then check if at least the current playback position has been loaded.
HTMLMediaElement: seeked event - Web APIs
bubbles no cancelable no interface event target element default action none event handler property globaleventhandlers.onseeked specification html5 media examples these examples add an event listener for the htmlmediaelement's seeked event, then post a message when that event handler has reacted to the event firing.
HTMLMediaElement: seeking event - Web APIs
bubbles no cancelable no interface event target element default action none event handler property globaleventhandlers.onseeking specification html5 media examples these examples add an event listener for the htmlmediaelement's seeking event, then post a message when that event handler has reacted to the event firing.
HTMLMediaElement.setSinkId() - Web APIs
syntax htmlmediaelement.setsinkid(sinkid).then(function() { ...
HTMLMediaElement.srcObject - Web APIs
usage notes older versions of the media source specification required using createobjecturl() to create an object url then setting src to that url.
HTMLMediaElement: stalled event - Web APIs
bubbles no cancelable no interface event target element default action none event handler property globaleventhandlers.onstalled specification html5 media examples these examples add an event listener for the htmlmediaelement's stalled event, then post a message when that event handler has reacted to the event firing.
HTMLMediaElement: suspend event - Web APIs
bubbles no cancelable no interface event target element default action none event handler property globaleventhandlers.onsuspend specification html5 media examples these examples add an event listener for the htmlmediaelement's suspend event, then post a message when that event handler has reacted to the event firing.
HTMLMediaElement: timeupdate event - Web APIs
bubbles no cancelable no interface event target element default action none event handler property globaleventhandlers.ontimeupdate specification html5 media examples these examples add an event listener for the htmlmediaelement's timeupdate event, then post a message when that event handler has reacted to the event firing.
HTMLMediaElement: volumechange event - Web APIs
bubbles no cancelable no interface event target element default action none event handler property globaleventhandlers.onvolumechange specification html5 media examples these examples add an event listener for the htmlmediaelement's volumechange event, then post a message when that event handler has reacted to the event firing.
HTMLMediaElement: waiting event - Web APIs
bubbles no cancelable no interface event target element default action none event handler property globaleventhandlers.onwaiting specification html5 media examples these examples add an event listener for the htmlmediaelement's waiting event, then post a message when that event handler has reacted to the event firing.
HTMLObjectElement - Web APIs
if this message is not the empty string, then the element is suffering from a custom validity error, and does not validate.
HTMLSelectElement.checkValidity() - Web APIs
if the element fails its constraints, the browser fires a cancelable invalid event at the element, and then returns false.
HTMLSelectElement.form - Web APIs
if the element is not associated with of a <form> element, then it returns null.
HTMLSelectElement.selectedOptions - Web APIs
when clicked, the event handler fetches the list of selected options using selectedoptions, then iterates over the options in the list.
HTMLSlotElement.assignedNodes() - Web APIs
let slots = this.shadowroot.queryselectorall('slot'); slots[1].addeventlistener('slotchange', function(e) { let nodes = slots[1].assignednodes(); console.log('element in slot "' + slots[1].name + '" changed to "' + nodes[0].outerhtml + '".'); }); here we grab references to all the slots, then add a slotchange event listener to the 2nd slot in the template — which is the one that keeps having its contents changed in the example.
HTMLSlotElement.name - Web APIs
let slots = this.shadowroot.queryselectorall('slot'); slots[1].addeventlistener('slotchange', function(e) { let nodes = slots[1].assignednodes(); console.log('element in slot "' + slots[1].name + '" changed to "' + nodes[0].outerhtml + '".'); }); here we grab references to all the slots, then add a slotchange event listener to the 2nd slot in the template — which is the one that keeps having its contents changed in the example.
HTMLSlotElement: slotchange event - Web APIs
let slots = this.shadowroot.queryselectorall('slot'); slots[1].addeventlistener('slotchange', function(e) { let nodes = slots[1].assignednodes(); console.log('element in slot "' + slots[1].name + '" changed to "' + nodes[0].outerhtml + '".'); }); here we grab references to all the <slot>s, then add a slotchange event listener to the template's second slot — which is the one which has its contents changed in the example.
HTMLSlotElement - Web APIs
let slots = this.shadowroot.queryselectorall('slot'); slots[1].addeventlistener('slotchange', function(e) { let nodes = slots[1].assignednodes(); console.log('element in slot "' + slots[1].name + '" changed to "' + nodes[0].outerhtml + '".'); }); here we grab references to all the slots, then add a slotchange event listener to the 2nd slot in the template — which is the one that keeps having its contents changed in the example.
HTMLTableElement.createCaption() - Web APIs
if no <caption> element exists on the table, this method creates it, and then returns it.
HTMLTableElement.createTFoot() - Web APIs
if no footer exists in the table, this methods creates it, and then returns it.
HTMLTableElement.createTHead() - Web APIs
if no header exists in the table, this method creates it, and then returns it.
HTMLTableElement.insertRow() - Web APIs
we then use htmltablerowelement.insertcell() to insert a new cell in the new row.
HTMLTableRowElement.insertCell() - Web APIs
we then use insertcell(0) to insert a new cell in the new row.
HTMLTextAreaElement - Web APIs
if this message is not the empty string, then the element is suffering from a custom validity error, and does not validate.
HTMLTrackElement - Web APIs
you can then change the mode as desired later.
HTMLVideoElement.msZoom - Web APIs
the rendered video will then take up the full space of the video object.
Dragging and Dropping Multiple Items - Web APIs
ataat("text/plain", "url2", 1); dt.mozsetdataat("text/uri-list", "url3", 2); dt.mozsetdataat("text/plain", "url3", 2); // [item1] data=url1, index=0 // [item2] data=url2, index=1 // [item3] data=url3, index=2 after you added three items in two different formats, dt.mozcleardataat("text/uri-list", 1); dt.mozcleardataat("text/plain", 1); you've removed the second item clearing all types, then the old third item becomes new second item, and its index decreases.
Recommended Drag Types - Web APIs
as a result, the contains method no longer works; the includes method should be used instead to check if a specific type of data is provided, using code like the following: if ([...event.datatransfer.types].includes('text/html')) { // do something } you could use feature detection to determine which method is supported on types, then run code as appropriate.
Headers.delete() - Web APIs
WebAPIHeadersdelete
example creating an empty headers object is simple: var myheaders = new headers(); // currently empty you could add a header to this using headers.append: myheaders.append('content-type', 'image/jpeg'); myheaders.get('content-type'); // returns 'image/jpeg' you can then delete it again: myheaders.delete('content-type'); myheaders.get('content-type'); // returns null, as it has been deleted specifications specification status comment fetchthe definition of 'delete()' in that specification.
Headers.get() - Web APIs
WebAPIHeadersget
example creating an empty headers object is simple: var myheaders = new headers(); // currently empty myheaders.get('not-set'); // returns null you could add a header to this using headers.append, then retrieve it using get(): myheaders.append('content-type', 'image/jpeg'); myheaders.get('content-type'); // returns "image/jpeg" if the header has multiple values associated with it, the byte string will contain all the values, in the order they were added to the headers object: myheaders.append('accept-encoding', 'deflate'); myheaders.append('accept-encoding', 'gzip'); myheaders.get('accept-e...
Headers.getAll() - Web APIs
WebAPIHeadersgetAll
example creating an empty headers object is simple: var myheaders = new headers(); // currently empty you could add a header to this using headers.append, then retrieve it using getall(): myheaders.append('content-type', 'image/jpeg'); myheaders.getall('content-type'); // returns [ "image/jpeg" ] if the header has multiple values associated with it, the array will contain all the values, in the order they were added to the headers object: myheaders.append('accept-encoding', 'deflate'); myheaders.append('accept-encoding', 'gzip'); myheaders.getall('a...
Headers.has() - Web APIs
WebAPIHeadershas
example creating an empty headers object is simple: var myheaders = new headers(); // currently empty you could add a header to this using headers.append, then test for the existence of it using has(): myheaders.append('content-type', 'image/jpeg'); myheaders.has('content-type'); // returns true myheaders.has('accept-encoding'); // returns false specifications specification status comment fetchthe definition of 'has()' in that specification.
Headers.set() - Web APIs
WebAPIHeadersset
example creating an empty headers object is simple: var myheaders = new headers(); // currently empty you could add a header to this using headers.append, then set a new value for this header using set(): myheaders.append('content-type', 'image/jpeg'); myheaders.set('content-type', 'text/html'); if the specified header does not already exist, set() will create it and set its value to the specified value.
Headers - Web APIs
WebAPIHeaders
examples in the following snippet, we create a new header using the headers() constructor, add a new header to it using append(), then return that header value using get(): var myheaders = new headers(); myheaders.append('content-type', 'text/xml'); myheaders.get('content-type') // should return 'text/xml' the same can be achieved by passing an array of arrays or an object literal to the constructor: var myheaders = new headers({ 'content-type': 'text/xml' }); // or, using an array of arrays: myheaders = new headers([ ...
History API - Web APIs
and then illustrates some of the methods of the history object to add, replace, and move within the browser history for the current tab.
IDBCursor.advance() - Web APIs
WebAPIIDBCursoradvance
example in this simple fragment we create a transaction, retrieve an object store, then use a cursor to iterate through the records in the object store.
IDBCursor.continue() - Web APIs
example in this simple fragment we create a transaction, retrieve an object store, then use a cursor to iterate through all the records in the object store.
IDBCursor.delete() - Web APIs
WebAPIIDBCursordelete
example in this simple fragment we create a transaction, retrieve an object store, then use a cursor to iterate through all the records in the object store.
IDBCursor.direction - Web APIs
example in this simple fragment we create a transaction, retrieve an object store, then use a cursor to iterate through all the records in the object store.
IDBCursor.key - Web APIs
WebAPIIDBCursorkey
example in this simple fragment we create a transaction, retrieve an object store, then use a cursor to iterate through all the records in the object store.
IDBCursor.primaryKey - Web APIs
example in this simple fragment we create a transaction, retrieve an object store, then use a cursor to iterate through all the records in the object store.
IDBCursor.request - Web APIs
WebAPIIDBCursorrequest
examples when you open a cursor, the request property is then available on that cursor object, to tell you what request object the cursor originated from.
IDBCursor.source - Web APIs
WebAPIIDBCursorsource
example in this simple fragment we create a transaction, retrieve an object store, then use a cursor to iterate through all the records in the object store.
IDBCursor - Web APIs
WebAPIIDBCursor
examples in this simple fragment we create a transaction, retrieve an object store, then use a cursor to iterate through all the records in the object store.
IDBCursorWithValue.value - Web APIs
example in this example we create a transaction, retrieve an object store, then use a cursor to iterate through all the records in the object store.
IDBCursorWithValue - Web APIs
example in this example we create a transaction, retrieve an object store, then use a cursor to iterate through all the records in the object store.
IDBDatabase: abort event - Web APIs
bubbles yes cancelable no interface event event handler property onabort examples this example opens a database (creating the database if it does not exist), then opens a transaction, adds a listener to the abort event, then aborts the transaction to trigger the event.
IDBDatabase.name - Web APIs
WebAPIIDBDatabasename
example this example shows a database connection being opened, the resulting idbdatabase object being stored in a db variable, and the name property then being logged.
IDBDatabaseSync - Web APIs
if a null path is specified, then the object store does not have a key path, and uses out-of-line keys.
databases - Web APIs
example const promise = indexeddb.databases() promise.then(databases => { console.log(databases) }) specifications specification status comment indexed database api draftthe definition of 'databases()' in that specification.
IDBKeyRange.bound() - Web APIs
WebAPIIDBKeyRangebound
if we used idbkeyrange.bound("a", "f", true, true);, then the range would not include "a" and "f", only the values between them.
IDBKeyRange.lowerBound() - Web APIs
if we used idbkeyrange.lowerbound("f", true);, then the range would not include "f"; only the values after it.
IDBKeyRange.upperBound() - Web APIs
if we used idbkeyrange.upperbound("f", true);, then the range excludes "f"; and instead only includes the values before it.
IDBObjectStore.add() - Web APIs
if a record already exists in the object store with the key parameter as its key, then an error constrainerror event is fired on the returned request object.
IDBObjectStore.count() - Web APIs
example in this simple fragment we create a transaction, retrieve an object store, then count the number of records in the store using count() — when the success handler fires, we log the count value (an integer) to the console.
IDBObjectStore.createIndex() - Web APIs
any sorting operations performed on the data via key ranges will then obey sorting rules of that locale (see locale-aware sorting.) you can specify its value in one of three ways: string: a string containing a specific locale code, e.g.
IDBObjectStore.getAll() - Web APIs
if a value is successfully found, then a structured clone of it is created and set as the result of the request object.
IDBObjectStore.getAllKeys() - Web APIs
if a value is successfully found, then a structured clone of it is created and set as the result of the request object.
IDBObjectStore.getKey() - Web APIs
if a key is successfully found, then a structured clone of it is created and set as the result of the request object.
IDBObjectStore.openCursor() - Web APIs
example in this simple fragment we create a transaction, retrieve an object store, then use a cursor to iterate through all the records in the object store: var transaction = db.transaction("name", "readonly"); var objectstore = transaction.objectstore("name"); var request = objectstore.opencursor(); request.onsuccess = function(event) { var cursor = event.target.result; if(cursor) { // cursor.value contains the current record being iterated through // this is where you...
IDBObjectStore.openKeyCursor() - Web APIs
example in this simple fragment we create a transaction, retrieve an object store, then use a cursor to iterate through all the records in the object store: var transaction = db.transaction("name", "readonly"); var objectstore = transaction.objectstore("name"); var request = objectstore.openkeycursor(); request.onsuccess = function(event) { var cursor = event.target.result; if(cursor) { // cursor.key contains the key of the current record being iterated through // note ...
IDBRequest.onerror - Web APIs
}; example the following example requests a given record title, onsuccess gets the associated record from the idbobjectstore (made available as objectstoretitlerequest.result), updates one property of the record, and then puts the updated record back into the object store.
IDBRequest.onsuccess - Web APIs
}; example the following example requests a given record title, onsuccess gets the associated record from the idbobjectstore (made available as objectstoretitlerequest.result), updates one property of the record, and then puts the updated record back into the object store.
IDBRequest.readyState - Web APIs
example the following example requests a given record title, onsuccess gets the associated record from the idbobjectstore (made available as objectstoretitlerequest.result), updates one property of the record, and then puts the updated record back into the object store in another request.
IDBRequest.result - Web APIs
WebAPIIDBRequestresult
syntax var myresult = request.result; value any example the following example requests a given record title, onsuccess gets the associated record from the idbobjectstore (made available as objectstoretitlerequest.result), updates one property of the record, and then puts the updated record back into the object store.
IDBRequest.source - Web APIs
WebAPIIDBRequestsource
example the following example requests a given record title, onsuccess gets the associated record from the idbobjectstore (made available as objectstoretitlerequest.result), updates one property of the record, and then puts the updated record back into the object store in another request.
IDBTransaction: abort event - Web APIs
examples this example opens a database (creating the database if it does not exist), then opens a transaction, adds a listener to the abort event, then aborts the transaction to trigger the event.
IIRFilterNode.getFrequencyResponse() - Web APIs
(5); next we create a <ul> element in our html to contain our results, and grab a reference to it in our javascript: <p>iir filter frequency response for: </p> <ul class="freq-response-output"> </ul> var freqresponseoutput = document.queryselector('.freq-response-output'); finally, after creating our filter, we use getfrequencyresponse() to generate the response data and put it in our arrays, then loop through each data set and output them in a human-readable list at the bottom of the page: var feedforwardcoefficients = [0.1, 0.2, 0.3, 0.4, 0.5]; var feedbackcoefficients = [0.5, 0.4, 0.3, 0.2, 0.1]; var iirfilter = audioctx.createiirfilter(feedforwardcoefficients, feedbackcoefficients); ...
IdleDeadline.didTimeout - Web APIs
your callback will typically check the value of didtimeout if it needs to perform an action even if the browser is too busy to grant you the time; you should react by performing the needed task or, ideally, a minimal amount of work that can be done to keep things moving along, then schedule a new callback to try again to get the rest of the work done.
ImageCapture() constructor - Web APIs
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 that specification.
ImageCapture.grabFrame() - Web APIs
var grabframebutton = document.queryselector('button#grabframe'); var canvas = document.queryselector('canvas'); grabframebutton.onclick = grabframe; function grabframe() { imagecapture.grabframe() .then(function(imagebitmap) { console.log('grabbed frame:', imagebitmap); canvas.width = imagebitmap.width; canvas.height = imagebitmap.height; canvas.getcontext('2d').drawimage(imagebitmap, 0, 0); canvas.classlist.remove('hidden'); }) .catch(function(error) { console.log('grabframe() error: ', error); }); } specifications specification status comment ...
ImageCapture.takePhoto() - Web APIs
var takephotobutton = document.queryselector('button#takephoto'); var canvas = document.queryselector('canvas'); takephotobutton.onclick = takephoto; function takephoto() { imagecapture.takephoto().then(function(blob) { console.log('took photo:', blob); img.classlist.remove('hidden'); img.src = url.createobjecturl(blob); }).catch(function(error) { console.log('takephoto() error: ', error); }); } specifications specification status comment mediastream image capturethe definition of 'takephoto()' in that specification.
IndexedDB API - Web APIs
you need to specify the database schema, open a connection to your database, and then retrieve and update data within a series of transactions.
InstallEvent - Web APIs
resources to pre-fetch:', urlstoprefetch); event.waituntil( caches.open(current_caches['prefetch']).then(function(cache) { return cache.addall(urlstoprefetch.map(function(urltoprefetch) { return new request(urltoprefetch, {mode: 'no-cors'}); })).then(function() { console.log('all resources have been fetched and cached.'); }); }).catch(function(error) { console.error('pre-fetching failed:', error); }) ); }); specifications specification ...
IntersectionObserver.unobserve() - Web APIs
example this snippet simply shows an observer being created, an element being observed, and then being unobserved.
IntersectionObserverEntry.isIntersecting - Web APIs
if this is true, then, the intersectionobserverentry describes a transition into a state of intersection; if it's false, then you know the transition is from intersecting to not-intersecting.
IntersectionObserverEntry - Web APIs
if this is true, then, the intersectionobserverentry describes a transition into a state of intersection; if it's false, then you know the transition is from intersecting to not-intersecting.
Keyboard.getLayoutMap() - Web APIs
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
WebAPIKeyboard
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.
KeyboardEvent.code - Web APIs
function refresh() { let x = position.x - (shipsize.width/2); let y = position.y - (shipsize.height/2); let transform = "translate(" + x + " " + y + ") rotate(" + angle + " 15 15) "; spaceship.setattribute("transform", transform); } finally, the addeventlistener() method is used to start listening for keydown events, acting on each key by updating the ship position and rotation angle, then calling refresh() to draw the ship at its new position and angle.
KeyboardLayoutMap.get() - Web APIs
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
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.
Keyboard API - Web APIs
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.
KeyframeEffect - Web APIs
these can then be played using the animation() constructor.
Location: host - Web APIs
WebAPILocationhost
the host property of the location interface is a usvstring containing the host, that is the hostname, and then, if the port of the url is nonempty, a ':', and the port of the url.
LockManager.request() - Web APIs
steal optional: if true, then any held locks with the same name will be released, and the request will be granted, preempting any queued requests for it.
LockedFile.active - Web APIs
WebAPILockedFileactive
if the object is inactive then it is impossible to perform any read or write operation with it.
MIDIAccess - Web APIs
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 specification sta...
MIDIMessageEvent - Web APIs
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.
MSCandidateWindowShow - Web APIs
example in ie11, developers can detect the opening of the ime candidate window by listening to mscandidatewindowshow event, then call getcandidatewindowclientrect() function to find out where the candidate window is and position the suggestion ui away from it: var context = document.getelementbyid("mysearchbox").msgetinputcontext(); context.addeventlistener("mscandidatewindowshow", candidatewindowshowhandler); function candidatewindowshowhandler(e) { var imerect = context.getcandidatewindowclientrect(); var suggest...
MediaCapabilities.decodingInfo() - Web APIs
}, }; // check support and performance navigator.mediacapabilities.decodinginfo(mediaconfig).then(result => { console.log('this configuration is ' + (result.supported ?
MediaCapabilities.encodingInfo() - Web APIs
} }; // check support and performance navigator.mediacapabilities.encodinginfo(mediaconfig).then(result => { console.log('this configuration is ' + (result.supported ?
MediaCapabilitiesInfo - Web APIs
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
} }; // check support and performance navigator.mediacapabilities.decodinginfo(mediaconfig).then(result => { console.log('this configuration is ' + (result.supported ?
MediaDeviceInfo - Web APIs
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 =...
MediaDevices.enumerateDevices() - Web APIs
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 =...
MediaDevices - Web APIs
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 = stream; }) .catch(function(error) { if (err...
MediaEncodingConfiguration - Web APIs
} }; // check support and performance navigator.mediacapabilities.encodinginfo(mediaconfig).then(result => { console.log('this configuration is ' + (result.supported ?
MediaError.code - Web APIs
WebAPIMediaErrorcode
example this example creates a <video> element, establishes an error handler for it, and then sets the element's src attribute to the video resource to present in the element.
msExtendedCode - Web APIs
the element's error property will then contain an msextendedcode read-only property with platform-specific error code information.
generateRequest() - Web APIs
syntax mediakeysession.generaterequest().then(function) { ...
load() - Web APIs
syntax mediakeysession.load(sessionid).then(function(booleanvalue) { ...
setServerCertificate() - Web APIs
syntax mediakeys.setservercertificate([mediakeysessiontype]).then(function() { ...
MediaPositionState.duration - Web APIs
this information can then, in turn, be used by the user agent to provide a user interface which displays media playback information to the viewer.
MediaPositionState.position - Web APIs
this information is then, in turn, used by the user agent to provide a user interface which displays media playback information to the viewer.
MediaQueryList.media - Web APIs
javascript let mql = window.matchmedia('(max-width: 600px)'); document.queryselector(".mq-value").innertext = mql.media; the javascript code simply passes the media query to match into matchmedia() to compile it, then sets the <span>'s innertext to the value of the result's media property.
MediaQueryList - Web APIs
examples this simple example creates a mediaquerylist and then sets up a listener to detect when the media query status changes, running a custom function when it does to change the appearence of the page.
MediaRecorder.ondataavailable - Web APIs
when mediarecorder.requestdata() is called, all media data which has been captured since recording began or the last time a dataavailable event occurred is delivered; then a new blob is created and media capture continues into that blob.
MediaRecorder.start() - Web APIs
then, each time that amount of media has been recorded, an event will be delivered to let you act upon the recorded media, while a new blob is created to record the next slice of the media assuming the mediarecorder's state is inactive, start() sets the state to recording, then begins capturing media from the input stream.
MediaSource.isTypeSupported() - Web APIs
if the returned value is false, then the user agent is certain that it cannot access media of the specified format.
active - Web APIs
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.getTrackById() - Web APIs
example this example activates a commentary track on a video by ducking the audio level of the main audio track to 50%, then enabling the commentary track.
MediaStream.getTracks() - Web APIs
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
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 that specification.
MediaStream.id - Web APIs
WebAPIMediaStreamid
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.
MediaStreamTrack.applyConstraints() - Web APIs
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.
MediaStreamTrack.enabled - Web APIs
"&#x25b6;&#xfe0f;" : "&#x23f8;&#xfe0f;"; myaudiotrack.enabled = newstate; } this creates a variable, newstate, which is the opposite of the current value of enabled, then uses that to select either the emoji character for the "play" icon or the character for the "pause" icon as the new innerhtml of the pause button's element.
MediaStreamTrack.stop() - Web APIs
then the stream's track list is obtained by calling its gettracks() method.
MediaStream Image Capture API - Web APIs
navigator.mediadevices.getusermedia({ video: true }) .then(mediastream => { // do something with the stream.
MediaTrackConstraints.autoGainControl - Web APIs
if, instead, the value is given as an object with an exact field, that field's boolean value indicates a required setting for the automatic gain control feature; if it can't be met, then the request will result in an error.
MediaTrackConstraints.cursor - Web APIs
usage notes you can check the setting selected by the user agent after the display media has been created by getdisplaymedia() by calling getsettings() on the display media's video mediastreamtrack, then checking the value of the returned mediatracksettings object's cursor object.
MediaTrackConstraints.displaySurface - Web APIs
usage notes you can check the setting selected by the user agent after the display media has been created by getdisplaymedia() by calling getsettings() on the display media's video mediastreamtrack, then checking the value of the returned mediatracksettings object's displaysurface object.
MediaTrackConstraints.echoCancellation - Web APIs
if, instead, the value is given as an object with an exact field, that field's boolean value indicates a required setting for the echo cancellation feature; if it can't be met, then the request will result in an error.
MediaTrackConstraints.logicalSurface - Web APIs
usage notes you can check the setting selected by the user agent after the display media has been created by getdisplaymedia() by calling getsettings() on the display media's video mediastreamtrack, then checking the value of the returned mediatracksettings object's logicalsurface object.
MediaTrackConstraints.noiseSuppression - Web APIs
if, instead, the value is given as an object with an exact field, that field's boolean value indicates a required setting for the noise suppression feature; if it can't be met, then the request will result in an error.
MediaTrackSupportedConstraints.cursor - Web APIs
capturing is then started by calling getdisplaymedia() and attaching the returned stream to the video element referenced by the variable videoelem.
MediaTrackSupportedConstraints.displaySurface - Web APIs
capturing is then started by calling getdisplaymedia() and attaching the returned stream to the video element referenced by the variable videoelem.
MediaTrackSupportedConstraints.logicalSurface - Web APIs
capturing is then started by calling getdisplaymedia() and attaching the returned stream to the video element referenced by the variable videoelem.
Transcoding assets for Media Source Extensions - Web APIs
bento4's mp4-dash.py python script can then be used to generate the corresponding mpd file needed by clients.
MerchantValidationEvent.complete() - Web APIs
the event handler calls a function, getvalidationdata(), which retrieves the data from the validation url, then passes that data (or a promise to deliver the data) into complete().
MessageChannel() - Web APIs
the handlemessage handler then responds to a message being sent back from the iframe (using messageport.onmessage), putting it into a paragraph.
MessageChannel.port1 - Web APIs
the handlemessage handler then responds to a message being sent back from the <iframe> (using messageport.onmessage), putting it into a paragraph.
MessageChannel.port2 - Web APIs
the handlemessage handler then responds to a message being sent back from the iframe (using messageport.onmessage), putting it into a paragraph.
MessagePort.onmessage - Web APIs
the handlemessage handler then responds to a message being sent back from the iframe using onmessage, putting it into a paragraph — messagechannel.port1 is listened to, to check when the message arrives.
MessagePort.postMessage() - Web APIs
the handlemessage handler then responds to a message being sent back from the iframe using onmessage, putting it into a paragraph — messagechannel.port1 is listened to, to check when the message arrives.
MutationObserver.MutationObserver() - Web APIs
then the observer is instantiated, specifying the callback() function.
MutationObserver.observe() - Web APIs
if the same mutationobserver is not already in use on the target, then the existing observers are left alone and the new one is added.
MutationObserver.takeRecords() - Web APIs
*/ /* handle any still-pending mutations */ let mutations = observer.takerecords(); observer.disconnect(); if (mutations) { callback(mutations); } the code in lines 12–17 fetches any unprocessed mutation records, then invokes the callback with the records so that they can be processed.
MutationObserverInit.attributeFilter - Web APIs
for any items representing an attribute change (which can be detected by the value of mutationrecord.type being "attributes"), we use the attribute's name, obtained using mutationrecord.attributename, to identify the type of change that occurred and then dispatch to the appropriate handler function.
MutationObserverInit - Web APIs
all of the other mutationobserverinit properties are then extended to all of the nodes in the subtree instead of applying solely to the target node.
NDEFRecord.id - Web APIs
WebAPINDEFRecordid
web nfc does not sign the nfc content, thus record consumer should not make any assumptions about integrity or authenticity of the identifier or any other part of the records.
Navigation Timing API - Web APIs
concepts and usage you can use the navigation timing api to gather performance data on the client side, which you can then transmit to a server using xmlhttprequest or other techniques.
Navigator.clipboard - Web APIs
navigator.clipboard.readtext().then( cliptext => document.queryselector(".cliptext").innertext = cliptext); this snippet replaces the contents of the element whose class is "cliptext" with the text contents of the clipboard.
Navigator.credentials - Web APIs
example if ('credentials' in navigator) { navigator.credentials.get({password: true}) .then(function(creds) { //do something with the credentials.
Navigator.getBattery() - Web APIs
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.
Navigator.getUserMedia() - Web APIs
your callback can then assign the stream to the desired object (such as an <audio> or <video> element), as shown in the following example: function(stream) { var video = document.queryselector('video'); video.srcobject = stream; video.onloadedmetadata = function(e) { // do something with the video here.
Navigator.mediaCapabilities - Web APIs
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.permissions - Web APIs
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.vibrate() - Web APIs
WebAPINavigatorvibrate
you may provide either a single value (to vibrate once for that many milliseconds) or an array of values to alternately vibrate, pause, then vibrate again.
Navigator - Web APIs
WebAPINavigator
navigator.mediadevices returns a reference to a mediadevices object which can then be used to get information about available media devices (mediadevices.enumeratedevices()), find out what constrainable properties are supported for media on the user's computer and user agent (mediadevices.getsupportedconstraints()), and to request access to media using mediadevices.getusermedia().
Network Information API - Web APIs
if a cellular connection is found, then the preloadvideo flag is set to false.
Node.appendChild() - Web APIs
WebAPINodeappendChild
so if the node already has a parent, the node is first removed, then appended at the new position.
Node.compareDocumentPosition() - Web APIs
for example, if othernode is located earlier in the document and contains the node on which comparedocumentposition() was called, then both the document_position_contains and document_position_preceding bits would be set, producing a value of 10 (0x0a).
Node.isEqualNode() - Web APIs
WebAPINodeisEqualNode
then we run some javascript to compare the nodes using isequalnode() and output the results.
Node.isSameNode() - Web APIs
WebAPINodeisSameNode
then we run some javascript to compare the nodes using issamenode() and output the results.
Node.lastChild - Web APIs
WebAPINodelastChild
if its parent is an element, then the child is generally an element node, a text node, or a comment node.
Node.namespaceURI - Web APIs
WebAPINodenamespaceURI
if the namespaceuri returns the xul namespace and the localname returns "browser", then the node is understood to be a xul <browser/>.
Notification.Notification() - Web APIs
the function is passed parameters to specify the body, icon, and title we want, and then it creates the necessary options object and triggers the notification by using the notification() constructor.
Notification.close() - Web APIs
examples in the following snippet, we have a simple function that when called creates an options object and then a new notification.
Notification.data - Web APIs
WebAPINotificationdata
examples the following snippet fires a notification; a simple options object is created, then the notification is fired using the notification() constructor.
Notification.dir - Web APIs
WebAPINotificationdir
examples the following snippet fires a notification; a simple options object is created, then the notification is fired using the notification() constructor.
Notification.lang - Web APIs
WebAPINotificationlang
examples the following snippet fires a notification; a simple options object is created, then the notification is fired using the notification() constructor.
Notification.permission - Web APIs
examples the following snippet could be used if you wanted to first check whether notifications are supported, then check if permission has been granted for the current origin to send notifications, then request permission if required, before then sending a notification.
Notification.renotify - Web APIs
examples the following snippet is intended to fire a notification that renotifies the user after it has been replaced; a simple options object is created, and then the notification is fired using the notification() constructor.
Notification.silent - Web APIs
examples the following snippet is intended to fire a silent notification; a simple options object is created, and then the notification is fired using the notification() constructor.
Notification.tag - Web APIs
WebAPINotificationtag
one notification can then be programmatically replaced with another to avoid the users' screen being filled up with a huge number of similar notifications.
Notification.timestamp - Web APIs
examples the following snippet fires a notification; a simple options object is created, then the notification is fired using the notification() constructor.
Notification.vibrate - Web APIs
examples the following snippet is intended to create a notification that also triggers a device vibration; a simple options object is created, and then the notification is fired using the notification() constructor.
NotificationEvent.notification - Web APIs
console.log('notification tag:', event.notification.tag); console.log('notification data:', event.notification.data); event.notification.close(); // this looks to see if the current is already open and // focuses if it is event.waituntil(clients.matchall({ type: "window" }).then(function(clientlist) { for (var i = 0; i < clientlist.length; i++) { var client = clientlist[i]; if (client.url == '/' && 'focus' in client) return client.focus(); } if (clients.openwindow) return clients.openwindow('/'); })); }); specifications specification status comment notifications apithe definition of 'notification' in ...
NotificationEvent - Web APIs
example self.addeventlistener('notificationclick', function(event) { console.log('on notification click: ', event.notification.tag); event.notification.close(); // this looks to see if the current is already open and // focuses if it is event.waituntil(clients.matchall({ type: "window" }).then(function(clientlist) { for (var i = 0; i < clientlist.length; i++) { var client = clientlist[i]; if (client.url == '/' && 'focus' in client) return client.focus(); } if (clients.openwindow) return clients.openwindow('/'); })); }); specifications specification status comment notifications apithe definition of 'notificationevent...
OfflineAudioContext.OfflineAudioContext() - Web APIs
the offlineaudiocontext() constructor—part of the web audio api—creates and returns a new offlineaudiocontext object instance, which can then be used to render audio to an audiobuffer rather than to an audio output device.
OfflineAudioContext.resume() - Web APIs
syntax offlineaudiocontext.resume().then(function() { ...
OfflineAudioContext.suspend() - Web APIs
syntax offlineaudiocontext.suspend(suspendtime).then(function() { ...
OffscreenCanvas.convertToBlob() - Web APIs
offscreen.converttoblob().then(function(blob) { console.log(blob); }); // blob { size: 334, type: "image/png" } specifications currently drafted as a proposal: offscreencanvas.
OffscreenCanvas() - Web APIs
we then initialize a webgl context on it using the getcontext() method.
OffscreenCanvas.convertToBlob() - Web APIs
offscreen.converttoblob().then(function(blob) { console.log(blob); }); // blob { size: 334, type: "image/png" } specifications specification status comment html living standardthe definition of 'offscreencanvas: converttoblob' in that specification.
OffscreenCanvas.getContext() - Web APIs
if set to false, the browser now knows that the backdrop is always opaque, which can speed up drawing of transparent content and images then.
OffscreenCanvas.convertToBlob() - Web APIs
offscreen.converttoblob().then(function(blob) { console.log(blob); }); // blob { size: 334, type: "image/png" } specifications currently drafted as a proposal: offscreencanvas.
OffscreenCanvas - Web APIs
calling getcontext() will then obtain a renderingcontext from that offscreencanvas.
OrientationSensor - Web APIs
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(); ...
PaintWorklet.registerPaint - Web APIs
to use it, you register it with the css.paintworklet.addmodule() method: <script> css.paintworklet.addmodule('checkboardworklet.js'); </script> you can then use the paint() css function in your css anywhere an <image> value is valid.
PannerNode.refDistance - Web APIs
he test tone with a given refdistance // and schedules it to move away from the listener along the z (depth-wise) axis // at the given start time, resulting in a decrease in volume (decay) const scheduletesttone = (refdistance, starttime) => { const osc = new oscillatornode(context); const panner = new pannernode(context); panner.refdistance = refdistance; // set the initial z position, then schedule the ramp panner.positionz.setvalueattime(0, starttime); panner.positionz.linearramptovalueattime(z_distance, starttime + note_length); osc.connect(panner) .connect(context.destination); osc.start(starttime); osc.stop(starttime + note_length); }; // this tone should decay immediately and fairly quickly scheduletesttone(1, context.currenttime); // this tone should decay s...
PannerNode.rolloffFactor - Web APIs
tone with a given rollofffactor // and schedules it to move away from the listener along the z (depth-wise) axis // at the given start time, resulting in a decrease in volume (decay) const scheduletesttone = (rollofffactor, starttime) => { const osc = new oscillatornode(context); const panner = new pannernode(context); panner.rollofffactor = rollofffactor; // set the initial z position, then schedule the ramp panner.positionz.setvalueattime(0, starttime); panner.positionz.linearramptovalueattime(z_distance, starttime + note_length); osc.connect(panner) .connect(context.destination); osc.start(starttime); osc.stop(starttime + note_length); }; // this tone should decay fairly quickly scheduletesttone(1, context.currenttime); // this tone should decay slower than the p...
ParentNode.children - Web APIs
if the node has no element children, then children is an empty list with a length of 0.
PasswordCredential.iconURL - Web APIs
the url must be accessible without authentication.
Path2D() - Web APIs
WebAPIPath2DPath2D
the path will move to point (m10 10) and then move horizontally 80 points to the right (h 80), then 80 points down (v 80), then 80 points to the left (h -80), and then back to the start (z).
Path2D - Web APIs
WebAPIPath2D
the path2d interface of the canvas 2d api is used to declare a path that can then be used on a canvasrenderingcontext2d object.
PaymentCurrencyAmount.value - Web APIs
this must be a valid decimal number, with an optional leading minus sign ("-"), then one or more decimal digits 0 through 9, optionally with a decimal point (".") with at least one digit following it to represent fractional units.
PaymentCurrencyAmount - Web APIs
this string must only contain an optional leading "-" to indicate a negative value, then one or more digits from 0 to 9, and an optional decimal point (".", regardless of locale) followed by at least one more digit.
PaymentRequest.PaymentRequest() - Web APIs
request.show().then(function(instrumentresponse) { // do something with the response from the ui.
PaymentRequest.abort() - Web APIs
var request = new paymentrequest(supportedinstruments, details, options); var paymenttimeout = window.settimeout(() => { window.cleartimeout(paymenttimeout); request.abort().then(() => { print('payment timed out after 20 minutes.'); }).catch(() => { print('unable to abort, because the user is currently in the process ' + 'of paying.'); }); }, 20 * 60 * 1000); /* 20 minutes */ specifications specification status comment payment request apithe definition of 'abort()' in that specification.
PaymentRequest.canMakePayment() - Web APIs
syntax paymentrequest.canmakepayment() .then( canpay => { ...
PaymentRequest.prototype.id - Web APIs
WebAPIPaymentRequestid
const details = { id: "super-store-order-123-12312", total: { label: "total due", amount: { currency: "usd", value: "65.00" }, }, }; const request = new paymentrequest(methoddata, details); console.log(request.id); // super-store-order-123-12312 the id is then also available in the paymentresponse returned from the show() method, but under the requestid attribute.
PaymentRequest.onmerchantvalidation - Web APIs
examples an example merchant validation handler for the paymentrequest object request looks like this: request.onmerchantvalidation = ev => { ev.complete(async () => { const merchantserverurl = window.location.origin + '/validation?url=' + encodeuricomponent(ev.validationurl); // get validation data, and complete validation; return await fetch(merchantserverurl).then(r => r.text()); }) }; const response = await request.show(); for more information, see merchant validation in payment processing concepts.
PaymentRequest.onshippingaddresschange - Web APIs
var payment = new paymentrequest(supportedinstruments, details, options); request.addeventlistener('shippingaddresschange', function(evt) { evt.updatewith(new promise(function(resolve) { updatedetails(details, request.shippingaddress, resolve); })); }); payment.show().then(function(paymentresponse) { // processing of paymentresponse exerpted for the same of clarity.
PaymentRequest.shippingAddress - Web APIs
var payment = new paymentrequest(supportedinstruments, details, options); payment.addeventlistener('shippingaddresschange', function(evt) { evt.updatewith(new promise(function(resolve) { updatedetails(details, request.shippingaddress, resolve); })); }); payment.show().then(function(paymentresponse) { // processing of paymentresponse exerpted for brevity.
PaymentResponse.complete() - Web APIs
var payment = new paymentrequest(supportedinstruments, details, options); payment.show().then(function(paymentresponse) { var fetchoptions = { method: 'post', credentials: include, body: json.stringify(paymentresponse) }; var serverpaymentrequest = new request('secure/payment/endpoint'); fetch(serverpaymentrequest, fetchoptions).then( response => { if (response.status < 400) { paymentresponse.complete("success"); } else { paymentresponse.complete("f...
PaymentResponse.onpayerdetailchange - Web APIs
il !== payeremail) { promisestovalidate.push(validateemail(payeremail)); oldpayeremail = payeremail; } if (oldpayerphone !== payerphone) { promisestovalidate.push(validatephone(payerphone)); oldpayerphone = payerphone; } // as each validation promise resolves, add the results of the // validation to the errors list const errors = await promise.all(promisestovalidate).then(results => results.reduce((errors, result), object.assign(errors, result)) ); // if we found any errors, wait for them to be corrected if (object.getownpropertynames(errors).length) { await response.retry(errors); } else { // we have a good payment; send the data to the server await fetch("/pay-for-things/", { method: "post", body: response.json() }); response.comple...
PaymentResponse: payerdetailchange event - Web APIs
il !== payeremail) { promisestovalidate.push(validateemail(payeremail)); oldpayeremail = payeremail; } if (oldpayerphone !== payerphone) { promisestovalidate.push(validatephone(payerphone)); oldpayerphone = payerphone; } // as each validation promise resolves, add the results of the // validation to the errors list const errors = await promise.all(promisestovalidate).then(results => results.reduce((errors, result), object.assign(errors, result)) ); // if we found any errors, wait for them to be corrected if (object.getownpropertynames(errors).length) { await response.retry(errors); } else { // we have a good payment; send the data to the server await fetch("/pay-for-things/", { method: "post", body: response.json() }); response.comple...
PaymentResponse.shippingAddress - Web APIs
var payment = new paymentrequest(supportedinstruments, details, options); request.addeventlistener('shippingaddresschange', function(evt) { evt.updatewith(new promise(function(resolve) { updatedetails(details, request.shippingaddress, resolve); })); }); payment.show().then(function(paymentresponse) { // processing of paymentresponse exerpted for the same of brevity.
PaymentResponse.shippingOption - Web APIs
var payment = new paymentrequest(supportedinstruments, details, options); request.addeventlistener('shippingoptionchange', function(evt) { evt.updatewith(new promise(function(resolve, reject) { updatedetails(details, request.shippingoption, resolve, reject); })); }); payment.show().then(function(paymentresponse) { // processing of paymentresponse exerpted for the same of brevity.
PerformanceNavigationTiming - Web APIs
if there was no redirect, or if the redirect was from another origin, and that origin does not permit it's timing information to be exposed to the current origin then the value will be 0.
PerformanceResourceTiming.connectEnd - Web APIs
the timestamp value includes the time interval to establish the transport connection, as well as other time intervals such as ssl handshake and socks authentication.
PerformanceTiming.connectEnd - Web APIs
a connection is considered as opened when all secure connection handshake, or socks authentication, is terminated.
PerformanceTiming - Web APIs
a connection is considered as opened when all secure connection handshake, or socks authentication, is terminated.
PermissionStatus.onchange - Web APIs
}) 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
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
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 that specification.
Permissions.revoke() - Web APIs
function revokepermission() { navigator.permissions.revoke({name:'geolocation'}).then(function(result) { report(result.state); }); } ...
Permissions - Web APIs
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.
Permissions API - Web APIs
once you have this object you can then perform permission-related tasks, for example querying a permission using the permissions.query() method to return a promise that resolves with the permissionstatus for a specific api.
Using Pointer Events - Web APIs
function copytouch(touch) { return { identifier: touch.pointerid, pagex: touch.clientx, pagey: touch.clienty }; } finding an ongoing touch the ongoingtouchindexbyid() function below scans through the ongoingtouches array to find the touch matching the given identifier, then returns that touch's index into the array.
PromiseRejectionEvent.promise - Web APIs
window.onunhandledrejection = function(event) { if (event.reason.code && event.reason.code == "module not ready") { window.requestidlecallback(function(deadline) { loadmodule(event.reason.modulename) .then(performstartup); }); event.preventdefault(); } } specifications specification status comment html living standardthe definition of 'promiserejectionevent.promise' in that specification.
PublicKeyCredential.getClientExtensionResults() - Web APIs
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 for accessing public key credentials level ...
PublicKeyCredential.id - Web APIs
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 web authentication: an api for a...
PublicKeyCredentialCreationOptions.rp - Web APIs
r 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 credentials level 1the definition of 'rp' in that...
PublicKeyCredentialCreationOptions.timeout - Web APIs
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 credentials level 1the definition of 'timeout' in...
PublicKeyCredentialRequestOptions.rpId - Web APIs
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 definition of 'rpid' in that specification.
PublicKeyCredentialRequestOptions.timeout - Web APIs
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 of 'timeout' in that specification.
PushManager.hasPermission() - Web APIs
syntax ​pushmanager.haspermission().then(function(pushpermissionstatus) { ...
PushManager.permissionState() - Web APIs
syntax pushmanager.permissionstate(options).then(function(pushmessagingstate) { ...
PushManager - Web APIs
} 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 xmlhttprequest.
PushMessageData - Web APIs
messages received through the push api are sent encrypted by push services and then automatically decrypted by browsers before they are made accessible through the methods of the pushmessagedata interface.
PushSubscription.endpoint - Web APIs
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 comment push apith...
PushSubscription.toJSON() - Web APIs
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.
RTCCertificate - Web APIs
the interface of the the webrtc api provides an object represents a certificate that an rtcpeerconnection uses to authenticate.
RTCConfiguration.bundlePolicy - Web APIs
any other transports that were used during negotiation are then closed.
RTCConfiguration.certificates - Web APIs
the rtcconfiguration dictionary's optional certificates property is an array of rtccertificate objects providing the security certificates available for use when authenticating duing the connection process.
RTCConfiguration.iceServers - Web APIs
the first one, stun:stun.services.mozilla.com, requires authentication, so the username and password are provided.
RTCDTMFSender.toneBuffer - Web APIs
in this example, we would send "*" to request access to the vm system, then, after a pause, send a "1" to start playback of voicemail messages, then after a pause, dial "5555" as a pin number to open the messages.
RTCDataChannel: bufferedamountlow event - Web APIs
then a listener is created for bufferedamountlow to refill the incoming data buffer any time its contents fall below 65536 bytes.
RTCDataChannel.label - Web APIs
example this sample creates a data channel on an rtcpeerconnection, then, some time later, sets the content of a ui element to display the channel's name.
RTCDataChannel.onclose - Web APIs
example in this sample from a hypothetical instant messaging client, a data channel is created, then handlers for the open and close events are set up to enable and disable user interface objects based on the state of the channel.
RTCDataChannel.onmessage - Web APIs
the new elements are then attached to the end of the document.
RTCDataChannel.onopen - Web APIs
it then establishes an open event handler which updates some user interface elements to prepare them for being used to send messages over the data channel.
RTCDataChannel.protocol - Web APIs
if no protocol was specified when the data channel was created, then this property's value is "" (the empty string).
RTCDataChannel - Web APIs
if no protocol was specified when the data channel was created, then this property's value is "" (the empty string).readystate read only the read-only rtcdatachannel property readystate returns an enum of type rtcdatachannelstate which indicates the state of the data channel's underlying data connection.reliable read only the read-only rtcdatachannel property reliable indicates whether or not the data channel is reliable.stream read only the deprecated (...
RTCError - Web APIs
WebAPIRTCError
this message is then displayed using a function called showmyalertmessage(), which stands in for whatever output mechanism this code might use.
RTCErrorEvent.error - Web APIs
this message is then displayed using a function called showmyalertmessage(), which stands in for whatever output mechanism this code might use.
RTCIceCandidate.candidate - Web APIs
the new candidate is then passed into rtcpeerconnection.addicecandidate() to add the candidate to the list of candidates for webrtc to consider using for the connection being established.
RTCIceCandidate.relatedAddress - Web APIs
example in this example, the candidate's type is checked, and then debugging output is presented, based on the candidate type, including the candidate's ip and relatedaddress.
RTCIceCandidate.relatedPort - Web APIs
example in this example, the candidate's type is checked, and then debugging output is presented, based on the candidate type, including the candidate's type, address (ip and port), and related address (relatedaddress and relatedport).
RTCIceCandidate. toJSON() - Web APIs
you can then get a stringified version of the object by calling stringify() on the returned object.
RTCIceCandidate - Web APIs
webrtc then uses that candidate's details to initiate the connection.
RTCIceCandidatePair.local - Web APIs
example this one-line example simply obtains the current candidate pair and then from that gets the local candidate.
RTCIceCandidatePair.remote - Web APIs
example this one-line example simply obtains the current candidate pair and then from that gets the remote candidate.
RTCIceCandidatePairStats - Web APIs
if it is, then we know that rtcstats is in fact an rtcicecandidatepairstats object.
RTCIceCandidateStats.deleted - Web APIs
window.setinterval(function() { mypeerconnection.getstats(null).then(stats => { let statsoutput = ""; stats.foreach(report => { if ((stats.type === "local-candidate" || stats.type === "remote.candidate") && !stats.deleted) { statsoutput += `<h2>report: ${report.type}</h3>\n<strong>id:</strong> ${report.id}<br>\n` + `<strong>timestamp:</strong> ${report.timestamp}<br>\n`; // now the statistics for this report; ...
RTCIceCandidateStats.networkType - Web APIs
window.setinterval(function() { mypeerconnection.getstats(null).then(stats => { let statsoutput = ""; stats.foreach(report => { if ((stats.type === "local-candidate" || stats.type === "remote.candidate") && stats.networktype === "cellular") { statsoutput += `<h2>report: ${report.type}</h3>\n<strong>id:</strong> ${report.id}<br>\n` + `<strong>timestamp:</strong> ${report.timestamp}<br>\n`; // now the statistics...
RTCIceCandidateStats - Web APIs
this function is then called for rtcstats objects whose type is local-candidate, indicating that the object is in fact an rtcicecandidatestats with information about a local ice candidate.
RTCIceServer.username - Web APIs
the rtciceserver dictionary's username property is a string which specifies the username to use when authenticating with the ice server being described.
RTCIceTransport.getLocalCandidates() - Web APIs
example this simple example gets the local candidate list from the rtcicetransport for the first rtcrtpsender on the rtcpeerconnection, then outputs to the console all of the candidates in the list.
RTCIceTransport.getRemoteCandidates() - Web APIs
example this simple example gets the remote candidate list from the rtcicetransport for the first rtcrtpsender on the rtcpeerconnection, then outputs to the console all of the candidates in the list.
RTCIdentityErrorEvent - Web APIs
rtcidentityerrorevent.loginurl read only is a domstring giving the url where the user can complete the authentication.
RTCPeerConnection.getConfiguration() - Web APIs
let configuration = mypeerconnection.getconfiguration(); if ((configuration.certificates != undefined) && (!configuration.certificates.length)) { rtcpeerconnection.generatecertificate({ name: 'rsassa-pkcs1-v1_5', hash: 'sha-256', moduluslength: 2048, publicexponent: new uint8array([1, 0, 1]) }).then(function(cert) { configuration.certificates = [cert]; mypeerconnection.setconfiguration(configuration); }); } this example fetches the current configuration of the rtcpeerconnection, then looks to see if it has any certificates set by examining whether or not (a) the configuration has a value for certificates, and (b) whether its length is zero.
RTCPeerConnection: iceconnectionstatechange event - Web APIs
usage notes a successful connection attempt will typically involve the state starting at new, then transitioning through checking, then connected, and finally completed.
RTCPeerConnection.onaddstream - Web APIs
example this code, based on an older version of our signaling and video calling sample, responds to addstream events by setting the video source for a <video> element to the stream specified in the event, and then enabling a "hang up" button in the app's user interface.
RTCPeerConnection.remoteDescription - Web APIs
the returned value typically reflects a remote description which has been received over the signaling server (as either an offer or an answer) and then put into effect by your code calling rtcpeerconnection.setremotedescription() in response.
RTCPeerConnection.restartIce() - Web APIs
pc.addeventlistener("iceconnectionstatechange", event => { if (pc.iceconnectionstate === "failed") { /* possibly reconfigure the connection in some way here */ /* then request ice restart */ pc.restartice(); } }); with this code in place, a transition to the failed state during ice negotiation will cause a negotiationneeded event to be fired, in response to which your code should renegotiate as usual.
RTCPeerConnection: track event - Web APIs
examples this example shows code that creates a new rtcpeerconnection, then adds a new track event handler.
RTCPeerConnectionIceErrorEvent.address - Web APIs
examples this example creates a handler for icecandidateerror events which creates human readable messages describing the local network interface for the connection as well as the ice server that was being used to try to open the connection, then calls a function to display those as well as the event's errortext property's contents.
RTCRtpReceiver.getStats() - Web APIs
receiver.getstats().then(function(stats) { document.getelementbyid("lostpackets").innertext = stats.packetslost; }); specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcrtpreceiver.getstats()' in that specification.
RTCRtpSender.getStats() - Web APIs
sender.getstats().then(function(stats) { document.getelementbyid("currentrtt").innertext = stats.roundtriptime; }); specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcrtpsender.getstats()' in that specification.
RTCRtpSender.replaceTrack() - Web APIs
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.replacetrack(videotrack); }); }) .catch(function(err) { console.error('error happens:', err); }); specifications ...
RTCRtpTransceiver.currentDirection - Web APIs
[1] to determine if a sender has at least one active encoding, the user agent gets its parameters using rtcrtpsender.getparameters(), then looks at the parameters' encodings property; if any of the listed encodings has its active property set to true, the sender has an active encoding.
RTCRtpTransceiver.direction - Web APIs
[1] to determine if a sender has at least one active encoding, the user agent gets its parameters using rtcrtpsender.getparameters(), then looks at the parameters' encodings property; if any of the listed encodings has its active property set to true, the sender has an active encoding.
RTCRtpTransceiver.setCodecPreferences() - Web APIs
a good approach to setting codec preferences is to first get the list of codecs that are actually supported, then modify that list to match what you want.
RTCRtpTransceiver.stop() - Web APIs
the receiver then stops receiving media; the receiver's track is stopped, and the transceiver's direction is changed to stopped, and renegotiation is triggered by sending a negotiationneeded event to the rtcpeerconnection.
RTCRtpTransceiverDirection - Web APIs
[1] to determine if a sender has at least one active encoding, the user agent gets its parameters using rtcrtpsender.getparameters(), then looks at the parameters' encodings property; if any of the listed encodings has its active property set to true, the sender has an active encoding.
Range() - Web APIs
WebAPIRangeRange
we then select the range using window.getselection() and selection.addrange().
Range.comparePoint() - Web APIs
if the reference node is a node of type text, comment, or cdatasection, then offset is the number of characters from the start of reference node.
Range.endOffset - Web APIs
WebAPIRangeendOffset
if the endcontainer is a node of type text, comment, or cdatasection, then the offset is the number of characters from the start of the endcontainer to the boundary point of the range.
Range.extractContents() - Web APIs
select one or more item, and then click "swap" to move them to the opposite container.
Range.setEnd() - Web APIs
WebAPIRangesetEnd
usage notes if the endnode is a node of type text, comment, or cdatasection, then endoffset is the number of characters from the start of endnode.
Range.startOffset - Web APIs
WebAPIRangestartOffset
if the startcontainer is a node of type text, comment, or cdatasection, then the offset is the number of characters from the start of the startcontainer to the boundary point of the range.
ReadableStream.ReadableStream() - Web APIs
if pull() returns a promise, then it won't be called again until that promise fulfills; if the promise rejects, the stream will become errored.
ReadableStream - Web APIs
fetch("https://www.example.org/").then((response) => { const reader = response.body.getreader(); const stream = new readablestream({ start(controller) { // the following function handles each data chunk function push() { // "done" is a boolean and value a "uint8array" reader.read().then(({ done, value }) => { // is there no more data to read?
ReadableStreamDefaultReader.closed - Web APIs
reader.closed.then(() => { console.log('reader closed'); }) specifications specification status comment streamsthe definition of 'closed' in that specification.
ReadableStreamDefaultReader - Web APIs
fetch("https://www.example.org/").then((response) => { const reader = response.body.getreader(); const stream = new readablestream({ start(controller) { // the following function handles each data chunk function push() { // "done" is a boolean and value a "uint8array" return reader.read().then(({ done, value }) => { // is there no more data to read?
RelativeOrientationSensor - Web APIs
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
examples in our deprecation_report.html example, we create a simple reporting observer to observe usage of deprecated features on our web page: let options = { types: ['deprecation'], buffered: true } let observer = new reportingobserver(function(reports, observer) { reportbtn.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( cons...
Request.clone() - Web APIs
WebAPIRequestclone
example in the following snippet, we create a new request using the request.request() constructor (for an image file in the same directory as the script), then clone the request.
Request.context - Web APIs
WebAPIRequestcontext
example in the following snippet, we create a new request using the request.request() constructor (for an image file in the same directory as the script), then save the request context in a variable: var myrequest = new request('flowers.jpg'); var mycontext = myrequest.context; // returns the empty string by default ...
Request.credentials - Web APIs
example in the following snippet, we create a new request using the request.request() constructor (for an image file in the same directory as the script), then save the request credentials in a variable: var myrequest = new request('flowers.jpg'); var mycred = myrequest.credentials; // returns "same-origin" by default specifications specification status comment fetchthe definition of 'credentials' in that specification.
Request.destination - Web APIs
example in the following snippet, we create a new request using the request() constructor (for an image file in the same directory as the script), then save the request's destination: var myrequest = new request('flowers.jpg'); var mydestination = myrequest.destination; // returns the empty string by default specifications specification status comment fetchthe definition of 'destination' in that specification.
Request.headers - Web APIs
WebAPIRequestheaders
example in the following snippet, we create a new request using the request.request() constructor (for an image file in the same directory as the script), then save the request headers in a variable: var myrequest = new request('flowers.jpg'); var myheaders = myrequest.headers; // headers {} to add a header to the headers object we use headers.append; we then create a new request along with a 2nd init parameter, passing headers in as an init option: var myheaders = new headers(); myheaders.append('content-type', 'image/jpeg'); var myinit = { method: 'get', headers: myheaders, mode: 'cors', cache: 'def...
Request.integrity - Web APIs
WebAPIRequestintegrity
example in the following snippet, we create a new request using the request.request() constructor (for an image file in the same directory as the script), then save the request integrity value in a variable: var myrequest = new request('flowers.jpg'); var myintegrity = myrequest.integrity; specifications specification status comment fetchthe definition of 'integrity' in that specification.
Request.method - Web APIs
WebAPIRequestmethod
example in the following snippet, we create a new request using the request.request() constructor (for an image file in the same directory as the script), then save the method of the request in a variable: var myrequest = new request('flowers.jpg'); var mymethod = myrequest.method; // get specifications specification status comment fetchthe definition of 'method' in that specification.
Request.mode - Web APIs
WebAPIRequestmode
example in the following snippet, we create a new request using the request.request() constructor (for an image file in the same directory as the script), then save the request mode in a variable: var myrequest = new request('flowers.jpg'); var mymode = myrequest.mode; // returns "cors" by default specifications specification status comment fetchthe definition of 'mode' in that specification.
Request.redirect - Web APIs
WebAPIRequestredirect
example in the following snippet, we create a new request using the request.request() constructor (for an image file in the same directory as the script), then save the request redirect value in a variable: var myrequest = new request('flowers.jpg'); var mycred = myrequest.redirect; specifications specification status comment fetchthe definition of 'redirect' in that specification.
Request.referrer - Web APIs
WebAPIRequestreferrer
example in the following snippet, we create a new request using the request.request() constructor (for an image file in the same directory as the script), then save the request referrer in a variable: var myrequest = new request('flowers.jpg'); var myreferrer = myrequest.referrer; // returns "about:client" by default specifications specification status comment fetchthe definition of 'referrer' in that specification.
Request.referrerPolicy - Web APIs
example in the following snippet, we create a new request using the request.request() constructor (for an image file in the same directory as the script), then save the request referrer policy in a variable: var myrequest = new request('flowers.jpg'); var myreferrer = myrequest.referrerpolicy; // returns "" by default specifications specification status comment fetchthe definition of 'referrerpolicy' in that specification.
Request.url - Web APIs
WebAPIRequesturl
example in the following snippet, we create a new request using the request.request() constructor (for an image file in the same directory as the script), then save the url of the request in a variable: var myrequest = new request('flowers.jpg'); var myurl = myrequest.url; // "http://mdn.github.io/fetch-examples/fetch-request/flowers.jpg" specifications specification status comment fetchthe definition of 'url' in that specification.
Response.useFinalURL - Web APIs
example consider a script residing in page index.html: fetch('/test').then((r) => console.log(r.url)) test.html is being controlled by the service worker sw.js: onfetch = (e) => { e.respondwith(fetch('/page2').then((r) => { r.usefinalurl = true; return r; }) } the output will be /page2 and not /test in index.html, since setting the usefinalurl means that the response's url is not set to request's url.
Response - Web APIs
WebAPIResponse
const image = document.queryselector('.my-image'); fetch('flowers.jpg').then(function(response) { return response.blob(); }).then(function(blob) { const objecturl = url.createobjecturl(blob); image.src = objecturl; }); you can also use the response.response() constructor to create your own custom response object: const response = new response(); specifications specification status comment fetchthe definition of 'response' in that spec...
format - Web APIs
if the font is in one of the formats listed in css2([css2], section15.3.5), then its value is the corresponding <string> parameter of the font.
SVGAnimatedAngle - Web APIs
if the given attribute is not currently being animated, then the svgangle will have the same contents as baseval.
SVGAnimatedLengthList - Web APIs
if the given attribute is not currently being animated, then the svglengthlist will have the same contents as baseval.
SVGAnimatedNumberList - Web APIs
if the given attribute is not currently being animated, then the svgnumberlist will have the same contents as baseval.
SVGAnimatedPathData - Web APIs
thus, if the d attribute has an "absolute moveto (m)" and an "absolute arcto (a)" command, then pathseglist will have two entries: a svg_pathseg_moveto_abs and a svg_pathseg_arc_abs.
SVGAnimatedPreserveAspectRatio - Web APIs
if the given attribute is not currently being animated, then the svgpreserveaspectratio will have the same contents as baseval.
SVGAnimatedRect - Web APIs
if the given attribute is not currently being animated, then the svgrect will have the same contents as baseval.
SVGAnimatedString.animVal - Web APIs
if the given attribute or property is not currently being animated, then it contains the same value as baseval the animval property is a read only property.
SVGAnimatedTransformList - Web APIs
if the given attribute is not currently being animated, then the svgtransformlist will have the same contents as baseval.
SVGDocument - Web APIs
svg document interface when an "svg" element is embedded inline as a component of a document from another namespace, such as when an "svg" element is embedded inline within an xhtml document, then an svgdocument object will not exist; instead, the root object in the document object hierarchy will be a document object of a different type, such as an htmldocument object.
SVGLength - Web APIs
WebAPISVGLength
for example, if the original value were "0.5cm" and the method was invoked to convert to millimeters, then the unittype would be changed to svg_lengthtype_mm, valueinspecifiedunits would be changed to the numeric value 5 and valueasstring would be changed to "5mm".
SVGPoint - Web APIs
WebAPISVGPoint
example // create an svgpoint in the user coordinate system let s = document.getelementbyid("svg-elementid").createsvgpoint(); // then, set the x and y values of the returned svgpoint object // (which is the variable `s`) s.y = 10; s.x = 10; ...
SVGTransform - Web APIs
in case the matrix object is changed directly (i.e., without using the methods on the svgtransform interface itself) then the type of the svgtransform changes to svg_transform_matrix.
Screen Capture API - Web APIs
this stream can then be recorded or shared with others over the network.
Screen Wake Lock API - Web APIs
wakelock.release() .then(() => { wakelock = null; }); listening for wake lock release this example updates the ui if the wake lock has been released for any reason (such as navigating away from the active window/tab).
ScrollToOptions.behavior - Web APIs
when the form is submitted, an event handler is run that puts the entered values into a scrolltooptions dictionary, and then invokes the window.scrollto() method, passing the dictionary as a parameter: form.addeventlistener('submit', (e) => { e.preventdefault(); var scrolloptions = { left: leftinput.value, top: topinput.value, behavior: scrollinput.checked ?
ScrollToOptions.left - Web APIs
when the form is submitted, an event handler is run that puts the entered values into a scrolltooptions dictionary, and then invokes the window.scrollto() method, passing the dictionary as a parameter: form.addeventlistener('submit', (e) => { e.preventdefault(); var scrolloptions = { left: leftinput.value, top: topinput.value, behavior: scrollinput.checked ?
ScrollToOptions.top - Web APIs
when the form is submitted, an event handler is run that puts the entered values into a scrolltooptions dictionary, and then invokes the window.scrollto() method, passing the dictionary as a parameter: form.addeventlistener('submit', (e) => { e.preventdefault(); var scrolloptions = { left: leftinput.value, top: topinput.value, behavior: scrollinput.checked ?
ScrollToOptions - Web APIs
when the form is submitted, an event handler is run that puts the entered values into a scrolltooptions dictionary, and then invokes the window.scrollto() method, passing the dictionary as a parameter: form.addeventlistener('submit', (e) => { e.preventdefault(); var scrolloptions = { left: leftinput.value, top: topinput.value, behavior: scrollinput.checked ?
Selection - Web APIs
WebAPISelection
focus then moves to the editing host.
Sensor APIs - Web APIs
navigator.permissions.query({ name: 'accelerometer' }) .then(result => { if (result.state === 'denied') { console.log('permission to use accelerometer sensor is denied.'); return; } // use the sensor.
Using server-sent events - Web APIs
th addeventlistener(): evtsource.addeventlistener("ping", function(event) { const newelement = document.createelement("li"); const time = json.parse(event.data).time; newelement.innerhtml = "ping at " + time; eventlist.appendchild(newelement); }); this code is similar, except that it will be called automatically whenever the server sends a message with the event field set to "ping"; it then parses the json in the data field and outputs that information.
ServiceWorker.onstatechange - Web APIs
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
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.waiting; document.queryselector('#kind').textcontent = 'waiting'; } else if (r...
ServiceWorkerContainer: message event - Web APIs
bubbles no cancelable no interface messageevent event handler property onmessage examples in this example the service worker get the client's id from a fetch event and then sends it a message using client.postmessage: // in the service worker async function messageclient(clientid) { const client = await clients.get(clientid); client.postmessage('hi client!'); } addeventlistener('fetch', (event) => { messageclient(event.clientid); event.respondwith(() => { // ...
ServiceWorkerContainer.startMessages() - Web APIs
examples if('serviceworker' in navigator) { navigator.serviceworker .register('/sw.js') .then(function() { console.log('service worker registered'); }); } // ...
ServiceWorkerGlobalScope: contentdelete event - Web APIs
self.addeventlistener('contentdelete', event => { event.waituntil( caches.open('cache-name').then(cache => { return promise.all([ cache.delete(`/icon/${event.id}`), cache.delete(`/content/${event.id}`) ]) }) ); }); you can also set up the event handler using the serviceworkerglobalscope.ondelete property: self.oncontentdelete = (event) => { ...
ServiceWorkerGlobalScope: install event - Web APIs
bubbles no cancelable no interface extendableevent event handler property serviceworkerglobalscope.oninstall examples the following snippet shows how an install event handler can be used to populate a cache with a number of responses, which the service worker can then use to serve assets offline: this.addeventlistener('install', function(event) { event.waituntil( caches.open('v1').then(function(cache) { return cache.add( '/sw-test/', '/sw-test/index.html', '/sw-test/style.css', '/sw-test/app.js', '/sw-test/image-list.js', '/sw-test/star-wars-logo.jpg', '/sw-test/gallery/', '/sw-test...
ServiceWorkerGlobalScope.onactivate - Web APIs
then.addeventlistener('activate', function(event) { var cachewhitelist = ['v2']; event.waituntil( caches.foreach(function(cache, cachename) { if (cachewhitelist.indexof(cachename) == -1) { return caches.delete(cachename); } }) ); }); specifications specification status comment service workersthe definition of 'event handlers' in that specifi...
ServiceWorkerGlobalScope.oncontentdelete - Web APIs
self.addeventlistener('contentdelete', event => { event.waituntil( caches.open('cache-name').then(cache => { return promise.all([ cache.delete(`/icon/${event.id}`), cache.delete(`/content/${event.id}`) ]) }) ); }); specifications specification status comment unknownthe definition of 'contentdelete' in that specification.
ServiceWorkerGlobalScope.oninstall - Web APIs
}; examples the following snippet shows how an install event handler can be used to populate a cache with a number of responses, which the service worker can then use to serve assets offline: this.addeventlistener('install', function(event) { event.waituntil( caches.open('v1').then(function(cache) { return cache.add( '/sw-test/', '/sw-test/index.html', '/sw-test/style.css', '/sw-test/app.js', '/sw-test/image-list.js', '/sw-test/star-wars-logo.jpg', '/sw-test/gallery/', '/sw-test...
ServiceWorkerGlobalScope.onnotificationclick - Web APIs
}; example self.onnotificationclick = function(event) { console.log('on notification click: ', event.notification.tag); event.notification.close(); // this looks to see if the current is already open and // focuses if it is event.waituntil(clients.matchall({ type: "window" }).then(function(clientlist) { for (var i = 0; i < clientlist.length; i++) { var client = clientlist[i]; if (client.url == '/' && 'focus' in client) return client.focus(); } if (clients.openwindow) return clients.openwindow('/'); })); }; specifications specification status comment notifications apithe definition of 'onnotificationclick' i...
ServiceWorkerGlobalScope.skipWaiting() - Web APIs
syntax serviceworkerglobalscope.skipwaiting().then(function() { //do something }); returns a promise that immediately resolves with undefined.
ServiceWorkerMessageEvent.data - Web APIs
navigator.serviceworker.ready.then(function(reg) { ...
ServiceWorkerMessageEvent.lastEventId - Web APIs
navigator.serviceworker.ready.then(function(reg) { ...
ServiceWorkerMessageEvent.origin - Web APIs
navigator.serviceworker.ready.then(function(reg) { ...
ServiceWorkerMessageEvent.ports - Web APIs
navigator.serviceworker.ready.then(function(reg) { ...
ServiceWorkerMessageEvent.source - Web APIs
navigator.serviceworker.ready.then(function(reg) { ...
ServiceWorkerMessageEvent - Web APIs
navigator.serviceworker.ready.then(function(reg) { ...
ServiceWorkerRegistration.pushManager - Web APIs
} 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 be sent to it using, // for example, an x...
ServiceWorkerRegistration.update() - Web APIs
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...
ShadowRoot - Web APIs
from here we use standard dom traversal techniques to find the <style> element inside the shadow dom and then update the css found inside it: function updatestyle(elem) { var shadow = elem.shadowroot; var childnodes = shadow.childnodes; for(var i = 0; i < childnodes.length; i++) { if(childnodes[i].nodename === 'style') { childnodes[i].textcontent = 'div {' + 'width: ' + elem.getattribute('l') + 'px;' + 'height: ' + elem.getattribute('l') + 'px;' + 'b...
SharedWorker.port - Web APIs
WebAPISharedWorkerport
multiple scripts can then access the worker through a messageport object accessed using the sharedworker.port property — the port is started using its start() method: var myworker = new sharedworker('worker.js'); myworker.port.start(); for a full example, see our basic shared worker example (run shared worker.) specifications specification status comment html living standardthe definition of 'abstractworker.onerror' in that specification.
SourceBuffer.mode - Web APIs
WebAPISourceBuffermode
if timestamps already exist for the media segments, then the value will be set to segments; if they don't, then the value will be set to sequence.
SpeechRecognition.onnomatch - Web APIs
note: the onnomatch handler does not yet work properly in firefox — the speech recognition system always returns a positive match, and then guesses at what item in the grammar it found.
SpeechRecognition.onresult - Web APIs
// we then return the transcript property of the speechrecognitionalternative object var color = event.results[0][0].transcript; diagnostic.textcontent = 'result received: ' + color + '.'; bg.style.backgroundcolor = color; } specifications specification status comment web speech apithe definition of 'onresult' in that specification.
SpeechRecognition - Web APIs
after some other values have been defined, we then set it so that the recognition service starts when a click event occurs (see speechrecognition.start().) when a result has been successfully recognised, the speechrecognition.onresult handler fires, we extract the color that was spoken from the event object, and then set the background color of the <html> element to that color.
SpeechRecognitionAlternative.confidence - Web APIs
// we then return the transcript property of the speechrecognitionalternative object var color = event.results[0][0].transcript; diagnostic.textcontent = 'result received: ' + color + '.'; bg.style.backgroundcolor = color; console.log('confidence: ' + event.results[0][0].confidence); } specifications specification status comment web speech apithe definition of 'confidence' ...
SpeechRecognitionAlternative.transcript - Web APIs
// we then return the transcript property of the speechrecognitionalternative object var color = event.results[0][0].transcript; diagnostic.textcontent = 'result received: ' + color + '.'; bg.style.backgroundcolor = color; } specifications specification status comment web speech apithe definition of 'transcript' in that specification.
SpeechRecognitionAlternative - Web APIs
// we then return the transcript property of the speechrecognitionalternative object var color = event.results[0][0].transcript; diagnostic.textcontent = 'result received: ' + color + '.'; bg.style.backgroundcolor = color; } specifications specification status comment web speech apithe definition of 'speechrecognitionalternative' in that specification.
SpeechRecognitionEvent.emma - Web APIs
if the speech recognition system does not supply emma data then the user agent will return null.
SpeechRecognitionEvent.results - Web APIs
// we then return the transcript property of the speechrecognitionalternative object var color = event.results[0][0].transcript; diagnostic.textcontent = 'result received: ' + color + '.'; bg.style.backgroundcolor = color; } specifications specification status comment web speech apithe definition of 'results' in that specification.
SpeechRecognitionEvent - Web APIs
// we then return the transcript property of the speechrecognitionalternative object var color = event.results[0][0].transcript; diagnostic.textcontent = 'result received: ' + color + '.'; bg.style.backgroundcolor = color; } specifications specification status comment web speech apithe definition of 'speechrecognitionevent' in that specification.
SpeechRecognitionResult.item() - Web APIs
// we then return the transcript property of the speechrecognitionalternative object var color = event.results[0][0].transcript; diagnostic.textcontent = 'result received: ' + color + '.'; bg.style.backgroundcolor = color; } specifications specification status comment web speech apithe definition of 'item()' in that specification.
SpeechRecognitionResult.length - Web APIs
// we then return the transcript property of the speechrecognitionalternative object var color = event.results[0][0].transcript; diagnostic.textcontent = 'result received: ' + color + '.'; bg.style.backgroundcolor = color; console.log(event.results[0].length); } specifications specification status comment web speech apithe definition of 'length' in that specification.
SpeechRecognitionResultList.item() - Web APIs
// we then return the transcript property of the speechrecognitionalternative object var color = event.results[0][0].transcript; diagnostic.textcontent = 'result received: ' + color + '.'; bg.style.backgroundcolor = color; } specifications specification status comment web speech apithe definition of 'item()' in that specification.
SpeechRecognitionResultList.length - Web APIs
// we then return the transcript property of the speechrecognitionalternative object var color = event.results[0][0].transcript; diagnostic.textcontent = 'result received: ' + color + '.'; bg.style.backgroundcolor = color; console.log(event.results.length); } specifications specification status comment web speech apithe definition of 'length' in that specification.
SpeechRecognitionResultList - Web APIs
// we then return the transcript property of the speechrecognitionalternative object var color = event.results[0][0].transcript; diagnostic.textcontent = 'result received: ' + color + '.'; bg.style.backgroundcolor = color; } specifications specification status comment web speech apithe definition of 'speechrecognitionresultlist' in that specification.
SpeechSynthesis.paused - Web APIs
if utterances are then added to the utterance queue, they will not be spoken until the speechsynthesis object is unpaused, using speechsynthesis.resume().
SpeechSynthesis.speak() - Web APIs
when a form containing the text we want to speak is submitted, we (amongst other things) create a new utterance containing this text, then speak it by passing it into speak() as a parameter.
StereoPannerNode.pan - Web APIs
we then use an oninput event handler to change the value of the stereopannernode.pan parameter and update the pan value display when the slider is moved.
StereoPannerNode - Web APIs
we then use an oninput event handler to change the value of the stereopannernode.pan parameter and update the pan value display when the slider is moved.
Storage.clear() - Web APIs
WebAPIStorageclear
examples the following function creates three data entries in local storage, and then deletes them by using clear().
Storage.getItem() - Web APIs
WebAPIStoragegetItem
example the following function retrieves three data items from local storage, then uses them to set custom styles on a page.
Storage.length - Web APIs
WebAPIStoragelength
example the following function adds three data items to the local storage for the current domain, then returns the number of items in the storage: function populatestorage() { localstorage.setitem('bgcolor', 'yellow'); localstorage.setitem('font', 'helvetica'); localstorage.setitem('image', 'cats.png'); return localstorage.length; // should return 3 } note: for a real world example, see our web storage demo.
Storage.removeItem() - Web APIs
example the following function creates three data items inside local storage, then removes the image data item.
Storage - Web APIs
WebAPIStorage
if it doesn't, we run another function, populatestorage(), which uses storage.setitem() to set the item values, then runs setstyles().
StorageEstimate.quota - Web APIs
</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
</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
</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.
StorageQuota.queryInfo - Web APIs
syntax storagequota.queryinfo().then(function(storageinfo) { ...
StorageQuota.requestPersistentQuota - Web APIs
syntax storagequota.requestpersistentquota().then(function(storageinfo) { ...
Storage API - Web APIs
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.
Storage Access API - Web APIs
as an example, federated logins often require access to authentication cookies stored in first-party storage, and will require the user to sign in on each site separately (or completely break) if those cookies are not available.
SubmitEvent.submitter - Web APIs
please try again.", "ok"); } }); the handler id is obtained by using the submit event's submitter property to get the submit button, from which we then get the id.
SubmitEvent - Web APIs
please try again.", "ok"); } }); the handler id is obtained by using the submit event's submitter property to get the submit button, from which we then get the id.
SubtleCrypto.sign() - Web APIs
WebAPISubtleCryptosign
hmac the hmac algorithm calculates and verifies hash-based message authentication codes according to the fips 198-1 standard.
SyncManager.getTags() - Web APIs
syntax syncmanager.gettags().then(function(tags[]) { ...
SyncManager.register() - Web APIs
syntax syncmanager.register([options]).then(function(syncregistration) { ...
TextEncoder() - Web APIs
syntax encoder = new textencoder(); parameters textencoder() takes no parameters since firefox 48 and chrome 53 note: prior to firefox 48 and chrome 53, an encoding type label was accepted as a paramer to the textencoder object, since then both browers have removed support for any encoder type other than utf-8, to match the spec.
TextEncoder.prototype.encodeInto() - Web APIs
if not, reallocate the target buffer to written + (s.length - read) * 3 and then convert the rest by taking a substring of s starting from index read and a subbuffer of the target buffer starting from index written.
TextRange - Web APIs
WebAPITextRange
it is implemented in ie, then a textrange object can be created by element.createtextrange() or document.selection.createrange().
TextTrack.mode - Web APIs
WebAPITextTrackmode
the user can then navigate to the desired chapter, which begins at the cue's start position and ends at the cue's end position.
Touch() - Web APIs
WebAPITouchTouch
if the ellipse described by radiusx and radiusy is circular, then rotationangle has no effect.
Touch.clientX - Web APIs
WebAPITouchclientX
in this example, we assume the user initiates a touch on an element with an id of source, moves within the element or out of the element and then releases contact with the surface.
Touch.clientY - Web APIs
WebAPITouchclientY
in this example, we assume the user initiates a touch on an element with an id of source, moves within the element or out of the element and then releases contact with the surface.
Touch.pageX - Web APIs
WebAPITouchpageX
in following simple code snippet, we assume the user initiates one or more touch contacts on the source element, moves the touch points and then releases all contacts with the surface.
Touch.pageY - Web APIs
WebAPITouchpageY
in following simple code snippet, we assume the user initiates one or more touch contacts on the source element, moves the touch points and then releases all contacts with the surface.
Touch.radiusX - Web APIs
WebAPITouchradiusX
when the src element is touched, the element's width and height will be calculate based on the touch point's radiusx and radiusy values and the element will then be rotated using the touch point's rotationangle.
Touch.screenX - Web APIs
WebAPITouchscreenX
in following simple code snippet, we assume the user initiates multiple touch contacts on an element with an id of source and then releases contacts with the surface.
TouchEvent.touches - Web APIs
in following code snippet, the touchstart event handler checks the length of the touchevent.touches list to determine the number of touch points that were activated and then invokes different handlers depending on the number of touch points.
Using Touch Events - Web APIs
if an application supports two-finger swipe for any two touch points, it will use the changedtouches list in the touchmove event handler to determine if two touch points had moved and then implement the semantics of that gesture in an application-specific manner.
TrackEvent - Web APIs
st)) { trackkind = "text"; } else { trackkind = "unknown"; } switch(event.type) { case "addtrack": console.log("added a " + trackkind + " track"); break; case "removetrack": console.log("removed a " + trackkind + " track"); break; } } the event handler uses the javascript instanceof operator to determine which type of track the event occurred on, then outputs to console a message indicating what kind of track it is and whether it's being added to or removed from the element.
TransformStream - Web APIs
let responses = [ /* conjoined response tree */ ] let {readable, writable} = new transformstream responses.reduce( (a, res, i, arr) => a.then(() => res.pipeto(writable, {preventclose: (i+1) !== arr.length})), promise.resolve() ) note that this is not resilient to other influences.
URL.host - Web APIs
WebAPIURLhost
the host property of the url interface is a usvstring containing the host, that is the hostname, and then, if the port of the url is nonempty, a ':', followed by the port of the url.
URL - Web APIs
WebAPIURL
you can then easily read the parsed components of the url or make changes to the url.
URLUtilsReadOnly - Web APIs
these were then inherited by other interfaces, such as workerlocation.
USB.getDevices() - Web APIs
WebAPIUSBgetDevices
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.
USBEndpoint - Web APIs
this code identifies the correct endpoints by searching for the interface implementing the usb cdc interface class and then identifying the candidate endpoints based on their type and direction.
Using the User Timing API - Web APIs
however, if no argument is given, then all performance entries of type "mark" will be removed from the performance timeline.
VRStageParameters - Web APIs
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 transform: ' + stagepara...
ValidityState.stepMismatch - Web APIs
if the field is numeric in nature, including the date, month, week, time, datetime-local, number and range types and the step value is not any, if the value don't doesn't conform to the constraints set by the step and min values, then stepmismatch will be true.
VideoPlaybackQuality.corruptedVideoFrames - Web APIs
if a corrupted frame is dropped, then both corruptedvideoframes and droppedvideoframes are incremented.
VideoPlaybackQuality.creationTime - Web APIs
example this example calls getvideoplaybackquality() to obtain a videoplaybackquality object, then determines what percentage of frames have been lost by either corruption or being dropped.
VideoPlaybackQuality.totalVideoFrames - Web APIs
example this example calls getvideoplaybackquality() to obtain a videoplaybackquality object, then determines what percentage of frames have been lost by either corruption or being dropped.
VideoTrack - Web APIs
usage notes to get a videotrack for a given media element, use the element's videotracks property, which returns a videotracklist object from which you can get the individual tracks contained in the media: var el = document.queryselector("video"); var tracks = el.videotracks; you can then access the media's individual tracks using either array syntax or functions such as foreach().
WakeLockSentinel.release() - Web APIs
syntax wakelocksentinel.release().then(...); parameters none.
WakeLockSentinel.type - Web APIs
examples this example shows an asynchronous function that acquires a wakelocksentinel, then logs the type to the console.
WakeLockSentinel - Web APIs
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('click', () => { if (wakelock !== null) { wakelock.release() .then(() => { wakelock = null; }) } }) specifications specification status comment screen wake lock apithe definition of 'wakelocksentinel' in that specification.
WebGLProgram - Web APIs
use the program gl.useprogram(program); // bind existing attribute data gl.bindbuffer(gl.array_buffer, buffer); gl.enablevertexattribarray(attributelocation); gl.vertexattribpointer(attributelocation, 3, gl.float, false, 0, 0); // draw a single triangle gl.drawarrays(gl.triangles, 0, 3); deleting the program if there is an error linking the program or you wish to delete an existing program, then it is as simple as running webglrenderingcontext.deleteprogram().
WebGLRenderingContext.createProgram() - Web APIs
these are then linked into a usable program..
WebGLRenderingContext.createShader() - Web APIs
the webglrenderingcontext method createshader() of the webgl api creates a webglshader that can then be configured further using webglrenderingcontext.shadersource() and webglrenderingcontext.compileshader().
WebGLRenderingContext.deleteShader() - Web APIs
it will then be deleted whenever the shader is no longer in use.
WebGLRenderingContext - Web APIs
this can be used to start an application using standard 2d presentation, then transition to using a vr or ar mode later.
WebGLShader - Web APIs
description to create a webglshader use webglrenderingcontext.createshader, then hook up the glsl source code using webglrenderingcontext.shadersource(), and finally invoke webglrenderingcontext.compileshader() to finish and compile the shader.
Clearing with colors - Web APIs
set up the rendering context and then just clear it solid green.
Color masking - Web APIs
it allows us to setup webgl in a single initialization phase, and then just execute drawing commands for each frame.
Scissor animation - Web APIs
for each square, we set its color once, and then update only its position every frame.
WebGL constants - Web APIs
you can then query getshaderinfolog to find the exact error delete_status 0x8b80 passed to getshaderparamter to determine if a shader was deleted via deleteshader.
WebGL best practices - Web APIs
any calculation that can be done on the vertices and then just interpolated among fragments (via varyings) is a performance boon.
Writing a WebSocket server in C# - Web APIs
payload length: if this value is between 0 and 125, then it is the length of message.
The WebSocket API (WebSockets) - Web APIs
interfaces websocket the primary interface for connecting to a websocket server and then sending and receiving data on the connection.
Targeting and hit detection - Web APIs
these objects then serve a s.
Web Animations API Concepts - Web APIs
back then it was the only animation engine browsers had to worry about.
Web Animations API - Web APIs
these can then be played using the animation() constructor.
Web Audio API best practices - Web APIs
you have to request the file and wait for it to load (this section of our advanced article shows a good way to do it), but then you have access to the data directly, which means more precision, and more precise manipulation.
Functions and classes available to Web Workers - Web APIs
8 (8) no support no support no support formdata formdata objects provide a way to easily construct a set of key/value pairs representing form fields and their values, which can then be easily sent using the xmlhttprequest send() method.
Window.confirm() - Web APIs
WebAPIWindowconfirm
if a browser is ignoring in-page dialogs, then the returned value is always false.
Window.getComputedStyle() - Web APIs
examples in this example we style a <p> element, then retrieve those styles using getcomputedstyle(), and print them into the text content of the <p>.
Window.isSecureContext - Web APIs
if (window.issecurecontext) { // page is a secure context so service workers are now available navigator.serviceworker.register("/offline-worker.js").then(function () { ...
Window.onpaint - Web APIs
WebAPIWindowonpaint
this event occurs after the load event for a window, and reoccurs each time the window needs to be re-rendered, such as when another window obscures it and is then cleared away.
Obsolete features - Web APIs
personalbar obsolete since gecko 76 if this feature is on, then the new secondary window renders the personal toolbar in netscape 6.x, netscape 7.x and mozilla browser.
Window: pageshow event - Web APIs
try loading new pages into this tab, then navigating forward and backward through history, noting the events’ output to the log.</p> results specifications specification status comment html living standardthe definition of 'pageshow' in that specification.
Window: popstate event - Web APIs
if the browser has state information it wishes to store with the current-entry before navigating away from it, it then does so.
Window.requestFileSystem() - Web APIs
the returned filesystem is then available for use with the other file system apis.
Window.self - Web APIs
WebAPIWindowself
by using self, you can refer to the global scope in a way that will work not only in a window context (self will resolve to window.self) but also in a worker context (self will then resolve to workerglobalscope.self).
Window: transitionend event - Web APIs
in the case where a transition is removed before completion, such as if the transition-property is removed or display is set to none, then the event will not be generated.
Window - Web APIs
WebAPIWindow
if the resource fully fits in the window, then this event cannot be invoked globaleventhandlers.onwheel called when the mouse wheel is rotated around any axis globaleventhandlers.onselect called after text in an input field is selected globaleventhandlers.onselectionchange is an eventhandler representing the code to be called when the selectionchange event is raised.
WindowClient.focused - Web APIs
example self.addeventlistener('notificationclick', function(event) { console.log('on notification click: ', event.notification.tag); event.notification.close(); // this looks to see if the current is already open and // focuses if it is event.waituntil(clients.matchall({ type: "window" }).then(function(clientlist) { for (var i = 0; i < clientlist.length; i++) { var client = clientlist[i]; if (client.url == '/' && 'focus' in client) { if(!client.focused) return client.focus(); } } } if (clients.openwindow) return clients.openwindow('/'); })); }); specifications specification status comment service ...
WindowClient.visibilityState - Web APIs
example event.waituntil(clients.matchall({ type: "window" }).then(function(clientlist) { for (let i = 0; i < clientlist.length; i++) { let client = clientlist[i]; if (client.url == '/' && 'focus' in client) { if (client.visibilitystate === 'hidden') return client.focus(); } } } if (clients.openwindow) { return clients.openwindow('/'); } })); }); specifications specification status comment service wo...
WindowClient - Web APIs
example self.addeventlistener('notificationclick', function(event) { console.log('on notification click: ', event.notification.tag); event.notification.close(); // this looks to see if the current is already open and // focuses if it is event.waituntil(clients.matchall({ type: "window" }).then(function(clientlist) { for (var i = 0; i < clientlist.length; i++) { var client = clientlist[i]; if (client.url == '/' && 'focus' in client) { client.focus(); break; } } if (clients.openwindow) return clients.openwindow('/'); })); }); specifications specification status comment service workersthe definition of 'window...
WindowEventHandlers.onafterprint - Web APIs
the beforeprint and afterprint events allow pages to change their content before printing starts (perhaps to remove a banner, for example) and then revert those changes after printing has completed.
WindowEventHandlers.onbeforeprint - Web APIs
the beforeprint and afterprint events allow pages to change their content before printing starts (perhaps to remove a banner, for example) and then revert those changes after printing has completed.
WindowEventHandlers.onbeforeunload - Web APIs
o be set e.returnvalue = ''; }); guarantee the browser unload by removing the returnvalue property of the event window.addeventlistener('beforeunload', function (e) { // the absence of a returnvalue property on the event will guarantee the browser unload happens delete e['returnvalue']; }); notes when your page uses javascript to render content, the javascript may stop when leaving and then navigating back to the page.
WindowOrWorkerGlobalScope.atob() - Web APIs
you can use the btoa() method to encode and transmit data which may otherwise cause communication problems, then transmit it and use the atob() method to decode the data again.
WindowOrWorkerGlobalScope.btoa() - Web APIs
you can use this method to encode data which may otherwise cause communication problems, transmit it, then use the atob() method to decode the data again.
WindowOrWorkerGlobalScope.caches - Web APIs
this.addeventlistener('install', function(event) { event.waituntil( caches.open('v1').then(function(cache) { return cache.addall([ '/sw-test/', '/sw-test/index.html', '/sw-test/style.css', '/sw-test/app.js', '/sw-test/image-list.js', '/sw-test/star-wars-logo.jpg', '/sw-test/gallery/', '/sw-test/gallery/bountyhunters.jpg', '/sw-test/gallery/mylittlevader.jpg', '/sw-test/gallery/snowtroopers.jpg' ...
WindowOrWorkerGlobalScope.setInterval() - Web APIs
} function stoptextcolor() { clearinterval(nintervid); } </script> </head> <body onload="changecolor();"> <div id="my_box"> <p>hello world</p> </div> <button onclick="stoptextcolor();">stop</button> </body> </html> example 3: typewriter simulation the following example simulates typewriter by first clearing and then slowly typing content into the nodelist that matches a specified group of selectors.
WindowOrWorkerGlobalScope.setTimeout() - Web APIs
however, in the following: settimeout(myarray.mymethod, 1.0*1000); // prints "[object window]" after 1 second settimeout(myarray.mymethod, 1.5*1000, '1'); // prints "undefined" after 1.5 seconds the myarray.mymethod function is passed to settimeout, then when it's called, its this is not set so it defaults to the window object.
Worker.prototype.postMessage() - Web APIs
transfer example this example shows a firefox add-on that transfers an arraybuffer from the main thread to the chromeworker, and then the chromeworker transfers it back to the main thread.
Worker.terminate() - Web APIs
WebAPIWorkerterminate
example the following code snippet shows creation of a worker object using the worker() constructor, which is then immediately terminated.
Worker - Web APIs
WebAPIWorker
example the following code snippet creates a worker object using the worker() constructor, then uses the worker object: var myworker = new worker('/worker.js'); var first = document.queryselector('input#number1'); var second = document.queryselector('input#number2'); first.onchange = function() { myworker.postmessage([first.value, second.value]); console.log('message posted to worker'); } for a full example, see ourbasic dedicated worker example (run dedicated worker).
WorkerNavigator.permissions - Web APIs
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.
Worklet.addModule() - Web APIs
WebAPIWorkletaddModule
cookies and http authentification) when loading the module.
Worklet - Web APIs
WebAPIWorklet
instead, you write vertex shaders and fragment shaders using glsl code, and those shaders will then run on the graphics card.
WritableStreamDefaultWriter.abort() - Web APIs
// abort the stream when desired writer.abort.then((reason) => { console.log(reason); }) specifications specification status comment streamsthe definition of 'abort()' in that specification.
WritableStreamDefaultWriter.closed - Web APIs
// check if the stream is closed writer.closed.then(() => { console.log('writer closed'); }) specifications specification status comment streamsthe definition of 'closed' in that specification.
XDomainRequest - Web APIs
syntax var xdr = new xdomainrequest(); returns a new xdomainrequest object, which can then be used to make and manage these requests.
How to check the security state of an XMLHTTPRequest over SSL - Web APIs
atch(err) { alert(err); } } function test(url) { var req = cc["@mozilla.org/xmlextras/xmlhttprequest;1"].createinstance(); req.open('get', url, true); req.addeventlistener("error", function(e) { var error = createtcperrorfromfailedxhr(req); dumpsecurityinfo(req, error); }, false); req.onload = function(e) { dumpsecurityinfo(req); }; req.send(); } then test("https://addons.mozilla.org"); produced the following output in my console: connection status: succeeded security info: security state: secure common name (cn) = addons.mozilla.org organisation = mozilla corporation issuer = verisign, inc.
XMLHttpRequest.abort() - Web APIs
return value undefined example this example begins loading content from the mdn home page, then due to some condition, aborts the transfer by calling abort().
XMLHttpRequest.getAllResponseHeaders() - Web APIs
the code shows how to obtain the raw header string, as well as how to convert it into an array of individual headers and then how to take that array and create a mapping of header names to their values.
XMLHttpRequest.getResponseHeader() - Web APIs
if there are multiple response headers with the same name, then their values are returned as a single concatenated string, where each value is separated from the previous one by a pair of comma and space.
XMLHttpRequest.mozAnon - Web APIs
if true, the request will be sent without cookies or authentication headers.
XMLHttpRequest.mozBackgroundRequest - Web APIs
in cases in where a security dialog (such as authentication or a bad certificate notification) would normally be shown, this request fails instead.
XPathEvaluator.createExpression() - Web APIs
this method compiles an xpathexpression which can then be used for (repeated) evaluations of the xpath expression.
XPathResult.resultType - Web APIs
note that if the result is a node-set then unordered_node_iterator_type is always the resulting type.
XPathResult - Web APIs
note that if the result is a node-set then unordered_node_iterator_type is always the resulting type.
XRHandedness - Web APIs
assuming that's then valid, a function called myrenderhandobject() is called with the grip's pose and the value of handedness.
XRInputSource.handedness - Web APIs
assuming that's then valid, a function called myrenderhandobject() is called with the grip's pose and the value of handedness.
XRInputSource.targetRaySpace - Web APIs
to determine the position and orientation of the target ray while rendering a frame, pass it into the xrframe method getpose() method, then use the returned xrpose object's transform to gather the spatial information you need.
XRInputSource - Web APIs
the grip space's coordinate system can then be used to render objects so they appear to be held in the user's hand.
XRInputSourceArray.entries() - Web APIs
the xrinputsourcearray interface's entries() method returns a javascript iterator which can then be used to iterate over the key/value pairs in the input source array.
XRInputSourceArray.keys() - Web APIs
the keys() method in the xrinputsourcearray interface returns a javascript iterator which can then be used to iterate over the keys used to reference each item in the array of input sources.
XRInputSourceEvent.frame - Web APIs
then, if the result isn't null, the target ray pose's transform is passed into a function called mycheckandhandlehit() to see if the ray was pointing at anything when the select was triggered.
XRPermissionDescriptor.mode - Web APIs
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 status comment webxr device apithe definition of '...
XRPermissionDescriptor.optionalFeatures - Web APIs
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 status comment webxr device apithe definition of '...
XRPermissionDescriptor.requiredFeatures - Web APIs
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 status comment webxr device apithe definition of '...
XRPermissionDescriptor - Web APIs
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 status comment webxr device apithe definition of '...
XRPose.emulatedPosition - Web APIs
if its position is computed as an offset from another object (such as by basing it off the model representing the user's body), then this value is true.
XRPose.transform - Web APIs
WebAPIXRPosetransform
it determines the targeted object by passing the event frame's pose into a function called findtargetusingray(), then dispatches the event differently depending on the user's handedness; this is done by comparing the value of the xrinputsource property handedness to a value in the variable user.handedness.
XRReferenceSpace - Web APIs
xrsession.requestreferencespace("local").then((refspace) => { xrreferencespace = refspace; /* ...
XRRigidTransform.inverse - Web APIs
the inverse's matrix is multiplied by the object's matrix to get the model view matrix, which is then passed into the shader program by setting a uniform to contain that information.
XRRigidTransform.position - Web APIs
ce which can be used to place an object at eye level (assuming eye level is 1.5 meters): function onsessionstarted(xrsession) { xrsession.addeventlistener("end", onsessionended); gl = initgraphics(xrsession); let gllayer = new xrwebgllayer(xrsession, gl); xrsession.updaterenderstate({ baselayer: gllayer }); if (immersivesession) { xrsession.requestreferencespace("bounded-floor").then((refspace) => { refspacecreated(refspace); }).catch(() => { session.requestreferencespace("local-floor").then(refspacecreated); }); } else { session.requestreferencespace("viewer").then(refspacecreated); } } function refspacecreated(refspace) { if (immersivesession) { xrreferencespace = refspace; } else { xrreferencespace = refspace.getoffsetreferencespace...
XRSession.cancelAnimationFrame() - Web APIs
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 (xrsession) { stopbutton.onclick = stopxr; requesthandle = xrsession.requestanimationframe(framecallback); ...
XRSession.inputSources - Web APIs
you can then either get the value of inputsources to examine the list, or you can refer to a reference to the list that you've previously saved.
XRSession.onsqueezeend - Web APIs
that's because (in this example, at least) the handler for the squeeze event has already dropped the object into its new location and then cleared the value of heldobject to indicate that the user is no longer holding anything.
XRSession: selectend event - Web APIs
if the target ray pose was fetched successfully, the code then uses the value of event property type to route control to an appropriate function to handle the event which arrived: for selectstart events, a mybegintracking() function is called with the target ray pose's matrix.
XRSession: selectstart event - Web APIs
if the target ray pose was fetched successfully, the code then uses the value of event property type to route control to an appropriate function to handle the event which arrived: for selectstart events, a mybegintracking() function is called with the target ray pose's matrix.
XRSession: squeezeend event - Web APIs
if the target ray pose was fetched successfully, the code then uses the value of event property type to route control to an appropriate function to handle the event which arrived: for squeezestart events, a mybegintracking() function is called with the target ray pose's matrix.
XRSession: squeezestart event - Web APIs
if the target ray pose was fetched successfully, the code then uses the value of event property type to route control to an appropriate function to handle the event which arrived: for squeezestart events, a mybegintracking() function is called with the target ray pose's matrix.
XRSession: visibilitychange event - Web APIs
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 dispatched to a function mysessionvi...
XRSystem: devicechange event - Web APIs
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 find out if there's a device available that can handle immersive vr presentations.
XRSystem: isSessionSupported() - Web APIs
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 = session; // onsessionstarted() not shown for reasons of bre...
XRViewerPose.views - Web APIs
if a valid pose is returned, the frame is rendered by clearing the backbuffer and then rendering each of the views in the pose; these are most likely the views for the left and right eyes.
XRViewerPose - Web APIs
if a valid pose is returned, the frame is rendered by clearing the backbuffer and then rendering each of the views in the pose; these are most likely the views for the left and right eyes.
XRWebGLLayer.framebuffer - Web APIs
examples this example gets the xrwebgllayer for a session and then passes its framebuffer into the webgl context's bindframebuffer() function.
XRWebGLLayer - Web APIs
examples binding the layer to a webgl context this snippet, taken from drawing a frame in movement, orientation, and motion: a webxr example, shows how the xrwebgllayer is obtained from the xrsession object's rendering state and is then bound as the current rendering webgl framebuffer by calling the webgl bindframebuffer() function.
XRWebGLLayerInit.depth - Web APIs
if this is true, then the depth buffer is either not present or is being ignored.
XRWebGLLayerInit.stencil - Web APIs
you can store values into each entry in the stencil bufer, then specify an operation that determines which stencil buffer values correspond to pixels which should be drawn to the screen during each frame.
XSLT Basic Example - Web APIs
the template that matches the root node outputs the article's title and then says to process all templates (via apply-templates) that match author nodes which are children of the authors node.
Introduction - Web APIs
each template matches (using xpath) a certain fragment of the input xml document and then applies the substitution part on that fragment to create the new resulting document.
XSLTProcessor - Web APIs
the xsltprocessor will then use the defaults specified in the xslt stylesheet.
ARIA live regions - Accessibility
one way around this would be to first clear the contents of the live region, and then inject the new content.
Using the alert role - Accessibility
when this role is added to an element, the browser will send out an accessible alert event to assistive technology products which can then notify the user about it.
Using the group role - Accessibility
when the role is added to an element, the browser will send out an accessible group event to assistive technology products which can then notify the user about it.
Using the log role - Accessibility
when this role is added to an element, the browser will send out an accessible log event to assistive technology products which can then notify the user about it.
Using the status role - Accessibility
when the role is added to an element, the browser will send out an accessible status event to assistive technology products which can then notify the user about it.
ARIA annotations - Accessibility
aria annotation roles and objects are currently exposed in: firefox from version 75 onwards, on windows and linux (on macos, we are first waiting for apple to define what safari will expose as apple-dialect attributes to voiceover, and will then follow suit.) chrome from version 81 onwards, currently behind the #enable-accessibility-expose-aria-annotations flag (go to chrome://flags to enable this.) unfortunately, you won’t be able to use any of these yet, as screenreader support is currently not there.
ARIA: timer role - Accessibility
one way around this would be to first clear the contents of the live region, and then inject the new content.
ARIA: alert role - Accessibility
if the user is expected to close the alert, then the alertdialog role should be used instead.
ARIA: cell role - Accessibility
keyboard interactions none required javascript features the first rule of aria use is if you can use a native feature with the semantics and behavior you require already built in, instead of repurposing an element and adding an aria role, state or property to make it accessible, then do so.
ARIA: document role - Accessibility
for example, if the document is collapsible, then the state and the value of aria-expanded must be maintained.
ARIA: feed role - Accessibility
for example, setting aria-busy to true during the update operation if needed, and then to false upon completion.
ARIA: figure role - Accessibility
you could add an id to an element containing content that describes the figure, and then reference that id inside an appropriate attribute on the figure to associate the figure with the label: <div role="figure" aria-labelledby="figure-1"> ...
ARIA: grid role - Accessibility
then the elements are rowheader and columnheader, respectively.
ARIA: rowgroup role - Accessibility
the first rule of aria use is if you can use a native feature with the semantics and behavior you require already built in, instead of re-purposing an element and adding an aria role, state or property to make it accessible, then do so.
ARIA: textbox role - Accessibility
description when an element has the textbox role, the browser sends an accessible textbox event to assistive technologies, which can then notify the user about it.
WAI-ARIA Roles - Accessibility
if the user is expected to close the alert, then the alertdialog role should be used instead.aria: application rolethe application role indicates to assistive technologies that an element and all of its children should be treated similar to a desktop application, and no traditional html interpretation techniques should be used.
Alerts - Accessibility
you can then shift-tab back and correct the error.
An overview of accessible web applications and widgets - Accessibility
a developer might be tempted to implement the "view" mode using a read-only text <input> element and setting its aria role to button, then switching to "edit" mode by making the element writable and removing the role attribute in "edit" mode (since <input> elements have their own role semantics).
Keyboard-navigable JavaScript widgets - Accessibility
there are two techniques for accomplishing this: roving tabindex: programmatically moving focus aria-activedescendant: managing a 'virtual' focus technique 1: roving tabindex setting the tabindex of the focused element to "0" ensures that if the user tabs away from the widget and then returns, the selected item within the group retains focus.
Understandable - Accessibility
your site should provide a glossary that contains definitions of such words/terms that you can then link to when they appear, or at the very least provide definitions somewhere in the surrounding text, or in a description list at the bottom of the page.
Understanding the Web Content Accessibility Guidelines - Accessibility
then step up to wcag 2.1.
Accessibility
accessibility (often abbreviated to a11y—as in "a" then 11 characters then "y") in web development means enabling as many people as possible to use web sites, even when those people's abilities are limited in some way.
-moz-context-properties - CSS: Cascading Style Sheets
note that if a color is set directly on the svg, but then the context color is also specified, the context color overrides the direct color.
:-moz-focusring - CSS: Cascading Style Sheets
if :-moz-focusring matches, then :focus also matches, but the converse is not always true: it depends on whether the user agent has focus ring drawing enabled and how the element was focused.
:-moz-only-whitespace - CSS: Cascading Style Sheets
examples html <div> </div> css :root { overflow: hidden; max-width: 100vw; max-height: 100vh; } div { background-color: #ccc; box-sizing: border-box; height: 100vh; min-height: 16px; min-height: 1rem; } div { border: 4px solid red; } :-moz-only-whitespace { border-color: lime; } result specifications briefly defined as :blank in selectors level 4, but then the functionality was merged into :empty and :blank redefined to mean empty <input>.
::placeholder - CSS: Cascading Style Sheets
an alternate approach to providing placeholder information is to include it outside of the input in close visual proximity, then use aria-describedby to programmatically associate the <input> with its hint.
:host() - CSS: Cascading Style Sheets
WebCSS:host()
the most obvious use of this is to put a class name only on certain custom element instances, and then include the relevant class selector as the function argument.
:left - CSS: Cascading Style Sheets
WebCSS:left
for example, if the first page has a major writing direction of left-to-right then it will be a :right page; if it has a major writing direction of right-to-left then it will be a :left page.
:right - CSS: Cascading Style Sheets
WebCSS:right
for example, if the first page has a major writing direction of left-to-right then it will be a :right page; if it has a major writing direction of right-to-left then it will be a :left page.
:state() - CSS: Cascading Style Sheets
WebCSS:state
examples fill in a simple example that nicely shows a typical usage of the selector, then perhaps some more complex examples.
:valid - CSS: Cascading Style Sheets
WebCSS:valid
we then absolutely position different generated content depending on whether the form's data is valid or invalid — a green check or a red cross, respectively.
fallback - CSS: Cascading Style Sheets
syntax /* keyword values */ fallback: lower-alpha; fallback: custom-gangnam-style; description if the specified fallback style is also unable to construct a representation, then its fallback style will be used.
negative - CSS: Cascading Style Sheets
if the negative descriptor is specified for other systems that don't support negative counter values, then the descriptor is ignored.
pad - CSS: Cascading Style Sheets
description if a marker representation is smaller than the specified pad length, then the marker will be padded with the specified pad symbol.
speak-as - CSS: Cascading Style Sheets
syntax /* keyword values */ speak-as: auto; speak-as: bullets; speak-as: numbers; speak-as: words; speak-as: spell-out; /* @counter-style name value */ speak-as: <counter-style-name>; values auto if the value of speak-as is specified as auto, then the effective value of speak-as will be determined based on the value of the system descriptor: if the value of system is alphabetic, the effective value of speak-as will be spell-out.
@document - CSS: Cascading Style Sheets
WebCSS@document
to match a literal period, you would first need to escape it using regular expression rules (to \.), then escape that string using css rules (to \\.).
font-style - CSS: Cascading Style Sheets
for a particular font family, authors can download various font faces which correspond to the different styles of the same font family, and then use the font-style descriptor to explicitly specify the font face's style.
font-weight - CSS: Cascading Style Sheets
for a particular font family, authors can download various font faces which correspond to the different styles of the same font family, and then use the font-weight descriptor to explicitly specify the font face's weights.
@font-face - CSS: Cascading Style Sheets
</body> </html> in this example, the user's local copy of "helvetica neue bold" is used; if the user does not have that font installed (two different names are tried), then the downloadable font named "mgopenmodernabold.ttf" is used instead: @font-face { font-family: myhelvetica; src: local("helvetica neue bold"), local("helveticaneue-bold"), url(mgopenmodernabold.ttf); font-weight: bold; } specifications specification status comment woff file format 2.0the definition of 'woff2 font format' in that specification.
@keyframes - CSS: Cascading Style Sheets
to use keyframes, create a @keyframes rule with a name that is then used by the animation-name property to match an animation to its keyframe declaration.
color - CSS: Cascading Style Sheets
WebCSS@mediacolor
for example, if a display uses 5 bits for blue and red and 6 bits for green, then the device is considered to use 5 bits per color component.
@namespace - CSS: Cascading Style Sheets
when a universal, type, or attribute selector is prefixed with a namespace prefix, then that selector only matches if the namespace and name of the element or attribute matches.
size - CSS: Cascading Style Sheets
WebCSS@pagesize
syntax /* keyword values for scalable size */ size: auto; size: portrait; size: landscape; /* <length> values */ /* 1 value: height = width */ size: 6in; /* 2 values: width then height */ size: 4in 6in; /* keyword values for absolute size */ size: a4; size: b5; size: jis-b4; size: letter; /* mixing size and orientation */ size: a4 portrait; values auto the user agent decides the size of the page.
At-rules - CSS: Cascading Style Sheets
WebCSSAt-rule
if the condition evaluates to true, then all of the statements within the group will be applied.
Box alignment for block, absolutely positioned and table layout - CSS: Cascading Style Sheets
if a content distribution method such as space-between, space-around or space-evenly is requested then the fallback alignment will be used, as the content is treated as a single alignment subject.
Box alignment in grid layout - CSS: Cascading Style Sheets
this means that you can set alignment for all of your grid items at once, then override any items that need a different alignment by applying the align-self or justify-self property to the rules for the individual grid items.
Box alignment in Flexbox - CSS: Cascading Style Sheets
the amount of space required to lay out the items is calculated, and the leftover space is then available for distribution.
Using CSS gradients - CSS: Cascading Style Sheets
we'll start by introducing linear gradients, then introduce features that are supported in all gradient types using linear gradients as the example, then move on to radial, conic and repeating gradients using linear gradients a linear gradient creates a band of colors that progress in a straight line.
Basic concepts of Logical Properties and Values - CSS: Cascading Style Sheets
there are then a group of properties which do not have a direct mapping in terms of existing physical properties.
Logical properties for margins, borders and padding - CSS: Cascading Style Sheets
if you were using a horizontal-tb writing mode with a right-to-left text direction then margin-inline-start would be the same as margin-right, and in a vertical writing mode it would be the same as using margin-top.
Logical properties for sizing - CSS: Cascading Style Sheets
if you were in a vertical writing mode then inline-size would be mapped to height.
CSS Motion Path - CSS: Cascading Style Sheets
you then animate it along that path by animating offset-distance, and can choose to rotate it at any point using offset-rotate.
Stacking with floated blocks - CSS: Cascading Style Sheets
this behavior can be shown with an added rule to the above list: the background and borders of the root element descendant non-positioned blocks, in order of appearance in the html floating blocks descendant non-positioned inline elements descendant positioned elements, in order of appearance in the html note: if an opacity value is applied to the non-positioned block (div #4), then something strange happens: the background and border of that block pops up above the floating blocks and the positioned blocks.
Stacking context example 1 - CSS: Cascading Style Sheets
then if div #4 is also assigned a positive z-index greater than div #2's z-index, it is rendered above all the other divs including div #2.
Stacking context example 3 - CSS: Cascading Style Sheets
if the three menu levels partially overlap, then managing stacking could become a problem.
Using the :target pseudo-class in selectors - CSS: Cascading Style Sheets
thus, to add a border to the #example fragment, we would write: #example:target { border: 1px solid black; } targeting all elements if the intent is to create a "blanket" style that will apply to all targeted elements, then the universal selector comes in handy: :target { color: red; } example in the following example, there are five links that point to elements in the same document.
Using CSS transforms - CSS: Cascading Style Sheets
you have to start by configuring the 3d space by giving it a perspective, then you have to configure how your 2d elements will behave in that space.
Using CSS transitions - CSS: Cascading Style Sheets
first, we set up the menu using html: <nav> <a href="#">home</a> <a href="#">about</a> <a href="#">contact us</a> <a href="#">links</a> </nav> then we build the css to implement the look and feel of our menu.
Card - CSS: Cascading Style Sheets
i then set the next track — which is where the content lives — to 1fr.
Center an element - CSS: Cascading Style Sheets
then set align-items to center to perform centering on the block axis, and justify-content to center to perform centering on the inline axis.
Column layouts - CSS: Cascading Style Sheets
lining items up in rows and columns — grid layout if what you want is a layout where items line up in rows and columns then you should choose css grid layout.
Grid wrapper - CSS: Cascading Style Sheets
center the content horizontally: .grid { max-width: 1200px; margin: 0 auto; // horizontally centers the container } /* remove the max-width and margins if the browser supports grid */ @supports (display: grid) { .grid { display: grid; /* other grid code goes here */ max-width: none; margin: 0; } } to “break out” a full-width item to the edge of the viewport you can then use this trick (courtesy of una kravets): .item { width: 100vw; margin-left: 50%; transform: translate3d(-50%, 0, 0); } this gives a good approximation of the layout, only without the benefit of being able to align items easily on an exact grid.
Pagination - CSS: Cascading Style Sheets
to ensure that the pagination is understandable by people using a screenreader, we mark the items up as a list inside a <nav> element, and then use css to display the layout visually as a row.
CSS Layout cookbook - CSS: Cascading Style Sheets
note: if you are new to css layout then you might first like to take a look at our css layout learning module, as this will give you the basic grounding you need to make use of the recipes here.
Testing media queries programmatically - CSS: Cascading Style Sheets
mediaquerylist.addlistener(handleorientationchange); this code creates the orientation-testing media query list, then adds an event listener to it.
Syntax - CSS: Cascading Style Sheets
WebCSSSyntax
at-rules that start with an at sign, '@' (u+0040 commercial at), followed by an identifier and then continuing up to the end of the statement, that is up to the next semi-colon (;) outside of a block, or the end of the next block.
Value definition syntax - CSS: Cascading Style Sheets
component value combinators brackets brackets enclose several entities, combinators, and multipliers, then transform them as a single component.
Actual value - CSS: Cascading Style Sheets
then, layout is calculated, resulting in the used value.
align-self - CSS: Cascading Style Sheets
if a flexbox item's cross-axis margin is auto, then align-self is ignored.
animation-timing-function - CSS: Cascading Style Sheets
• ease-in-out equal to cubic-bezier(0.42, 0, 0.58, 1.0), with the animating properties slowly transitioning, speeding up, and then slowing down again.
background-image - CSS: Cascading Style Sheets
the borders of the element are then drawn on top of them, and the background-color is drawn beneath them.
background-size - CSS: Cascading Style Sheets
if the image has no intrinsic proportions, then it's rendered at the size of the background positioning area.
<basic-shape> - CSS: Cascading Style Sheets
a <position> value in circle() or ellipse() is computed as a pair of offsets (horizontal then vertical) from the top left origin, each given as a combination of an absolute length and a percentage.
border-bottom-left-radius - CSS: Cascading Style Sheets
note: if the value of this property is not set in a border-radius shorthand property that is applied to the element after the border-bottom-left-radius css property, the value of this property is then reset to its initial value by the shorthand property.
border-bottom-right-radius - CSS: Cascading Style Sheets
note: if the value of this property is not set in a border-radius shorthand property that is applied to the element after the border-bottom-right-radius css property, the value of this property is then reset to its initial value by the shorthand property.
border-image-source - CSS: Cascading Style Sheets
the border-image-slice property is used to divide the source image into regions, which are then dynamically applied to the final border image.
border-top-left-radius - CSS: Cascading Style Sheets
note: if the value of this property is not set in a border-radius shorthand property that is applied to the element after the border-top-left-radius css property, the value of this property is then reset to its initial value by the shorthand property.
border-top-right-radius - CSS: Cascading Style Sheets
note: if the value of this property is not set in a border-radius shorthand property that is applied to the element after the border-top-right-radius css property, the value of this property is then reset to its initial value by the shorthand property.
bottom - CSS: Cascading Style Sheets
WebCSSbottom
this computed value is then handled as if it were a <length>, <percentage>, or the auto keyword.
box-align - CSS: Cascading Style Sheets
WebCSSbox-align
if the alignment is set using the element's align attribute, then the style is ignored.
box-direction - CSS: Cascading Style Sheets
if the direction is set using the element's dir attribute, then the style is ignored.
box-flex-group - CSS: Cascading Style Sheets
if the box would overflow after the preferred space of the children has been computed, then space is removed from flexible elements in a manner similar to that used when adding extra space.
box-pack - CSS: Cascading Style Sheets
WebCSSbox-pack
if the packing is set using the element's pack attribute, then the style is ignored.
break-after - CSS: Cascading Style Sheets
if we are inside a multicol container then it would force a column break, inside paged media (but not inside a multicol container) a page break.
break-before - CSS: Cascading Style Sheets
if we are inside a multicol container then it would force a column break, inside paged media (but not inside a multicol container) a page break.
Computed value - CSS: Cascading Style Sheets
for example, if an element has specified values font-size: 16px and padding-top: 2em, then the computed value of padding-top is 32px (double the font size).
contain - CSS: Cascading Style Sheets
WebCSScontain
and if a descendant overflows the containing element's bounds, then that descendant will be clipped to the containing element's border-box.
counter-set - CSS: Cascading Style Sheets
if there isn't currently a counter of the given name on the element, the element will create a new counter of the given name with a starting value of 0 (though it may then immediately set or increment that value to something different).
<display-inside> - CSS: Cascading Style Sheets
if its outer display type is inline or run-in, and it is participating in a block or inline formatting context, then it generates an inline box.
display - CSS: Cascading Style Sheets
WebCSSdisplay
if its outer display type is inline or run-in, and it is participating in a block or inline formatting context, then it generates an inline box.
element() - CSS: Cascading Style Sheets
WebCSSelement
a particularly useful scenario for using this would be to render an image in an html <canvas> element, then use that as a background.
flex-direction - CSS: Cascading Style Sheets
if the visual (css) order is important, then screen reader users will not have access to the correct reading order.
flex-grow - CSS: Cascading Style Sheets
WebCSSflex-grow
if all sibling items have the same flex grow factor, then all items will receive the same share of remaining space, otherwise it is distributed according to the ratio defined by the different flex grow factors.
font-stretch - CSS: Cascading Style Sheets
if the font does not provide a face that exactly matches the given value, then values less than 100% map to a narrower face, and values greater than or equal to 100% map to a wider face.
font-variant-caps - CSS: Cascading Style Sheets
in each case, if the font doesn't support the opentype value, then it synthesizes the glyphs.
font-weight - CSS: Cascading Style Sheets
fallback weights if the exact weight given is unavailable, then the following rule is used to determine the weight actually rendered: if the target weight given is between 400 and 500 inclusive: look for available weights between the target and 500, in ascending order.
font - CSS: Cascading Style Sheets
WebCSSfont
if font is specified as a shorthand for several font-related properties, then: it must include values for: <font-size> <font-family> it may optionally include values for: <font-style> <font-variant> <font-weight> <font-stretch> <line-height> font-style, font-variant and font-weight must precede font-size font-variant may only specify the values defined in css 2.1, that is normal and small-caps font-stretch may only be a single ke...
grid-area - CSS: Cascading Style Sheets
WebCSSgrid-area
the grid-area property can also be set to a <custom-ident> which acts as a name for the area, which can then be placed using grid-template-areas.
grid-auto-columns - CSS: Cascading Style Sheets
if max is smaller than min, then max is ignored and the function is treated as min.
grid-auto-rows - CSS: Cascading Style Sheets
if max is smaller than min, then max is ignored and the function is treated as min.
image-rendering - CSS: Cascading Style Sheets
for example, if the natural size of an image is 100×100px, but its actual dimensions are 200×200px (or 50×50px), then the image will be upscaled (or downscaled) using the algorithm specified by image-rendering.
Inheritance - CSS: Cascading Style Sheets
then it doubles the font size and applies a font-weight of "bold".
justify-self - CSS: Cascading Style Sheets
the second, third, and fourth grid items are then given different values of justify-self, to show how these override the justify-items value.
left - CSS: Cascading Style Sheets
WebCSSleft
this computed value is then handled as if it were a <length>, <percentage>, or the auto keyword.
<length> - CSS: Cascading Style Sheets
WebCSSlength
this is done by anchoring one of the units to a physical unit, and then defining the others relative to it.
linear-gradient() - CSS: Cascading Style Sheets
the following changes from red to yellow at the 30% mark, and then transitions from yellow to blue over 35% of the gradient linear-gradient(red 40%, yellow 30%, blue 65%); multi-position color stop are allowed.
list-style - CSS: Cascading Style Sheets
if list-style-type and list-style-image are both set, then list-style-type is used as a fallback if the image is unavailable.
mask-border-source - CSS: Cascading Style Sheets
the mask-border-slice property is used to divide the source image into regions, which are then dynamically applied to the final mask border.
mask - CSS: Cascading Style Sheets
WebCSSmask
if two <geometry-box> values are present, then the first sets mask-origin and the second sets mask-clip.
max-block-size - CSS: Cascading Style Sheets
that is, if the writing direction is horizontal, then max-block-size is equivalent to max-height; if the writing direction is vertical, max-block-size is the same as max-width.
offset-anchor - CSS: Cascading Style Sheets
the three are then given different background-color and offset-anchor values.
offset-distance - CSS: Cascading Style Sheets
if you want to animate an element along its full path, you would define its offset-path and then set up an animation that takes the offset-distance from 0% to 100%.
overscroll-behavior - CSS: Cascading Style Sheets
you may also have noticed that when you have a dialog box with scrolling content on top of a page of scrolling content, once the dialog box's scroll boundary is reached, the underlying page will then start to scroll — this is called scroll chaining.
paint-order - CSS: Cascading Style Sheets
syntax /* normal */ paint-order: normal; /* single values */ paint-order: stroke; /* draw the stroke first, then fill and markers */ paint-order: markers; /* draw the markers first, then fill and stroke */ /* multiple values */ paint-order: stroke fill; /* draw the stroke first, then the fill, then the markers */ paint-order: markers stroke fill; /* draw markers, then stroke, then fill */ if no value is specified, the default paint order is fill, stroke, markers.
place-self - CSS: Cascading Style Sheets
the second, third, and fourth grid items are then given different values of place-self, to show how these override the default placements.
<position> - CSS: Cascading Style Sheets
-axis; the y-axis defaults to 50% */ /* 2-value syntax */ keyword keyword /* a keyword for each direction (the order is irrelevant) */ keyword value /* a keyword for horizontal position, value for vertical position */ value keyword /* a value for horizontal position, keyword for vertical position */ value value /* a value for each direction (horizontal then vertical) */ /* 4-value syntax */ keyword value keyword value /* each value is an offset from the keyword that preceeds it */ formal syntax [ [ left | center | right ] || [ top | center | bottom ] | [ left | center | right | <length> | <percentage> ] [ top | center | bottom | <length> | <percentage> ]?
repeating-radial-gradient() - CSS: Cascading Style Sheets
browsers not supporting the syntax yet will see a gradient that goes from red to black and then from blue to green.
right - CSS: Cascading Style Sheets
WebCSSright
this computed value is then handled as if it were a <length>, <percentage>, or the auto keyword.
scroll-margin-block-end - CSS: Cascading Style Sheets
the scroll snap area is determined by taking the transformed border box, finding its rectangular bounding box (axis-aligned in the scroll container’s coordinate space), then adding the specified outsets.
scroll-margin-block-start - CSS: Cascading Style Sheets
the scroll snap area is determined by taking the transformed border box, finding its rectangular bounding box (axis-aligned in the scroll container’s coordinate space), then adding the specified outsets.
scroll-margin-block - CSS: Cascading Style Sheets
the scroll snap area is determined by taking the transformed border box, finding its rectangular bounding box (axis-aligned in the scroll container’s coordinate space), then adding the specified outsets.
scroll-margin-bottom - CSS: Cascading Style Sheets
the scroll snap area is determined by taking the transformed border box, finding its rectangular bounding box (axis-aligned in the scroll container’s coordinate space), then adding the specified outsets.
scroll-margin-inline-end - CSS: Cascading Style Sheets
the scroll snap area is determined by taking the transformed border box, finding its rectangular bounding box (axis-aligned in the scroll container’s coordinate space), then adding the specified outsets.
scroll-margin-inline-start - CSS: Cascading Style Sheets
the scroll snap area is determined by taking the transformed border box, finding its rectangular bounding box (axis-aligned in the scroll container’s coordinate space), then adding the specified outsets.
scroll-margin-inline - CSS: Cascading Style Sheets
the scroll snap area is determined by taking the transformed border box, finding its rectangular bounding box (axis-aligned in the scroll container’s coordinate space), then adding the specified outsets.
scroll-margin-left - CSS: Cascading Style Sheets
the scroll snap area is determined by taking the transformed border box, finding its rectangular bounding box (axis-aligned in the scroll container’s coordinate space), then adding the specified outsets.
scroll-margin-right - CSS: Cascading Style Sheets
the scroll snap area is determined by taking the transformed border box, finding its rectangular bounding box (axis-aligned in the scroll container’s coordinate space), then adding the specified outsets.
scroll-margin-top - CSS: Cascading Style Sheets
the scroll snap area is determined by taking the transformed border box, finding its rectangular bounding box (axis-aligned in the scroll container’s coordinate space), then adding the specified outsets.
scroll-margin - CSS: Cascading Style Sheets
the scroll snap area is determined by taking the transformed border box, finding its rectangular bounding box (axis-aligned in the scroll container’s coordinate space), then adding the specified outsets.
shape-image-threshold - CSS: Cascading Style Sheets
the 20% opacity threshold for treating gradient pixels as part of the shape is then established using shape-image-threshold with a value of 0.2.
symbols() - CSS: Cascading Style Sheets
WebCSSsymbols
fixed: the system cycles through the given values once, then falls back to arabic numerals.
text-decoration - CSS: Cascading Style Sheets
this means that if an element specifies a text decoration, then a child element can't remove the decoration.
text-size-adjust - CSS: Cascading Style Sheets
formal definition initial valueauto for smartphone browsers supporting inflation, none in other cases (and then not modifiable).applies toall elementsinheritedyespercentagesyes, refer to the corresponding size of the text fontcomputed valueas specifiedanimation typediscrete formal syntax none | auto | <percentage> examples basic disabling usage as hinted at above, on a properly designed responsive site the text-size-adjust behavior is not needed, so developers can elect to turn it off by specifying a ...
text-underline-position - CSS: Cascading Style Sheets
in the text with a vertical writing-mode set, we can then use values of left or right to make the underline appear on the left or right of the text as required.
top - CSS: Cascading Style Sheets
WebCSStop
this computed value is then handled as if it were a <length>, <percentage>, or the auto keyword.
transition-timing-function - CSS: Cascading Style Sheets
• ease-in-out equal to cubic-bezier(0.42, 0, 0.58, 1.0), starts transitioning slowly, speeds up, and then slows down again.
user-select - CSS: Cascading Style Sheets
all the content of the element shall be selected atomically: if a selection would contain part of the element, then the selection must contain the entire element including all its descendants.
math:max() - EXSLT
WebEXSLTmathmax
the maximum value is then the first node in the sorted list, converted into a number.
math:min() - EXSLT
WebEXSLTmathmin
the minimum value is then the first node in the sorted list, converted into a number.
set:leading() - EXSLT
WebEXSLTsetleading
if nodeset2 is empty, then the result is nodeset1.
set:trailing() - EXSLT
WebEXSLTsettrailing
if nodeset2 is empty, then the result is nodeset1.
EXSLT
exslt modules to use an exslt function, you need to declare the namespace the function is in, and then use the appropriate prefix when calling the function.
Event reference
mozbrowserusernameandpasswordrequired firefox os browser api-specific sent when an http authentication is requested.
Guide to Web APIs - Developer guides
WebGuideAPI
recordingnnavigation timingnetwork information api ppage visibility apipayment request apiperformance apiperformance timeline apipermissions apipointer eventspointer lock apiproximity events push api rresize observer apiresource timing apisserver sent eventsservice workers apistoragestorage access apistreams ttouch eventsuurl apivvibration apivisual viewport wweb animationsweb audio apiweb authentication apiweb crypto apiweb notificationsweb storage apiweb workers apiwebglwebrtcwebvttwebxr device apiwebsockets api ...
Live streaming web audio and video - Developer guides
of course, we then have the issue that we need to encode in three different formats.
Media buffering, seeking, and time ranges - Developer guides
if it doesn't then audio.seekable will be equivalent to audio.buffered, which will give a valid indication of the end of seekable media.
Creating a cross-browser video player - Developer guides
if the browser is currently in fullscreen mode, then it must be exited and vice versa.
Audio and video manipulation - Developer guides
selecting an audio source the web audio api can receive audio from a variety of sources, then process it and send it back out to an audiodestinationnode representing the output device to which the sound is sent after processing.
Overview of events and handlers - Developer guides
note that in this example, the code does not even name the event argument to the function because the code never needs to use the data structure describing the event; rather, the code merely needs to wait to run until after then event has happened.
Using device orientation with 3D transforms - Developer guides
is 180 (device flat on the back, top of the screen pointing 12:00), so the rotatez value should be alpha - 180 the y axis of the screen coordinate system is inverted, such that translatey(100px) moves an element 100px down, so the rotatey value should be -gamma finally, the order of the three different rotations is very important to accurately convert an orientation to a 3d rotation: rotatez, then rotatex and then rotatey.
Content categories - Developer guides
the script-supporting elements are: <script> <template> transparent content model if an element has a transparent content model, then its contents must be structured such that they would be valid html 5, even if the transparent element were removed and replaced by the child elements.
Rich-Text Editing in Mozilla - Developer guides
the function executed the requested command using execcommand() and then sets focus back to the editable document, as clicking on a button will set focus on the button itself, which breaks the editing flow.
Using HTML sections and outlines - Developer guides
if a significant percentage of your particular target audience is using internet explorer 8 or older, then you can follow the below instructions to make them behave as expected.
Localizations and character encodings - Developer guides
this has then had the effect that web authors have depended on heuristic detection being present, so firefox still has heuristic detection in these locales.
A hybrid approach - Developer guides
this hybrid approach centers around breaking down mobile development into its three goals, and then applying the best techniques available to tackle each goal individually.
Separate sites for mobile and desktop - Developer guides
if the functionality you would like to provide to your users on mobile devices is extremely different from that on a desktop, then using separate sites is simply likely to be the most practical choice.
HTML attribute: crossorigin - HTML: Hypertext Markup Language
the "anonymous" keyword means that there will be no exchange of user credentials via cookies, client-side ssl certificates or http authentication as described in the terminology section of the cors specification, unless it is in the same origin.
HTML attribute: min - HTML: Hypertext Markup Language
WebHTMLAttributesmin
we add a big red border around invalid inputs: input:invalid { border: solid red 3px; } then define an input with a minimum value of 7.2, omitting the step attribute, wherein it defaults to 1.
HTML attribute: readonly - HTML: Hypertext Markup Language
constraint validation if the element is readonly, then the element's value can not be updated by the user, and does not participate in constraint validation.
HTML attribute: required - HTML: Hypertext Markup Language
constraint validation if the element is required and the element's value is the empty string, then the element is suffering from valuemissing and the element will match the :invalid pseudo class.
HTML attribute: size - HTML: Hypertext Markup Language
WebHTMLAttributessize
for the input, if the type attribute is text or password then it's the number of characters.
HTML attribute: step - HTML: Hypertext Markup Language
WebHTMLAttributesstep
we add a big red border around invalid inputs: input:invalid { border: solid red 3px; } then define an input with a minimum value of 7.2, omitting the step attribute, wherein it defaults to 1.
HTML attribute reference - HTML: Hypertext Markup Language
if the element's type attribute is text or password then it's the number of characters.
DASH Adaptive Streaming for HTML 5 Video - HTML: Hypertext Markup Language
dash works via http, so as long as your http server supports byte range requests, and it's set up to serve .mpd files with mimetype="application/dash+xml", then you're all set.
<a>: The Anchor element - HTML: Hypertext Markup Language
WebHTMLElementa
onclick events anchor elements are often abused as fake buttons by setting their href to # or javascript:void(0) to prevent the page from refreshing, then listening for their click events .
<address>: The Contact Address element - HTML: Hypertext Markup Language
WebHTMLElementaddress
permitted parents any element that accepts flow content, but always excluding <address> elements (according to the logical principle of symmetry, if <address> tag, as a parent, can not have nested <address> element, then the same <address> content can not have <address> tag as its parent).
<applet>: The Embed Java Applet element - HTML: Hypertext Markup Language
WebHTMLElementapplet
permitted content zero or more <param> elements, then transparent.
<base>: The Document Base URL element - HTML: Hypertext Markup Language
WebHTMLElementbase
if the document has no <base> elements, then baseuri defaults to location.href.
<basefont> - HTML: Hypertext Markup Language
WebHTMLElementbasefont
with this set, the font's size can then be varied relative to the base size using the <font> element.
<bdi>: The Bidirectional Isolate element - HTML: Hypertext Markup Language
WebHTMLElementbdi
but if embedded-text is rtl, then - 1 will be treated as rtl text (because it consists of neutral and weak characters).
<blink>: The Blinking Text element (obsolete) - HTML: Hypertext Markup Language
WebHTMLElementblink
css polyfill if you really do need a polyfill, then you can use the following css polyfill.
<button>: The Button element - HTML: Hypertext Markup Language
WebHTMLElementbutton
assistive technology then uses the accessibility tree to navigate and manipulate page content.
<canvas>: The Graphics Canvas element - HTML: Hypertext Markup Language
WebHTMLElementcanvas
</canvas> javascript then in the javascript code, call htmlcanvaselement.getcontext() to get a drawing context and start drawing onto the canvas: const canvas = document.queryselector('canvas'); const ctx = canvas.getcontext('2d'); ctx.fillstyle = 'green'; ctx.fillrect(10, 10, 100, 100); result accessibility concerns alternative content the <canvas> element on its own is just a bitmap and does not provide informati...
<details>: The Details disclosure element - HTML: Hypertext Markup Language
WebHTMLElementdetails
when the user clicks on the widget or focuses it then presses the space bar, it "twists" open, revealing its contents: from there, you can use css to style the disclosure widget, and you can programmatically open and close the widget by setting/removing its open attribute.
<figure>: The Figure with Optional Caption element - HTML: Hypertext Markup Language
WebHTMLElementfigure
on + "; "; 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> <figc...
<font> - HTML: Hypertext Markup Language
WebHTMLElementfont
though once normalized in html 3.2, it was deprecated in html 4.01, at the same time as all elements related to styling only, then made obsolete in html5.
<hgroup> - HTML: Hypertext Markup Language
WebHTMLElementhgroup
however, given that a key purpose of the <hgroup> element is to affect how headings are displayed by the outline algorithm defined in the html specification—but the html outline algorithm is not implemented in any browsers—then the <hgroup> semantics are in practice only theoretical.
<input type="password"> - HTML: Hypertext Markup Language
WebHTMLElementinputpassword
if the required property is specified, then the password edit box must contain a value other than an empty string to be valid.
<input type="search"> - HTML: Hypertext Markup Language
WebHTMLElementinputsearch
the following screenshot comes from chrome: in addition, modern browsers also tend to automatically store search terms previously entered across domains, which then come up as autocomplete options when subsequent searches are performed in search inputs on that domain.
<input type="url"> - HTML: Hypertext Markup Language
WebHTMLElementinputurl
then, as the user types, the list is adjusted to show only matching values.
<menu> - HTML: Hypertext Markup Language
WebHTMLElementmenu
context menus are then attached to the element they're activated from using either the associated element's contextmenu attribute or, for button-activated menus attached to <button> elements, the menu attribute.
<meter>: The HTML Meter element - HTML: Hypertext Markup Language
WebHTMLElementmeter
for example, if it is between the min attribute and the low attribute, then the lower range is considered preferred.
<object> - HTML: Hypertext Markup Language
WebHTMLElementobject
permitted content zero or more <param> elements, then transparent.
<picture>: The Picture element - HTML: Hypertext Markup Language
WebHTMLElementpicture
the selected image is then presented in the space occupied by the <img> element.
<rb>: The Ruby Base element - HTML: Hypertext Markup Language
WebHTMLElementrb
the browser can then fill in the full element in the rendered version.
<samp>: The Sample Output element - HTML: Hypertext Markup Language
WebHTMLElementsamp
found <em>n</em> results.</samp> you can then proceed to the next step.</p> the resulting output looks like this: sample output including user input you can nest the <kbd> element within a <samp> block to present an example that includes text entered by the user.
<summary>: The Disclosure Summary element - HTML: Hypertext Markup Language
WebHTMLElementsummary
when the user clicks on the summary, the parent <details> element is toggled open or closed, and then a toggle event is sent to the <details> element, which can be used to let you know when this state change occurs.
<template>: The Content Template element - HTML: Hypertext Markup Language
WebHTMLElementtemplate
then comes the template, which describes the structure of an html fragment representing a single table row.
<textarea> - HTML: Hypertext Markup Language
WebHTMLElementtextarea
if the autocomplete attribute is not specified on a <textarea> element, then the browser uses the autocomplete attribute value of the <textarea> element's form owner.
<track>: The Embed Text Track element - HTML: Hypertext Markup Language
WebHTMLElementtrack
if the kind attribute is set to subtitles, then srclang must be defined.
HTML elements reference - HTML: Hypertext Markup Language
WebHTMLElement
the row's cells can then be established using a mix of <td> (data cell) and <th> (header cell) elements.
accesskey - HTML: Hypertext Markup Language
r older: control + key internet explorer alt + key alt + shift + key n/a edge n/a control + option + key control + option + shift + key google chrome alt + shift + key safari n/a opera 15+ alt + key control + alt + key opera 12 shift + esc opens a contents list which are accessible by accesskey, then, can choose an item by pressing key accessibility concerns in addition to poor browser support, there are numerous concerns with the accesskey attribute: an accesskey value can conflict with a system or browser keyboard shortcut, or assistive technology functionality.
dir - HTML: Hypertext Markup Language
it uses a basic algorithm as it parses the characters inside the element until it finds a character with a strong directionality, then applies that directionality to the whole element.
hidden - HTML: Hypertext Markup Language
if the content is not applicable or relevant, then there is no reason to link to it.
tabindex - HTML: Hypertext Markup Language
if you set the tabindex attribute on a <div>, then its child content cannot be scrolled with the arrow keys unless you set tabindex on the content, too.
title - HTML: Hypertext Markup Language
some caution must be taken, as this means the following renders across two lines: html <p>newlines in <code>title</code> should be taken into account, like <abbr title="this is a multiline title">example</abbr>.</p> result title attribute inheritance if an element has no title attribute, then it inherits it from its parent node, which in turn may inherit it from its parent, and so on.
x-ms-acceleratorkey - HTML: Hypertext Markup Language
"ctrl+; then k" for a shortcut similar to fogbugz’s old keyboard mode.
Global attributes - HTML: Hypertext Markup Language
it uses a basic algorithm as it parses the characters inside the element until it finds a character with a strong directionality, then it applies that directionality to the whole element.
Inline elements - HTML: Hypertext Markup Language
the <p> element totally changes the layout of the text, splitting it into three segments: the text before the <p>, then the <p>'s text, and finally the text following the <p>.
Choosing between www and non-www URLs - HTTP
it is a matter of choosing which type you want to use as your canonical location, then redirecting the other type to it.
Evolution of HTTP - HTTP
ssl 1.0 was never released outside the company, but ssl 2.0 and its successor ssl 3.0 allowed for the creation of e-commerce web sites by encrypting and guaranteeing the authenticity of the messages exchanged between the server and client.
Using Feature Policy - HTTP
if you do not specify a policy for a feature, then a default allowlist will be used.
Accept-Language - HTTP
(by languages, we mean natural languages, such as english, and not programming languages.) using content negotiation, the server then selects one of the proposals, uses it and informs the client of its choice with the content-language response header.
Accept - HTTP
WebHTTPHeadersAccept
using content negotiation, the server then selects one of the proposals, uses it and informs the client of its choice with the content-type response header.
Access-Control-Allow-Headers - HTTP
* (wildcard) the value "*" only counts as a special wildcard value for requests without credentials (requests without http cookies or http authentication information).
Access-Control-Allow-Methods - HTTP
* (wildcard) the value "*" only counts as a special wildcard value for requests without credentials (requests without http cookies or http authentication information).
Access-Control-Expose-Headers - HTTP
* (wildcard) the value "*" only counts as a special wildcard value for requests without credentials (requests without http cookies or http authentication information).
Clear-Site-Data - HTTP
http authentication credentials are also cleared out.
Connection - HTTP
except for the standard hop-by-hop headers (keep-alive, transfer-encoding, te, connection, trailer, upgrade, proxy-authorization and proxy-authenticate), any hop-by-hop headers used by the message must be listed in the connection header, so that the first proxy knows it has to consume them and not forward them further.
Content-Location - HTTP
then the client could remember that the json version is available at that particular url, skipping content negotation the next time it requests that document.
CSP: base-uri - HTTP
if this value is absent, then any uri is allowed.
CSP: worker-src - HTTP
csp version 3 directive type fetch directive fallback if this directive is absent, the user agent will first look for the child-src directive, then the script-src directive, then finally for the default-src directive, when governing worker execution.
DPR - HTTP
WebHTTPHeadersDPR
accept-ch: dpr accept-ch-lifetime: 86400 then on subsequent requests the client might send dpr header back: dpr: 1.0 ...
Device-Memory - HTTP
accept-ch: device-memory accept-ch-lifetime: 86400 then on subsequent requests the client might send device-memory header back: device-memory: 1 specifications specification status comment device memory 1the definition of 'device-memory' in that specification.
Feature-Policy: fullscreen - HTTP
it can do so by delivering the following http response header to define a feature policy: feature-policy: fullscreen 'self' then include an allow attribute on the <iframe> element: <iframe src="https://other.com/videoplayer" allow="fullscreen"></iframe> iframe attributes can selectively enable features in certain frames, and not in others, even if those frames contain documents from the same origin.
Feature-Policy: geolocation - HTTP
it can do so by delivering the following http response header to define a feature policy: feature-policy: geolocation 'self' then include an allow attribute on the <iframe> element: <iframe src="https://other.com/map" allow="geolocation"></iframe> iframe attributes can selectively enable features in certain frames, and not in others, even if those frames contain documents from the same origin.
Feature-Policy - HTTP
publickey-credentials-get controls whether the current document is allowed to use the web authentication api to retreive already stored public-key credentials, i.e.
From - HTTP
WebHTTPHeadersFrom
you shouldn't use the from header for access control or authentication.
If-Match - HTTP
WebHTTPHeadersIf-Match
if it doesn't match, then a 416 (range not satisfiable) response is returned.
If-None-Match - HTTP
when the condition fails for get and head methods, then the server must return http status code 304 (not modified).
Large-Allocation - HTTP
if you have one of these addons installed, then we will continue to use the old single process architecuture for compatibility, and cannot handle the large-allocation header.
Sec-WebSocket-Accept - HTTP
header type response header forbidden header name no syntax sec-websocket-accept: <hashed key> directives <hashed key> the server takes the value of the sec-websocket-key sent in the handshake request, appends 258eafa5-e914-47da-95ca-c5ab0dc85b11, takes sha-1 of the new value, and is then base64 encoded.
Server-Timing - HTTP
for example, you could only show metrics to authenticated users and nothing to the public.
Set-Cookie - HTTP
multiple host/domain values are not allowed, but if a domain is specified, then subdomains are always included.
Trailer - HTTP
WebHTTPHeadersTrailer
these header fields are disallowed: message framing headers (e.g., transfer-encoding and content-length), routing headers (e.g., host), request modifiers (e.g., controls and conditionals, like cache-control, max-forwards, or te), authentication headers (e.g., authorization or set-cookie), or content-encoding, content-type, content-range, and trailer itself.
Transfer-Encoding - HTTP
the content-length header is omitted in this case and at the beginning of each chunk you need to add the length of the current chunk in hexadecimal format, followed by '\r\n' and then the chunk itself, followed by another '\r\n'.
Upgrade-Insecure-Requests - HTTP
the http upgrade-insecure-requests request header sends a signal to the server expressing the client’s preference for an encrypted and authenticated response, and that it can successfully handle the upgrade-insecure-requests csp directive.
Upgrade - HTTP
WebHTTPHeadersUpgrade
the client can then request a protocol change using the process above.
X-Content-Type-Options - HTTP
since then, other browsers have introduced it, even if their mime sniffing algorithms were less aggressive.
CONNECT - HTTP
WebHTTPMethodsCONNECT
the server then proceeds to make the connection on behalf of the client.
OPTIONS - HTTP
WebHTTPMethodsOPTIONS
safe yes idempotent yes cacheable no allowed in html forms no syntax options /index.html http/1.1 options * http/1.1 examples identifying allowed request methods to find out which request methods a server supports, one can use the curl command-line program to issue an options request: curl -x options https://example.org -i the response then contains an allow header that holds the allowed methods: http/1.1 204 no content allow: options, get, head, post cache-control: max-age=604800 date: thu, 13 oct 2016 11:45:00 gmt server: eos (lax004/2813) preflighted requests in cors in cors, a preflight request is sent with the options method so that the server can respond if it is acceptable to send the request.
PATCH - HTTP
WebHTTPMethodsPATCH
for example if an auto-incrementing counter field is an integral part of the resource, then a put will naturally overwrite it (since it overwrites everything), but not necessarily so for patch.
Proxy servers and tunneling - HTTP
there are two types of proxies: forward proxies (or tunnel, or gateway) and reverse proxies (used to control and protect access to a server for load-balancing, authentication, decryption or caching).
HTTP Public Key Pinning (HPKP) - HTTP
to ensure the authenticity of a server's public key used in tls sessions, this public key is wrapped into a x.509 certificate which is usually signed by a certificate authority (ca).
HTTP resources and specifications - HTTP
rfc 7233 hypertext transfer protocol (http/1.1): range requests proposed standard rfc 7234 hypertext transfer protocol (http/1.1): caching proposed standard rfc 5861 http cache-control extensions for stale content informational rfc 8246 http immutable responses proposed standard rfc 7235 hypertext transfer protocol (http/1.1): authentication proposed standard rfc 6265 http state management mechanism defines cookies proposed standard draft spec cookie prefixes ietf draft draft spec same-site cookies ietf draft draft spec deprecate modification of 'secure' cookies from non-secure origins ietf draft rfc 2145 use and interpretation of http version numb...
307 Temporary Redirect - HTTP
WebHTTPStatus307
with 302, some old clients were incorrectly changing the method to get: the behavior with non-get methods and 302 is then unpredictable on the web, whereas the behavior with 307 is predictable.
403 Forbidden - HTTP
WebHTTPStatus403
this status is similar to 401, but in this case, re-authenticating will make no difference.
501 Not Implemented - HTTP
WebHTTPStatus501
this status can also send a retry-after header, telling the requester when to check back to see if the functionality is supported by then.
510 Not Extended - HTTP
WebHTTPStatus510
if the server receives such a request, but any described extensions are not supported for the request, then the server responds with the 510 status code.
About JavaScript - JavaScript
a javascript web server would expose host objects representing a http request and response objects, which could then be manipulated by a javascript program to dynamically generate web pages.
Concurrency model and the event loop - JavaScript
then, the event loop will process the next message in the queue (if there is one).
Iterators and generators - JavaScript
const rangeiterator = { next: function() { let result; if (nextindex < end) { result = { value: nextindex, done: false } nextindex += step; iterationcount++; return result; } return { value: iterationcount, done: true } } }; return rangeiterator; } using the iterator then looks like this: const it = makerangeiterator(1, 10, 2); let result = it.next(); while (!result.done) { console.log(result.value); // 1 3 5 7 9 result = it.next(); } console.log("iterated over sequence of size: ", result.value); // [5 numbers returned, that took interval in between: 0 to 10] note: it is not possible to know reflectively whether a particular object is an iterator.
Groups and ranges - JavaScript
examples counting vowels var aliceexcerpt = "there was a long silence after this, and alice could only hear whispers now and then."; var regexpvowels = /[aeiouy]/g; console.log("number of vowels:", aliceexcerpt.match(regexpvowels).length); // number of vowels: 25 using groups let personlist = `first_name: john, last_name: doe first_name: jane, last_name: smith`; let regexpnames = /first_name: (\w+), last_name: (\w+)/mg; let match = regexpnames.exec(personlist); do { console.log(`hello ${match[1]} ${match[2]}`); } whi...
Regular expressions - JavaScript
html <p> enter your phone number (with area code) and then click "check".
Text formatting - JavaScript
const foo = new string('foo'); // creates a string object console.log(foo); // displays: [string: 'foo'] typeof foo; // returns 'object' you can call any of the methods of the string object on a string literal value—javascript automatically converts the string literal to a temporary string object, calls the method, then discards the temporary string object.
JavaScript technologies overview - JavaScript
since then ecmascript editions are published on a yearly basis.
Memory Management - JavaScript
periodically, the garbage collector will start from these roots, find all objects that are referenced from these roots, then all objects referenced from these, etc.
TypeError: can't define property "x": "obj" is not extensible - JavaScript
'use strict'; var obj = {}; obj.x = 'foo'; // add property first and only then prevent extensions object.preventextensions(obj); ...
Warning: expression closures are deprecated - JavaScript
this syntax will be removed entirely in bug 1083458 and scripts using it will throw a syntaxerror then.
SyntaxError: for-in loop head declarations may not have initializers - JavaScript
the for loop allows you to set an initializer then as well: var arr = [ "a", "b", "c" ] for (var i = 2; i < arr.length; i++) { console.log(arr[i]); } // "c" ...
SyntaxError: missing formal parameter - JavaScript
tion greet("howdy") { return greeting; }; // syntaxerror: missing formal parameter function log({ obj: "value"}) { console.log(arg) }; // syntaxerror: missing formal parameter you will need to use identifiers in function declarations: function square(number) { return number * number; }; function greet(greeting) { return greeting; }; function log(arg) { console.log(arg) }; you can then call these functions with the arguments you like: square(2); // 4 greet("howdy"); // "howdy" log({obj: "value"}); // object { obj: "value" } ...
Default parameters - JavaScript
case 5: f = arguments; case 6: g = this.value; default: } return [a, b, c, d, e, f, g]; } withdefaults.call({value: '=^_^='}); // [undefined, 5, 5, ":p", {value:"=^_^="}, arguments, "=^_^="] withoutdefaults.call({value: '=^_^='}); // [undefined, 5, 5, ":p", {value:"=^_^="}, arguments, "=^_^="] scope effects if default parameters are defined for one or more parameter, then a second scope (environment record) is created, specifically for the identifiers within the parameter list.
The arguments object - JavaScript
description note: if you're writing es6 compatible code, then rest parameters should be preferred.
Rest parameters - JavaScript
each one of them is then multiplied by the first parameter, and the array is returned: function multiply(multiplier, ...theargs) { return theargs.map(element => { return multiplier * element }) } let arr = multiply(2, 1, 2, 3) console.log(arr) // [2, 4, 6] use with the arguments object array methods can be used on rest parameters, but not on the arguments object: function sortrestargs(...theargs) { let s...
Functions - JavaScript
for example: if (shoulddefinezero) { function zero() { // danger: compatibility risk console.log("this is zero."); } } es2015 says that if shoulddefinezero is false, then zero should never be defined, since the block never executes.
Array.prototype[@@iterator]() - JavaScript
if you have a function that takes an iterator and then iterate over the value, but don't know if that object is going to have a [iterable].prototype.values method.
Array.prototype.every() - JavaScript
if kpresent is true, then if (k in o) { var testresult; // i.
Array.prototype.find() - JavaScript
if it is not provided, then undefined is used.
Array.prototype.findIndex() - JavaScript
if it is not provided, then undefined is used.
Array.prototype.flatMap() - JavaScript
the flatmap() method first maps each element using a mapping function, then flattens the result into a new array.
Array.prototype.length - JavaScript
the value in each element is then doubled.
Array.prototype.push() - JavaScript
examples adding elements to an array the following code creates the sports array containing two elements, then appends two elements to it.
Array.prototype.shift() - JavaScript
description the shift method removes the element at the zeroeth index and shifts the values at consecutive indexes down, then returns the removed value.
Array.prototype.splice() - JavaScript
if deletecount is omitted, or if its value is equal to or larger than array.length - start (that is, if it is equal to or greater than the number of elements left in the array, starting at start), then all the elements from start to the end of the array will be deleted.
AsyncFunction - JavaScript
ion() constructor function resolveafter2seconds(x) { return new promise(resolve => { settimeout(() => { resolve(x); }, 2000); }); } let asyncfunction = object.getprototypeof(async function(){}).constructor let a = new asyncfunction('a', 'b', 'return await resolveafter2seconds(a) + await resolveafter2seconds(b);'); a(10, 20).then(v => { console.log(v); // prints 30 after 4 seconds }); specifications specification ecmascript (ecma-262)the definition of 'asyncfunction object' in that specification.
Atomics - JavaScript
if waiting is not allowed in the calling agent then it throws an error exception.
Date.prototype.setYear() - JavaScript
description if yearvalue is a number between 0 and 99 (inclusive), then the year for dateobj is set to 1900 + yearvalue.
Date.prototype.toLocaleDateString() - JavaScript
the default value for each date-time component property is undefined, but if the weekday, year, month, day properties are all undefined, then year, month, and day are assumed to be "numeric".
Date.prototype.toLocaleString() - JavaScript
but, if the weekday, year, month, and day properties are all undefined, then year, month, and day are assumed to be "numeric".
Date.prototype.toLocaleTimeString() - JavaScript
the default value for each date-time component property is undefined, but if the hour, minute, second properties are all undefined, then hour, minute, and second are assumed to be "numeric".
Error.prototype.stack - JavaScript
description each step will be separated by a newline, with the first part of the line being the function name (if not a call from the global scope), then by an at (@) sign, the file location (except when the function is the error constructor as the error is being thrown), a colon, and, if there is a file location, the line number.
FinalizationRegistry.prototype.unregister() - JavaScript
examples using unregister this example shows registering a target object using that same object as the unregister token, then later unregistering it via unregister: class thingy { #cleanup = label => { // ^^^^^−−−−− held value console.error( `the \`release\` method was never called for the object with the label "${label}"` ); }; #registry = new finalizationregistry(this.#cleanup); /** * constructs a `thingy` instance.
Function.prototype.call() - JavaScript
with call(), you can write a method once and then inherit it in another object, without having to rewrite the method for the new object.
Intl.DateTimeFormat() constructor - JavaScript
possible values are: "long" (e.g., british summer time) "short" (e.g., gmt+1) the default value for each date-time component property is undefined, but if all component properties are undefined, then year, month, and day are assumed to be "numeric".
Intl.Locale() constructor - JavaScript
for example, set the hourcycle property of the configuration object to your desired hour cycle type, and then pass it into the constructor: let us12hour = new intl.locale("en-us", {hourcycle: "h12"}); console.log(us12hour.hourcycle); // prints "h12" specifications specification ecmascript internationalization api (ecma-402) ...
Intl.Locale.prototype.calendar - JavaScript
set the calendar property of the configuration object to your desired calendar era, and then pass it into the constructor.
Intl.Locale.prototype.caseFirst - JavaScript
set the casefirst property of the configuration object to your desired casefirst value, and then pass it into the constructor.
Intl.Locale.prototype.collation - JavaScript
set the collation property of the configuration object to your desired collation type, and then pass it into the constructor.
Intl.Locale.prototype.hourCycle - JavaScript
set the hourcycle property of the configuration object to your desired hour cycle type, and then pass it into the constructor.
Intl.Locale.prototype.numeric - JavaScript
if numeric is set to true, then the locale will take numeric characters into account when collating strings.
Intl.Locale - JavaScript
for example, set the hourcycle property of the configuration object to your desired hour cycle type, and then pass it into the constructor: let us12hour = new intl.locale("en-us", {hourcycle: "h12"}); console.log(us12hour.hourcycle); // prints "h12" specifications specification ecmascript internationalization api (ecma-402) ...
Intl.NumberFormat() constructor - JavaScript
if at least one property from the second group is defined, then the first group is ignored.
Intl.PluralRules() constructor - JavaScript
if at least one property from the second group is defined, then the first group is ignored.
Intl - JavaScript
if the application doesn't provide a locales argument, or the runtime doesn't have a locale that matches the request, then the runtime's default locale is used.
Map.prototype.get() - JavaScript
if the value that is associated to the provided key is an object, then you will get a reference to that object and any change made to that object will effectively modify it inside the map object.
Math.imul() - JavaScript
this is because of the costly conversion from a floating point to an integer for multiplication, and then converting the multiplied integer back into a floating point.
Math.random() - JavaScript
the math.random() function returns a floating-point, pseudo-random number in the range 0 to less than 1 (inclusive of 0, but not 1) with approximately uniform distribution over that range — which you can then scale to your desired range.
Math.random() - JavaScript
the math.random() function returns a floating-point, pseudo-random number in the range 0 to less than 1 (inclusive of 0, but not 1) with approximately uniform distribution over that range — which you can then scale to your desired range.
Number.parseFloat() - JavaScript
if this argument is not a string, then it is converted to one using the tostring abstract operation.
Number.parseInt() - JavaScript
if this argument is not a string, then it is converted to one using the tostring abstract operation.
Object.prototype.constructor - JavaScript
the example then displays the constructor property for the object thetree.
Object.freeze() - JavaScript
in es5, if the argument to this method is not an object (a primitive), then it will cause a typeerror.
Object.getOwnPropertyDescriptor() - JavaScript
// value: 73, // writable: true // } o = {}; object.defineproperty(o, 'qux', { value: 8675309, writable: false, enumerable: false }); d = object.getownpropertydescriptor(o, 'qux'); // d is { // value: 8675309, // writable: false, // enumerable: false, // configurable: false // } non-object coercion in es5, if the first argument to this method is not an object (a primitive), then it will cause a typeerror.
Object.getOwnPropertyDescriptors() - JavaScript
merable and own properties from a source object to a target object, you are able to use this method and object.create() for a shallow copy between two unknown objects: object.create( object.getprototypeof(obj), object.getownpropertydescriptors(obj) ); creating a subclass a typical way of creating a subclass is to define the subclass, set its prototype to an instance of the superclass, and then define properties on that instance.
Object.getOwnPropertyNames() - JavaScript
in es5, if the argument to this method is not an object (a primitive), then it will cause a typeerror.
Object.isExtensible() - JavaScript
var frozen = object.freeze({}); object.isextensible(frozen); // === false non-object coercion in es5, if the argument to this method is not an object (a primitive), then it will cause a typeerror.
Object.isSealed() - JavaScript
ct.isfrozen(sealed); // === true // (all properties also non-writable) var s2 = object.seal({ p: 3 }); object.isfrozen(s2); // === false // ('p' is still writable) var s3 = object.seal({ get p() { return 0; } }); object.isfrozen(s3); // === true // (only configurability matters for accessor properties) non-object coercion in es5, if the argument to this method is not an object (a primitive), then it will cause a typeerror.
Object.keys() - JavaScript
non-object coercion in es5, if the argument to this method is not an object (a primitive), then it will cause a typeerror.
Object.preventExtensions() - JavaScript
fixed.__proto__ = { oh: 'hai' }; non-object coercion in es5, if the argument to this method is not an object (a primitive), then it will cause a typeerror.
Object.seal() - JavaScript
object.defineproperty(obj, 'ohai', { value: 17 }); // throws a typeerror object.defineproperty(obj, 'foo', { value: 'eit' }); // changes existing property value non-object coercion in es5, if the argument to this method is not an object (a primitive), then it will cause a typeerror.
Object.setPrototypeOf() - JavaScript
* *** object.appendchain(@object [, "@arg_name_1", "@arg_name_2", "@arg_name_3", "..."], "@function_body") *** object.appendchain(@object [, "@arg_name_1, @arg_name_2, @arg_name_3, ..."], "@function_body") * * appends the first non-native prototype of a chain to the native function.prototype object, then appends a * new function(["@arg"(s)], "@function_body") to that chain.
Promise.reject() - JavaScript
examples using the static promise.reject() method promise.reject(new error('fail')).then(function() { // not called }, function(error) { console.error(error); // stacktrace }); specifications specification ecmascript (ecma-262)the definition of 'promise.reject' in that specification.
handler.defineProperty() - JavaScript
if a property has a corresponding target object property then object.defineproperty(target, prop, descriptor) will not throw an exception.
handler.ownKeys() - JavaScript
if the target object is not extensible, then the result list must contain all the keys of the own properties of the target object and no other values.
Proxy - JavaScript
cate success return true; } }); let i1 = view.selected = document.getelementbyid('item-1'); //giving error here, i1 is null console.log(i1.getattribute('aria-selected')); // 'true' let i2 = view.selected = document.getelementbyid('item-2'); console.log(i1.getattribute('aria-selected')); // 'false' console.log(i2.getattribute('aria-selected')); // 'true' note: even if selected: !null, then giving oldval.setattribute is not a function value correction and an extra property the products proxy object evaluates the passed value and converts it to an array if needed.
Reflect.getOwnPropertyDescriptor() - JavaScript
r({x: 'hello'}, 'x') // {value: "hello", writable: true, enumerable: true, configurable: true} reflect.getownpropertydescriptor({x: 'hello'}, 'y') // undefined reflect.getownpropertydescriptor([], 'length') // {value: 0, writable: true, enumerable: false, configurable: false} difference to object.getownpropertydescriptor() if the target argument to this method is not an object (a primitive), then it will cause a typeerror.
Reflect.isExtensible() - JavaScript
let frozen = object.freeze({}) reflect.isextensible(frozen) // === false difference to object.isextensible() if the target argument to this method is not an object (a primitive), then it will cause a typeerror.
Reflect.preventExtensions() - JavaScript
reflect.preventextensions(empty) reflect.isextensible(empty) // === false difference from object.preventextensions() if the target argument to this method is not an object (a primitive), then it will cause a typeerror.
RegExp.prototype.exec() - JavaScript
the returned array has the matched text as the first item, and then one item for each parenthetical capture group of the matched text.
String.prototype.charCodeAt() - JavaScript
if the unicode code point cannot be represented in a single utf-16 code unit (because its value is greater than 0xffff) then the code unit returned will be the first part of a surrogate pair for the code point.
String.prototype.lastIndexOf() - JavaScript
if searchvalue is an empty string, then fromindex is returned.
String.prototype.link() - JavaScript
the returned string can then be added to the document via document.write() or element.innerhtml.
String.prototype.padStart() - JavaScript
if the value is less than str.length, then str is returned as-is.
String.prototype.replaceAll() - JavaScript
(for example, if the whole string was 'abcd', and the matched substring was 'bc', then this argument will be 1.) string the whole string being examined.
String.prototype.substring() - JavaScript
if indexstart is greater than indexend, then the effect of substring() is as if the two arguments were swapped; see example below.
Symbol.iterator - JavaScript
can be defined directly inside a class or object using a computed property: class foo { *[symbol.iterator] () { yield 1; yield 2; yield 3; } } const someobj = { *[symbol.iterator] () { yield 'a'; yield 'b'; } } [...new foo] // [ 1, 2, 3 ] [...someobj] // [ 'a', 'b' ] non-well-formed iterables if an iterable's @@iterator method does not return an iterator object, then it is a non-well-formed iterable.
TypedArray.prototype.find() - JavaScript
if it is not provided, then undefined is used.
TypedArray.prototype.findIndex() - JavaScript
if it is not provided, then undefined is used.
TypedArray.prototype.indexOf() - JavaScript
if the calculated index is less than 0, then the whole typed array will be searched.
TypedArray - JavaScript
int8array), an array buffer is created internally in memory or, if an arraybuffer object is given as constructor argument, then this is used instead.
WeakMap - JavaScript
getting values from the map would involve iterating through all keys to find a match, then using the index of this match to retrieve the corresponding value from the array of values.
WebAssembly.Memory.prototype.grow() - JavaScript
var memory = new webassembly.memory({initial:1, maximum:10}); we can then grow the instance by one page like so: const bytesperpage = 64 * 1024; console.log(memory.buffer.bytelength / bytesperpage); // "1" console.log(memory.grow(1)); // "1" console.log(memory.buffer.bytelength / bytesperpage); // "2" note the return value of grow() here is the previous number of webassembly pages.
WebAssembly.Module() constructor - JavaScript
examples synchronously compiling a webassembly module var importobject = { imports: { imported_func: function(arg) { console.log(arg); } } }; function createwasmmodule(bytes) { return new webassembly.module(bytes); } fetch('simple.wasm').then(response => response.arraybuffer() ).then(bytes => { let mod = createwasmmodule(bytes); webassembly.instantiate(mod, importobject) .then(result => result.exports.exported_func() ); }) specifications specification webassembly javascript interfacethe definition of 'webassembly.module()' in that specification.
WebAssembly.Table.prototype.grow() - JavaScript
var table = new webassembly.table({ element: "anyfunc", initial: 2, maximum: 10 }); you can then grow the table by 1 with the following: console.log(table.length); // "2" console.log(table.grow(1)); // "2" console.log(table.length); // "3" specifications specification webassembly javascript interfacethe definition of 'grow()' in that specification.
WebAssembly.Table.prototype.length - JavaScript
var table = new webassembly.table({ element: "anyfunc", initial: 2, maximum: 10 }); you can then grow the table by 1 with the following: console.log(table.length); // "2" console.log(table.grow(1)); // "2" console.log(table.length); // "3" specifications specification webassembly javascript interfacethe definition of 'length' in that specification.
escape() - JavaScript
(hh are two hexadecimal digits, and the form \xhh\xhh is used for higher-plane unicode characters.) escaped characters in string literals can be expanded by replacing the \x with %, then using the decodeuricomponent() function.
isNaN() - JavaScript
the resulting value is then tested to determine whether it is nan.
parseFloat() - JavaScript
if this argument is not a string, then it is converted to one using the tostring abstract operation.
Iteration protocols - JavaScript
alue of ['a', 'b', 'c']) { console.log(value); } // "a" // "b" // "c" console.log([...'abc']); // ["a", "b", "c"] function* gen() { yield* ['a', 'b', 'c']; } console.log(gen().next()); // { value: "a", done: false } [a, b, c] = new set(['a', 'b', 'c']); console.log(a); // "a" non-well-formed iterables if an iterable's @@iterator method doesn't return an iterator object, then it's considered a non-well-formed iterable.
Comma operator (,) - JavaScript
var a, b, c; a = b = 3, c = 4; // returns 4 in console console.log(a); // 3 (left-most) var x, y, z; x = (y = 5, z = 6); // returns 6 in console console.log(x); // 6 (right-most) processing and then returning another example that one could make with comma operator is processing before returning.
Conditional (ternary) operator - JavaScript
the conditional (ternary) operator is the only javascript operator that takes three operands: a condition followed by a question mark (?), then an expression to execute if the condition is truthy followed by a colon (:), and finally the expression to execute if the condition is falsy.
Equality (==) - JavaScript
however, if both operands are string objects, then they are compared as objects and must reference the same object for comparison to succeed: const string1 = "hello"; const string2 = string("hello"); const string3 = new string("hello"); const string4 = new string("hello"); console.log(string1 == string2); // true console.log(string1 == string3); // true console.log(string2 == string3); // true console.log(string3 == string4); // false console.l...
Grouping operator ( ) - JavaScript
examples using the grouping operator overriding multiplication and division first, then addition and subtraction to evaluate addition first.
Logical AND (&&) - JavaScript
see example: function a(){ console.log('called a'); return false; } function b(){ console.log('called b'); return true; } console.log( a() && b() ); // logs "called a" due to the function call, // then logs false (which is the resulting value of the operator) operator precedence the following expressions might seem equivalent, but they are not, because the && operator is executed before the || operator (see operator precedence).
Logical OR (||) - JavaScript
see example: function a(){ console.log('called a'); return false; } function b(){ console.log('called b'); return true; } console.log( b() || a() ); // logs "called b" due to the function call, // then logs true (which is the resulting value of the operator) operator precedence the following expressions might seem equivalent, but they are not, because the && operator is executed before the || operator (see operator precedence).
Optional chaining (?.) - JavaScript
without optional chaining, looking up a deeply-nested subproperty requires validating the references in between, such as: let nestedprop = obj.first && obj.first.second; the value of obj.first is confirmed to be non-null (and non-undefined) before then accessing the value of obj.first.second.
Function expression - JavaScript
this name is then local only to the function body (scope).
this - JavaScript
while the default for a constructor is to return the object referenced by this, it can instead return some other object (if the return value isn't an object, then the this object is returned).
Expressions and operators - JavaScript
- the unary negation operator converts its operand to number type and then negates it.
break - JavaScript
examples break in while loop the following function has a break statement that terminates the while loop when i is 3, and then returns the value 3 * x.
class - JavaScript
examples a simple class declaration in the following example, we first define a class named polygon, then extend it to create a class named square.
for await...of - JavaScript
this example first creates an async iterable for a stream of data, then uses it to find the size of the response from the api.
for...in - JavaScript
if a property is modified in one iteration and then visited at a later time, its value in the loop is its value at that later time.
label - JavaScript
description you can use a label to identify a loop, and then use the break or continue statements to indicate whether a program should interrupt the loop or continue its execution.
throw - JavaScript
you can then reference the object's properties in the catch block.
JavaScript typed arrays - JavaScript
let idview = new uint32array(buffer, 0, 1); let usernameview = new uint8array(buffer, 4, 16); let amountdueview = new float32array(buffer, 20, 1); then you can access, for example, the amount due with amountdueview[0].
JavaScript
since then, ecmascript standards are on yearly release cycles.
icons - Web app manifests
the icon can then be used by the user agent like a mask over any solid fill.
Proving the Pythagorean theorem - MathML
i.e, if a and b are the legs and c is the hypotenuse then a 2 + b 2 = c 2 .
Media container formats (file types) - Web media technologies
then add child <source> elements within the <video> element, one for each version of the video you offer.
Image file type and format guide - Web media technologies
the color map lists all of the red values, then all of the green values, then all of the blue values (rather than rgb, rgb, rgb...).
Handling media support issues in web content - Web media technologies
<img src="/images/stafff-photo-huge-progressive.jpg" alt="staff photo, taken in january of 1972"> when using a progressive image, the data is stored in such a way that the browser is able to render a low-quality representation of the image as soon as possible, then update the image as it loads—or after it's finished loading—to present it in full quality.
OpenSearch description format
then, logging information will appear in firefox's error console (tools ⟩ error console) when search plugins are added.
CSS and JavaScript animation performance - Web Performance
note: in nightly/developer edition, you should see that omta is enabled by default, so you might have to do the tests the other way around (test with it enabled first, then disable to test without omta.) summary browsers are able to optimize rendering flows.
Recommended Web Performance Timings: How long is too long? - Web Performance
the first asset retrieved from a request is usually an html document, which then makes calls for additional assets.
Optimizing startup performance - Web Performance
instead, you should write your code so that your app creates a web worker that does as much as possible in a background thread (for example, fetching and processing data.) then, anything that must be done on the main thread (such as user events and rendering ui) should be broken up into small pieces so that the app's event loop continues to cycle while it starts up.
Using dns-prefetch - Web Performance
the cross-origin domain is then specified in the href attribute: syntax <link rel="dns-prefetch" href="https://fonts.gstatic.com/" > examples <html> <head> <link rel="dns-prefetch" href="https://fonts.gstatic.com/"> <!-- and all other head elements --> </head> <body> <!-- your page content --> </body> </html> you should place dns-prefetch hints in the <head> element any time your site references resour...
Progressive web apps (PWAs)
this guide explains how a2hs is used, and what you need to do as a developer to allow your users to take advantage of it.how to make pwas installablein this article, we learned about how we can make pwas installable with a properly-configured web manifest, and how the user can then install the pwa with the "add to home screen" feature of their browser.how to make pwas re-engageable using notifications and pushhaving the ability to cache the contents of an app to work offline is a great feature.
baseFrequency - SVG: Scalable Vector Graphics
if one number is provided, then that value is used for both x and y.
color-profile - SVG: Scalable Vector Graphics
if no match is found, then the embedded profile inside the image is used.
d - SVG: Scalable Vector Graphics
WebSVGAttributed
the end point (pn) then becomes the current point for the next command (po′).
divisor - SVG: Scalable Vector Graphics
WebSVGAttributedivisor
if the specified divisor is 0 then the default value will be used instead.
enable-background - SVG: Scalable Vector Graphics
default value accumulate animatable no accumulate if an ancestor container element has a property value of enable-background: new, then all graphics elements within the current container element are rendered both onto the parent container elementʼs background image canvas and onto the target device.
externalResourcesRequired - SVG: Scalable Vector Graphics
in particular, if an element sets externalresourcesrequired="true", then all style sheets must be available since any style sheet might affect the rendering of that element.
keyPoints - SVG: Scalable Vector Graphics
bad values, too many or too few values), then thatʼs an error.
letter-spacing - SVG: Scalable Vector Graphics
if the attribute value has a unit identifier, such as .25em or 1%, then the browser converts the <length> into its corresponding value in the current user coordinate system.
local - SVG: Scalable Vector Graphics
WebSVGAttributelocal
if both the xlink:href and the local attribute are specified, then the local file system is searched for the color profile first, and, if not available locally, then the resource identified by the xlink:href attribute is used.
marker-mid - SVG: Scalable Vector Graphics
if the reference is not valid, then no marker will be drawn.
method - SVG: Scalable Vector Graphics
WebSVGAttributemethod
stretch this value indicates that the character outlines will be converted into paths, and then stretched and possibly warped.
orient - SVG: Scalable Vector Graphics
WebSVGAttributeorient
note: for example, if a value of 45 is given, then the marker's positive x-axis would be pointing down and right in the shape's coordinate system.
paint-order - SVG: Scalable Vector Graphics
ibute, it can be applied to any element but it has effect only on the following ten elements: <circle>, <ellipse>, <line>, <path>, <polygon>, <polyline>, <rect>, <text>, <textpath>, and <tspan> usage notes value normal | [ fill || stroke || markers ] default value normal animatable yes normal this value indicates that the fill will be painted first, then the stroke, and finally the markers.
pathLength - SVG: Scalable Vector Graphics
this value is then used to calibrate the browser's distance calculations with those of the author, by scaling all distance computations using the ratio pathlength/(computed value of path length).
preserveAspectRatio - SVG: Scalable Vector Graphics
note that if <align> is none, then the optional <meetorslice> value is ignored.
radius - SVG: Scalable Vector Graphics
WebSVGAttributeradius
if one number is provided, then that value is used for both x and y.
requiredFeatures - SVG: Scalable Vector Graphics
if the attribute is not present, then its implicit evaluated value is true.
result - SVG: Scalable Vector Graphics
WebSVGAttributeresult
if supplied, then graphics that result from processing this filter primitive can be referenced by an in attribute on a subsequent filter primitive within the same <filter> element.
startOffset - SVG: Scalable Vector Graphics
if a percentage is given, then the start offset represents a percentage distance along the entire path.
stroke-dasharray - SVG: Scalable Vector Graphics
if an odd number of values is provided, then the list of values is repeated to yield an even number of values.
text-anchor - SVG: Scalable Vector Graphics
then, the text string is mapped onto the path with this midpoint placed at the current text position.) end the rendered characters are shifted such that the end of the resulting rendered text (final current text position before applying the text-anchor property) is at the initial current text position.
textLength - SVG: Scalable Vector Graphics
then <text> is used to create the text element itself, with an id of "hello".
transform-origin - SVG: Scalable Vector Graphics
if two or more values are defined and either no value is a keyword, or the only used keyword is center, then the first value represents the horizontal offset and the second represents the vertical offset.
u1 - SVG: Scalable Vector Graphics
WebSVGAttributeu1
if a given unicode character within the set has multiple corresponding <glyph> elements (i.e., there are multiple <glyph> elements with the same unicode attribute value but different glyph-name values), then all such glyphs are included in the set.
u2 - SVG: Scalable Vector Graphics
WebSVGAttributeu2
if a given unicode character within the set has multiple corresponding <glyph> elements (i.e., there are multiple <glyph> elements with the same unicode attribute value but different glyph-name values), then all such glyphs are included in the set.
vector-effect - SVG: Scalable Vector Graphics
the default rendering behaviour is used which is to first fill the geometry of a shape with a specified paint, then stroke the outline with a specified paint.
visibility - SVG: Scalable Vector Graphics
note: if the visibility attribute is set to hidden on a text element, then the text is invisible but still takes up space in text layout calculations.
word-spacing - SVG: Scalable Vector Graphics
.25em or 1%), then the browser converts the <length> into a corresponding value in the current user coordinate system.
xml:space - SVG: Scalable Vector Graphics
then, it draws all space characters (including leading, trailing and multiple consecutive space characters).
Content type - SVG: Scalable Vector Graphics
for example, to fill a rectangle with a linear gradient, you first define a <lineargradient> element and give it an id, as in: <lineargradient xml:id="mygradient">...</lineargradient> you then reference the linear gradient as the value of the fill attribute for the rectangle, as in the following example: <rect fill="url(#mygradient)"/> svg supports two types of iri references: local iri references, where the iri reference does not contain an <absoluteiri> or <relativeiri> and thus only contains a fragment identifier (i.e., #<elementid> or #xpointer(id<elementid>)).
<feConvolveMatrix> - SVG: Scalable Vector Graphics
assuming the simplest case (where the input image's pixel grid aligns perfectly with the kernel's pixel grid) and assuming default values for attributes ‘divisor’, ‘targetx’ and ‘targety’, then resulting color value will be: (9* 0 + 8* 20 + 7* 40 + 6*100 + 5*120 + 4*140 + 3*200 + 2*220 + 1*240) / (9+8+7+6+5+4+3+2+1) usage context categoriesfilter primitive elementpermitted contentany number of the following elements, in any order:<animate>, <set> attributes global attributes core attributes presentation attributes filter primitive attributes class style specific attribu...
<feMerge> - SVG: Scalable Vector Graphics
WebSVGElementfeMerge
this is achieved by other filters storing their output via the result attribute and then accessing it in a <femergenode> child.
<hatch> - SVG: Scalable Vector Graphics
WebSVGElementhatch
hatches defined by the <hatch> element can then referenced by the fill and stroke css properties on a given graphics element to indicate that the given element shall be filled or stroked with the hatch.
<use> - SVG: Scalable Vector Graphics
WebSVGElementuse
--> </svg> the effect is the same as if the nodes were deeply cloned into a non-exposed dom, then pasted where the use element is, much like cloned template elements in html5.
SVG animation with SMIL - SVG: Scalable Vector Graphics
in this case, we're establishing a path consisting of a moveto command to establish the starting point for the animation, then the horizontal-line command to move the circle 300 pixels to the right, followed by the z command, which closes the path, establishing a loop back to the beginning.
Basic shapes - SVG: Scalable Vector Graphics
the drawing then closes the path, so a final straight line would be drawn from (2,2) to (0,0).
Clipping and masking - SVG: Scalable Vector Graphics
then every part of the target lying in a transparent area of the resulting clippath's content will not be rendered.
Patterns - SVG: Scalable Vector Graphics
WebSVGTutorialPatterns
the two rects and the circle inside the pattern were then sized to fit in a 50×50 box.
SVG In HTML Introduction - SVG: Scalable Vector Graphics
the preserveaspectratio attribute specifies that the aspect ratio must be preserved by centering the picture in the available size, sizing to the maximum of the height or width and then cutting off any overflow.
SVG and CSS - SVG: Scalable Vector Graphics
see below how the structure then looks like.
Insecure passwords - Web security
attackers are getting smarter; they steal username/password pairs from one site and then try reusing them on more lucrative sites.
Mixed content - Web security
the webpage may have public data visible to the world or private data visible only when authenticated.
Same-origin policy - Web security
corporate intranet domains), then the same-origin limitations are not applied.
Features restricted to secure contexts - Web security
push api 42 17 not supported 44 reporting api supported not supported not supported behind flag since fx 65 service workers 40 17 11.1 44 storage api 55 not supported not supported 51 web authentication api 65 in preview (17) in development 60 web bluetooth 56 not supported not supported not supported web midi (see midiaccess, for example) 43 not supported not supported not supported web crypto api 60 79 not supported 75 secure context restrictions that vary by browser some browsers may decide to disable ...
Subdomain takeovers - Web security
an attacker can take over that subdomain by providing their own virtual host and then hosting their own content for it.
Web security
security-related glossary terms block cipher mode of operation certificate authority challenge-response authentication cipher cipher suite ciphertext cors cors-safelisted request header cors-safelisted response header cross-site scripting cryptanalysis cryptographic hash function cryptography csp csrf decryption digital certificate dtls encryption forbidden header name forbidden response header name...
element-available - XPath
if the expanded-name has a namespace uri equal to the xslt namespace uri, then it refers to an element defined by xslt.
lang - XPath
WebXPathFunctionslang
if the current node does not have an xml:lang attribute, then the value of the xml:lang attribute of the nearest ancestor that has an xml:lang attribute will determine the current node's language.
round - XPath
WebXPathFunctionsround
returns the nearest integer less then, greater than, or equal todecimal.
translate - XPath
if abc is longer than xyz, then every occurrence of characters in abc that do not have a corresponding character in xyz will be removed.
<xsl:attribute-set> - XSLT: Extensible Stylesheet Language Transformations
xslt/xpath reference: xslt elements, exslt functions, xpath functions, xpath axes the <xsl:attribute-set> element creates a named set of attributes, which can then be applied as whole to the output document, in a manner similar to named styles in css.
<xsl:if> - XSLT: Extensible Stylesheet Language Transformations
WebXSLTElementif
to achieve the functionality of an if-then-else statement, however, use the <xsl:choose> element with one <xsl:when> and one <xsl:otherwise> children.
<xsl:number> - XSLT: Extensible Stylesheet Language Transformations
WebXSLTElementnumber
the processor goes to the first node in the ancestor-or-self axis that matches the count attribute and then counts that node plus all its preceding siblings (stopping when it reaches a match to the from attribute, if there is one) that also match the count attribute.if no match is found, the sequence will be an empty list.
Transforming XML with XSLT - XSLT: Extensible Stylesheet Language Transformations
xslt allows a stylesheet author to transform a primary xml document in two significant ways: manipulating and sorting the content, including a wholesale reordering of it if so desired, and transforming the content into a different format (and in the case of firefox, the focus is on converting it on the fly into html which can then be displayed by the browser).
Using the Mozilla JavaScript interface to XSL Transformations - XSLT: Extensible Stylesheet Language Transformations
resetting the xsltprocessor object also implements a xsltprocessor.reset() method, which can be used to remove all stylesheets and parameters then put the processor back into its initial state.
Basic Example - XSLT: Extensible Stylesheet Language Transformations
the .xsl file is then imported (xsltprocessor.importstylesheet(xslstylesheet)) and the transformation run (xsltprocessor.transformtofragment(xmldoc, document)).
Introduction - XSLT: Extensible Stylesheet Language Transformations
javascript can enable a web application to load xml data, process it via xslt into a presentable form and then add it into an existing document.
JavaScript/XSLT Bindings - XSLT: Extensible Stylesheet Language Transformations
the cloned dom can then be easily inserted into the xml document using node.appendchild(), as shown in figure 2.
Setting Parameters - XSLT: Extensible Stylesheet Language Transformations
for example, javascript and xslt could be used to sort xml data and then display it.
XSLT: Extensible Stylesheet Language Transformations
WebXSLT
then, the new document may be serialized (output) by the processor in standard xml syntax or in another format, such as html or plain text.
Compiling a New C/C++ Module to WebAssembly - WebAssembly
you could then build your custom html completely from scratch, although this is an advanced approach; it is usually easier to use the provided html template.
Index - WebAssembly
this article provides a reference for the different mechanisms that can be used to fetch webassembly bytecode, as well as how to compile/instantiate then run it.
Compiling an Existing C Module to WebAssembly - WebAssembly
luckily, the canvas api has canvasrenderingcontext2d.getimagedata — that gives you an uint8clampedarray containing the image data in rgba: async function loadimage(src) { // load image const imgblob = await fetch(src).then(resp => resp.blob()); const img = await createimagebitmap(imgblob); // make canvas same size as image const canvas = document.createelement('canvas'); canvas.width = img.width; canvas.height = img.height; // draw image onto canvas const ctx = canvas.getcontext('2d'); ctx.drawimage(img, 0, 0); return ctx.getimagedata(0, 0, img.width, img.height); } now it's "only" a matter of co...
WebAssembly
compiling a new c/c++ module to webassembly when you’ve written code in c/c++, you can then compile it into .wasm using a tool like emscripten.