Search completed in 0.95 seconds.
1043 results for "reason":
Your results are loading. Please wait...
451 Unavailable For Legal Reasons - HTTP
Web › HTTP › Status › 451
note: the link header might also contain a rel="blocked-by" relation identifying the entity and implementing blockage, not any other entity mandating it. any attempt to identify the entity ultimately responsible for the resource being unavailable belongs in the response body, not in the rel="blocked-by" link. ...
...lation identifying the entity and implementing blockage, not any other entity mandating it. any attempt to identify the entity ultimately responsible for the resource being unavailable belongs in the response body, not in the rel="blocked-by" link. this includes the name of the person or organization that made a legal demand resulting in the content's removal. ...
...sible for the resource being unavailable belongs in the response body, not in the rel="blocked-by" link. this includes the name of the person or organization that made a legal demand resulting in the content's removal. ...
...And 2 more matches
RTCOutboundRtpStreamStats.qualityLimitationReason - Web APIs
the qualitylimitationreason property of the rtcoutboundrtpstreamstats dictionary is a string indicating the reason why the media quality in the stream is currently being reduced by the codec during encoding, or none if no quality reduction is being performed. this quality reduction may include changes such as reduced frame rate or resolution, or an increase in compression factor. the amount of time the encoded media has had its quality reduced in each of the potential ways that can be done can be found in qualitylimitationdurations. ...
...reduced by the codec during encoding, or none if no quality reduction is being performed. this quality reduction may include changes such as reduced frame rate or resolution, or an increase in compression factor. the amount of time the encoded media has had its quality reduced in each of the potential ways that can be done can be found in qualitylimitationdurations. syntax var qualitylimitationreason = rtcoutboundrtpstreamstats.qualitylimitationreason; value a map whose keys are domstrings whose values come from the rtcqualitylimitationreason enumerated type, and whose values are the duration of the media, in seconds, whose quality was reduced for that reason. examples specifications specification status comment identifiers for webrtc's statistics apithe defi...
... value a map whose keys are domstrings whose values come from the rtcqualitylimitationreason enumerated type, and whose values are the duration of the media, in seconds, whose quality was reduced for that reason. examples specifications specification status comment identifiers for webrtc's statistics apithe definition of 'rtcoutboundrtpstreamstats.qualitylimitationreason' in that specification. candidate recommendation initial definition. ...
Reason: Did not find method in CORS header ‘Access-Control-Allow-Methods’ - HTTP
this header specifies a comma-delineated list of the http methods which may be used when using cors to access the url specified in the request; if the request is using any other method, this error occurs. for example, if the response includes: access-control-allow-methods: get,head,post trying to use a put request will fail with this error. make sure your code only uses the permitted http methods when accessing the service. ...
...er method, this error occurs. for example, if the response includes: access-control-allow-methods: get,head,post trying to use a put request will fail with this error. make sure your code only uses the permitted http methods when accessing the service. note: if the server includes any unrecognized or undefined method names in its access-control-allow-methods header, a different error occurs: reason: invalid token ‘xyz' in cors header ‘access-control-allow-methods’. ...
Reason: CORS preflight channel did not succeed - HTTP
make sure your code only preflights once per connection. the preflight request simply suffered any kind of networking error that might ordinarily occur. ...
...make sure your code only preflights once per connection. the preflight request simply suffered any kind of networking error that might ordinarily occur. ...
PromiseRejectionEvent.reason - Web APIs
the promiserejectionevent reason read-only property is any javascript value or object which provides the reason passed into promise.reject(). this in theory provides information about why the promise was rejected. syntax reason = promiserejectionevent.reason value a value or object which provides information you can use to understand why the promise was rejected. this could be anything from an error code to an object with text, links, and whatever else you might wish to include. examples window.onunhandledrejection = function(e) { console.log(e.reason); } specifications specification status comment html living standardthe definition of 'promiserejectionevent.reason' in that specification. living standard initial definition. ...
Reason: CORS header 'Access-Control-Allow-Origin' does not match 'xyz' - HTTP
this error can also occur if the response includes more than one access-control-allow-origin header. if the service your code is accessing using a cors request is under your control, make sure that it's configured to include your origin in its access-control-allow-origin header, and that only one such header is included in responses. the header itself accepts a comma-delineated list of origins, so adding a new origin is not difficult. ...
Reason: CORS request did not succeed - HTTP
the error is not directly related to cors, but is a fundamental network error of some kind. in many cases, it is caused by a browser plugin (e.g. an ad blocker or privacy protector) blocking the request. other possible causes include: trying to access an https resource that has an invalid certificate will cause this error. trying to access an http resource from a page with an https origin will also cause this error. as of firefox 68, https pages are not permitted to access http://localhost, although this may be changed by bug 1488740. ...
Reason: CORS disabled - HTTP
Web › HTTP › CORS › Errors › CORSDisabled
when this happens, the user needs to turn cors back on in their browser. in firefox, the preference that disables cors is content.cors.disable. setting this to true disables cors, so whenever that's the case, cors requests will always fail with this error. ...
Reason: CORS request external redirect not allowed - HTTP
for example, if the page https://service.tld/fetchdata were requested, and the http response is "301 moved permanently", "307 temporary redirect", or "308 permanent redirect" with a location of https://anotherservice.net/getdata, the cors request will fail in this manner. to fix the problem, update your code to use the new url as reported by the redirect, thereby avoiding the redirect. ...
Reason: invalid token ‘xyz’ in CORS header ‘Access-Control-Allow-Headers’ - HTTP
the access-control-allow-headers header is sent by the server in response to a preflight request; it lets the client know which http headers are permitted in cors requests. if the client user agent finds among the comma-delineated values provided by the header any header name it does not recognize, this error occurs. this is a problem that most likely can only be fixed on the server side, by modifying the server's configuration to no longer send the invalid or unknown header name with the access-control-allow-headers header. ...
Reason: invalid token ‘xyz’ in CORS header ‘Access-Control-Allow-Methods’ - HTTP
the access-control-allow-methods header is sent by the server to let the client know what http request methods it supports for cors requests. the header's value is a comma-delineated string of http method names, such as get, post, or head. if any of the specified values are not recognized by the client user agent, this error occurs. ...
Reason: expected ‘true’ in CORS header ‘Access-Control-Allow-Credentials’ - HTTP
to fix this problem on the client side, revise the code to not request the use of credentials. if the request is being issued using xmlhttprequest, make sure you're not setting withcredentials to true. if using server-sent events, make sure eventsource.withcredentials is false (it's the default value). if using the fetch api, make sure request.credentials is "omit". ...
Reason: missing token ‘xyz’ in CORS header ‘Access-Control-Allow-Headers’ from CORS preflight channel - HTTP
the value of access-control-allow-headers should be a comma-delineated list of header names, such as "x-custom-information" or any of the standard but non-basic header names (which are always allowed). this error occurs when attempting to preflight a header that is not expressly allowed (that is, it's not included in the list specified by the access-control-allow-headers header sent by the server). to fix this, the server needs to be updated so that it allows the indicated header, or you need to avoid using that header. ...
Reason: CORS header 'Access-Control-Allow-Origin' missing - HTTP
if the server is under your control, add the origin of the requesting site to the set of domains permitted access by adding it to the access-control-allow-origin header's value. for example, to allow a site at https://amazing.site to access the resource using cors, the header should be: access-control-allow-origin: https://amazing.site you can also configure a site to allow any site to access it by using the * wildcard. you should only use this for public apis. ...
Reason: Multiple CORS header 'Access-Control-Allow-Origin' not allowed - HTTP
this isn't allowed. if you have access to the server you can change your implementation to echo back an origin in the access-control-allow-origin header. ...
Reason: Credential is not supported if the CORS header ‘Access-Control-Allow-Origin’ is ‘*’ - HTTP
to correct this problem on the client side, simply ensure that the credentials flag's value is false when issuing your cors request. if the request is being issued using xmlhttprequest, make sure you're not setting withcredentials to true. if using server-sent events, make sure eventsource.withcredentials is false (it's the default value). if using the fetch api, make sure request.credentials is "omit". ...
Reason: CORS header ‘Origin’ cannot be added - HTTP
all cors requests must have an origin header. this can happen if the javascript code is running with enhanced privileges allowing it access to multiple domains' content, for example. ...
Reason: CORS request not HTTP - HTTP
this often occurs if the url specifies a local file, using a file:/// url. to fix this problem, simply make sure you use https urls when issuing requests involving cors, such as xmlhttprequest, fetch apis, web fonts (@font-face), and webgl textures, and xsl stylesheets. local file security in firefox 68 when a user opened a page using a file:/// uri in firefox 67 and earlier, the origin of the page was defined as the directory from which the page was opened. resources in the same directory and its subdirectories were treated as having the same origin for purposes of the cors same-origin rule. ...
Examples
ise = 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(functio...
...nction in a try catch and make that catch return promise.reject(ex) otherwise it will not trigger the rejection function of the promise.then. this way if any error happens it will reject the promise. in the example below we try alerting an undefined variable. ...
...promise.reject(ex) otherwise it will not trigger the rejection function of the promise.then. this way if any error happens it will reject the promise. in the example below we try alerting an undefined variable. ...
...And 30 more matches
Index - Web APIs
Web › API › Index
nstructor, domexception, reference the domexception() constructor returns a domexception object with a specified message and name. 707 domexception.code api, code, domexception, property, reference the code read-only property of the domexception interface returns a short that contains one of the error code constants, or 0 if none match. this field is used for historical reasons. new dom exceptions don't use this anymore: they put this info in the domexception.name attribute. 708 domexception.message api, domexception, property, reference, message the message read-only property of the domexception interface returns a domstring representing a message or description associated with the given error name. 709 domexception.name api, domexc...
...able by the digitizer. 1002 document: pointerlockchange event document, event, reference, web, pointerlockchange the pointerlockchange event is fired when the pointer is locked/unlocked. 1003 document: pointerlockerror event document, event, reference, web, pointerlockerror the pointerlockerror event is fired when locking the pointer failed (for technical reasons or because the permission was denied). 1004 document: pointermove event document, event, pointerevent, reference, web, pointer, pointermove the pointermove event is fired when a pointer changes coordinates, and the pointer has not been canceled by a browser touch-action. 1005 document: pointerout event document, event, pointerevent, reference, web, onpointerou...
...ent: pointermove event document, event, pointerevent, reference, web, pointer, pointermove the pointermove event is fired when a pointer changes coordinates, and the pointer has not been canceled by a browser touch-action. 1005 document: pointerout event document, event, pointerevent, reference, web, onpointerout, pointerout the pointerout event is fired for several reasons including: pointing device is moved out of the hit test boundaries of an element; firing the pointerup event for a device that does not support hover (see pointerup); after firing the pointercancel event (see pointercancel); when a pen stylus leaves the hover range detectable by the digitizer. 1006 document: pointerover event document, event, pointerevent, reference, web, onpointe...
...And 19 more matches
HTTP Index - HTTP
Web › HTTP › Index
unning at one origin, access to selected resources from a different origin. 21 cors errors cors, errors, http, https, messages, same-origin, security, console, troubleshooting cross-origin resource sharing (cors) is a standard that allows a server to relax the same-origin policy. this is used to explicitly allow some cross-origin requests while rejecting others. 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. when this happens, the user needs to turn cors back on in their browser. 23 rea...
... security, sharing, validation, secure, troubleshooting a request that needs to use cors was attempted, but cors is disabled in the user's browser. when this happens, the user needs to turn cors back on in their browser. ...
...n cors back on in their browser. 23 reason: cors header 'access-control-allow-origin' does not match 'xyz' cors, corsalloworiginnotmatchingorigin, cross-origin, error, http, https, messages, reasons, security, console, troubleshooting simply put, the origin making the request does not match any of the origins permitted by the access-control-allow-origin header. 24 reason: cors header 'access-control-allow-origin' missing cors, corsmissingalloworigin, cross-origin, error, http, https, messages, reasons, security, console, troubleshooting the response to the cors request is missing the required access-control-allow-origin header, which is used to determine whether or not the resource can be accessed by content operating within the current origin. 2...
...And 18 more matches
CORS errors - HTTP
Web › HTTP › CORS › Errors
r web app in question and open the developer tools. now try to reproduce the failing transaction and check the console if you are seeing a cors violation error message. it will probably look like this: the text of the error message will be something similar to the following: cross-origin request blocked: the same origin policy disallows reading the remote resource at https://some-url-here. (reason: additional information here). note: for security reasons, specifics about what went wrong with a cors request are not available to javascript code. all the code knows is that an error occurred. the only way to determine what specifically went wrong is to look at the browser's console for details. cors error messages firefox's console displays messages in its console when requests fail due t...
...e: for security reasons, specifics about what went wrong with a cors request are not available to javascript code. all the code knows is that an error occurred. the only way to determine what specifically went wrong is to look at the browser's console for details. cors error messages firefox's console displays messages in its console when requests fail due to cors. part of the error text is a "reason" message that provides added insight into what went wrong. the reason messages are listed below; click the message to open an article explaining the error in more detail and offering possible solutions. ...
...g is to look at the browser's console for details. cors error messages firefox's console displays messages in its console when requests fail due to cors. part of the error text is a "reason" message that provides added insight into what went wrong. the reason messages are listed below; click the message to open an article explaining the error in more detail and offering possible solutions. ...
...And 9 more matches
Promise - JavaScript
s the eventual completion (or failure) of an asynchronous operation, and its resulting value. to learn about the way promises work and how you can use them, we advise you to read using promises first. description a promise is a proxy for a value not necessarily known when the promise is created. it allows you to associate handlers with an asynchronous action's eventual success value or failure reason. this lets asynchronous methods return values like synchronous methods: instead of immediately returning the final value, the asynchronous method returns a promise to supply the value at some point in the future. a promise is in one of these states: pending: initial state, neither fulfilled nor rejected. fulfilled: meaning that the operation completed successfully. rejected: meaning that th...
...eturning the final value, the asynchronous method returns a promise to supply the value at some point in the future. a promise is in one of these states: pending: initial state, neither fulfilled nor rejected. fulfilled: meaning that the operation completed successfully. rejected: meaning that the operation failed. a pending promise can either be fulfilled with a value, or rejected with a reason (error). when either of these options happens, the associated handlers queued up by a promise's then method are called. if the promise has already been fulfilled or rejected when a corresponding handler is attached, the handler will be called, so there is no race condition between an asynchronous operation completing and its handlers being attached. as the promise.prototype.then() and promise.pr...
...ccept a single parameter of any type. these functions are written by you, the programmer. the termination condition of these functions determines the "settled" state of the next promise in the chain. any termination other than a throw creates a "resolved" state, while terminating with a throw creates a "rejected" state. handlefulfilled(value) { /*...*/; return nextvalue; } handlerejection(reason) { /*...*/; throw nextreason; } handlerejection(reason) { /*...*/; return nextvalue; } the returned nextvalue can be another promise object, in which case the promise gets dynamically inserted into the chain. when a .then() lacks the appropriate function that return a promise object, processing simply continues to the next link of the chain. therefore, a chain can safely omit every handlere...
...And 9 more matches
Search Extension Tutorial (Draft) - Archive of obsolete content
while this is generally considered acceptable behavior, considerable care must be taken to avoid violating the mozilla add-on guidelines or creating an adverse user experience. due to the large volume of user complaints regarding hidden settings being changed against their will, and not being restored after the add-ons responsible are disabled, mozilla will take any steps necessary to mitigate the impact of offending add-ons. ...
...e the original and new values. savedprefs[name] = [defaultprefs.getcharpref(name), value]; // change the default defaultprefs.setcharpref(name, value); // clear the user value if this is the first run, or the // new default is the same as the user value. ...
...lues. savedprefs[name] = [defaultprefs.getcharpref(name), value]; // change the default defaultprefs.setcharpref(name, value); // clear the user value if this is the first run, or the // new default is the same as the user value. ...
...And 8 more matches
OS.File for the main thread
nction onsuccess(array) { return decoder.decode(array); // convert this array to a text } ); this example requires firefox 18 or a more recent version. example: write a string to a file the following snippet writes the text "this is some text" to a string "file.txt", using the default encoding (utf-8). ...
... example: copy a file the following snippet copies file "oldname.txt" to "newname.txt". on most operating system...
... example: copy a file the following snippet copies file "oldname.txt" to "newname.txt". on most operating systems, this operation is handled directly by the operati...
...And 8 more matches
How to convert an overlay extension to restartless - Archive of obsolete content
than whatever you were doing before. reportedly xmlhttprequest doesn't work reliably when used in jsm under versions of firefox less than 16, however as previously mentioned, this guide should be taken as requiring firefox 17+. step 4: manually handle default preferences normal extensions load default preferences from a standardized file automatically. restartless extensions don't (for no good reason). this part is fairly easy to implement yourself, at least. here are some functions to handle this: function getgenericpref(branch,prefname) { switch (branch.getpreftype(prefname)) { default: case 0: return undefined; // pref_invalid case 32: return getucharpref(prefname,branch); // pref_string case 64: return branch.getintpref(pr...
...ons of firefox prior to 4.0 (gecko 2.0), the xpi would be extracted into a folder in your profile's extensions folder. in current versions it stays unextracted as an xpi. if you were using input streams you already had to deal with this because they weren't an option without extraction. opting-out to extractionlessness is done via the "unpack" flag in install.rdf. why the internal jar? well, two reasons: prior to extractionless add-ons, all of your files got extracted. putting them in one single jar file made all your stuff load in one file read, which was faster. extractionless xpis are bascially a standardization of this idea. xpi files are glorified zips, and zip compression is horrible. doing anuncompressed internal jar (aka, another zip) acts like a poor-man's solid archive and signifi...
...esheets any global css style sheets which you are using will need to be registered upon load and unregistered when your extension is unloaded. any css files used in any of your own xul files will function normally without any extra work needed. components.utils.import("resource://gre/modules/services.jsm"); var stylesheets = ["chrome://myextension/skin/mystylesheet.css"]; function startup(data,reason) { ... // load stylesheets let stylesheetservice= components.classes["@mozilla.org/content/style-sheet-service;1"] .getservice(components.interfaces.nsistylesheetservice); for (let i=0,len=stylesheets.length;i<len;i++) { let stylesheeturi = services.io.newuri(stylesheets[i], null, null); stylesheetservice.loadandregistersheet(styles...
...And 6 more matches
Promise
hree states: pending, when the final value is not available yet. this is the only state that may transition to one of the other two states. fulfilled, when and if the final value becomes available. a fulfillment value becomes permanently associated with the promise. this may be any value, including undefined. rejected, if an error prevented the final value from being determined. a rejection reason becomes permanently associated with the promise. this may be any value, including undefined, though it is generally an error object, like in exception handling. note: you should always handle, forward, or report errors (rejection reasons). if you see the message "a promise chain failed to handle a rejection", there is likely something to be fixed in the code. see handling errors and common pit...
... a rejection", there is likely something to be fixed in the code. see handling errors and common pitfalls below. documentation conventions in documentation, the type of the fulfillment value is usually specified between angular brackets. for example, the os.file.exists function returns a promise that will eventually fulfill with a boolean: promise<boolean> exists(string path); the rejection reason may be specified separately in the function's documentation, and is considered to be an error object unless otherwise specified. 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 resolvin...
...e( avalue ); parameters avalue optional if this value is not a promise, including undefined, it becomes the fulfillment value of the associated promise. 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). reject() rejects the associated promise with the specified reason. if the promise has already been resolved, either to a value, a rejection, or another promise, this method does nothing. void reject( areason ); parameters areason optional the rejection reason for the associated promise. although the reason can be undefined, it is generally an error object, like in exception handling. note: this argument should not be a promise. specifying a rejecte...
...And 5 more matches
Bootstrapped extensions - Archive of obsolete content
the extension needs to start itself up. this happens at application launch time, when the extension is enabled after being disabled or after it has been shut down in order to install an update. as such, this can be called many times during the lifetime of the application. this is when your add-on should inject its ui, start up any tasks it may need running and so forth. void startup( data, reason ); parameters data a bootstrap data structure. reason one of the reason constants, indicating why the extension is being started up. this will be one of app_startup, addon_disable, addon_install, addon_upgrade, or addon_downgrade. shutdown called when the extensidisableon needs to shut itself down, such as when the application is quitting or when the extension is about to be upgraded o...
...p. this will be one of app_startup, addon_disable, addon_install, addon_upgrade, or addon_downgrade. shutdown called when the extensidisableon needs to shut itself down, such as when the application is quitting or when the extension is about to be upgraded or disabled. any user interface that has been injected must be removed, tasks shut down, and objects disposed of. void shutdown( data, reason ); parameters data a bootstrap data structure. reason one of the reason constants, indicating why the extension is being shut down. this will be one of app_shutdown, addon_disable, addon_uninstall, addon_upgrade, or addon_downgrade. install your bootstrap script must include an install() function, which the application calls before the first call to startup() after the extension is ins...
...this will be one of addon_install, addon_upgrade, or addon_downgrade. uninstall this function is called after the last call to shutdown() before a particular version of an extension is uninstalled. ...
...And 4 more matches
Browser Detection and Cross Browser Support - Archive of obsolete content
an entire family of user agents based upon the gecko layout engine which includes the commercial browser compuserve 7, and open source browsers such as epiphany, galeon, camino, kmeleon, and seamonkey. gecko was designed from the ground up to be compliant with the w3c html, w3c css, w3c xml, w3c dom, and ecmascript (javascript) standards. it also includes compatibility features which allow it to reasonably handle legacy content which was developed for earlier generations of browsers such as netscape navigator 4 as well as features which provide compatibility with internet explorer 5 and 6. unlike other browsers, gecko is truly cross platform and provides consistent behavior across all supported operating systems. the easiest way to support gecko is to create content which follows web standards...
...ser detection using user agent strings was born. user agent strings are defined in the http protocol and are available to web servers (see rfc 1945 - hypertext transfer protocol 1.0 and rfc 2068 - hypertext transfer protocol 1.1). the most common approach at this time was to distinguish user agents by vendor and version using the reported user agent string. although this approach was considered reasonable at the time, this approach caused problems for browser vendors right from the beginning. the original netscape browsers used a user agent string which began with the code name for the netscape browser followed by its version number, e.g. mozilla/version followed by a comment token which gave additional information regarding the operating system being used, etc. since the earliest browser dete...
...ticular browsers while the period from 1994-2000 was dominated by incompatible non-standard browsers from netscape and microsoft, today the dominating factor in web development are the standards proposed by the world wide web consortium (w3c). standards are important for web developers due to the increased flexibility, power of presentation, support for users with disabilities to name just a few reasons. targeting your web content to particular vendors ignores the possibility that other browsers which support the same standards may be introduced in the future. a common problem on the web today is the assumption that the only browsers in the world are netscape navigator and microsoft internet explorer. this ignores the existence of opera as well as the newer handheld devices which are being use...
...And 4 more matches
Extending a Protocol
the protocol implementation. // the protocol implementation will give us the actual // methods for sending messages, as we will soon see. class echochild final : public pechochild { friend class pechochild; // allows us to participate in reference counting ns_inline_decl_threadsafe_refcounting(echochild, final) public: explicit echochild(); protected: void actordestroy(actordestroyreason awhy) override; // we get sendecho(nscstring& astring) from the superclass. private: ~echochild() = default; bool mactoralive; }; } // end of namespace dom } // end of namespace mozilla and add the echochild.h to dom/ipc/moz.build, as part of the exports.mozilla.dom array. again, remember that this must be in alphabetical order! compiling this will now complain: "fatal error: 'moz...
...again, remember that this must be in alphabetical order! ok, if we now try to compile, it should complain that "error: no member named 'allocpechoparent' in '...
...wglobalchild::deallocpechochild(pechochild* actor) { delete actor; return true; } and now finally, let's implement echochild.cpp and echoparent.cpp. implementing echochild.cpp this is a little one. create dom/ipc/echochild.cpp and implement: #include "echochild.h" namespace mozilla { namespace dom { echochild::echochild() : mactoralive(true) {} void echochild::actordestroy(actordestroyreason awhy) { mactoralive = false; } } // end of namespace dom } // end of namespace mozilla ok, now add 'echochild.cpp' to the unified_sources of dom/ipc/moz.build. remember alphabetical order for the 1000th time! implementing echoparent.cpp and now, we can finally implement dom/ipc/echoparent.cpp. this is the exciting one, as it the one that actually receives the ipc message via recvecho(). ...
...And 3 more matches
Deferred
methods resolve() fulfills the associated promise with the specified value, or propagates the state of an existing promise. if the associated promise has already been resolved, either to a value, a rejection, or another promise,...
...e( avalue ); parameters avalue optional if this value is not a promise, including undefined, it becomes the fulfillment value of the associated promise. 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). reject() rejects the associated promise with the specified reason. ...
...te as the provided promise (including any future transitions). reject() rejects the associated promise with the specified reason. if the promise has already been resolved, either to a value, a rejection, or another promise, this method does nothing. note: this function is bound to its associated promise when promise.defer() is called, and can be called with any value of this. void reject( areason ); parameters areason optional the rejection reason for the associated promise. although the reason can be undefined, it is generally an error object, like in exception handling. note: this argument should not be a promise. specifying a rejected promise would make the rejection reason equal to the rejected promise itself, and not its rejection reason. backwards and forwards compatib...
...And 3 more matches
Rendering and the WebXR frame animation callback - Web APIs
this happens when the amount of time it takes to render a frame exceeds the time available between frames, whether because rendering was delayed or because rendering itself took more time than was available. in the diagram above, frame 3 is dropped because frame 2 did not complete rendering until after frame 3 was due to be painted. the next frame drawn will be frame 4 instead. ...
... fortunately, you can easily compute how much time you're allowed to use between frames as 1/refreshrate seconds. ...
...the visual effect of the top part of the screen showing the new frame, while the bottom part of the frame shows some combination of the previous frame and possibly even the frame before that one. your mission, then, is to keep your code tight and lightweight enough that you don't overrrun the time available to you or otherwise cause dropped frames or excessively abuse the main thread. for these reasons, unless your renderer is fairly small and lightweight, with little to do, you should consider offloading everything you can to a worker so you can be computing the next frame while the browser handles other things. by simply having your computations and data ready before the frame is actually called for, you can make your site or app render much more efficiently, improving main thread performanc...
...And 3 more matches
core/promise - Archive of obsolete content
implementation of promises to make asynchronous programming easier. rationale most of the js apis are asynchronous complementing its non-blocking nature. while this has a good reason and many advantages, it comes with a price. instead of structuring our programs into logical black boxes: function blackbox(a, b) { var c = assemble(a); return combine(b, c); } we're forced into continuation passing style, involving lots of machinery: function sphagetti(a, b, callback) { assemble(a, function continuewith(error, c) { if (error) callback(error); else combine(b, c, callback); }); } this style also makes doing things in sequence hard: widget.on('click', function onclick() { promptuserfortwitterhandle(function continuewith(error, handle) { if (error) return ui.displayerror...
...acks, a function returns an object that represents a eventual result, either successful or failed. this object is a promise, both figuratively and by name, to eventually resolve. we can call a function on the promise to observe either its fulfillment or rejection. if the promise is rejected and the rejection is not explicitly observed, any derived promises will be implicitly rejected for the same reason. 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) { // ... }, function failure(reason) { // ... }); if foo returns a promise that gets fulfilled with the value, success callback (the value hand...
...ntual return (fulfillment) value or thrown exception (rejection): foo().then(function success(value) { // ... }, function failure(reason) { // ... }); if foo returns a promise that gets fulfilled with the value, success callback (the value handler) will be called with that value. however, if the returned promise gets rejected, the failure callback (the error handler) will be called with the reason of an error. propagation the then method of a promise returns a new promise that is resolved with the return value of either handler. since a function can either return a value or throw an exception, only one handler will ever be called. var bar = foo().then(function success(value) { // compute something from a value... }, function failure(reason) { // handle an error... }); in this examp...
...And 2 more matches
Listening for Load and Unload - Archive of obsolete content
to follow this tutorial you'll need to have learned the basics of jpm. 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. you don't have to use exports.main() or exports.onunload(). you can just place your add-on's code at the top level instead of wrapping it in a function assigned to exports.main(). it will be loaded in the same circumstances, but you won't get access to the load/unload reason or arguments. exports.mai...
...ts. if your add-on exports a function called main(), that function will be called immediately after the overall main.js is evaluated, and after all top-level require() statements have run (so generally after all dependent modules have been loaded). exports.main = function (options, callbacks) {}; options is an object describing the parameters with which your add-on was loaded. ...
...exports a function called main(), that function will be called immediately after the overall main.js is evaluated, and after all top-level require() statements have run (so generally after all dependent modules have been loaded). exports.main = function (options, callbacks) {}; options is an object describing the parameters with which your add-on was loaded. ...
...And 2 more matches
Index - Archive of obsolete content
# page tags and summary 1 archive of obsolete content archive, landing here at mdn, we try to avoid outright deleting content that might be useful to people targeting legacy platforms, operating systems, and browsers. perhaps your target audience is people that are using older hardware, for example, and can't upgrade to the latest and greatest browsers. or for "reasons," your company is required to use very old software and you need to build web content that runs on that software. or perhaps you're just curious about the history of an obsolete feature or api, and how it worked. 2 .htaccess ( hypertext access ) 301 redirect, cache control, custom error pages, htaccess, permanent redirect, redirect file accessing : htaccess files can be open...
...while this is generally considered acceptable behavior, considerable care must be taken to avoid violating the mozilla add-on guidelines or creating an adverse user experience. 296 security best practices in extensions add-ons, best practices, extensions, guide, security this document is intended as a guide for develop...
...any of the most common accessibility mistakes will be found and reported. 1815 xul and rdf this page was auto-generated because a user created a sub-page to this page. 1816 the implementation of the application object model outdated_articles purpose - the purpose of this document is two-fold. the first section of the document describes the motivation and reasoning behind using rdf as the foundation of xul. this section makes a technical argument both for having xul in the first place and for using rdf as the underlying implementation of xul's content model. the second section describes the xul/rdf architecture itself and outlines enhancements to the xul language in order to allow the markup language to reference local data and to indicate how and when i...
...And 2 more matches
The Implementation of the Application Object Model - Archive of obsolete content
this section makes a technical argument both for having xul in the first place and for using rdf as the underlying implementation of xul's content model. ...
... of other sites. this same ability to aggregate data leads to another capability of rdf. because rdf can suck up data from a remote location (e.g., from a downloadable rdf file), and also suck up data from a local source, it can take the remote data and combine it with local data. you'll often hear people refer to this as rdf's local/remote merging capability. this capability is desirable for two reasons. what is local/remote merging good for? the first reason to have local/remote merging is that a remote file must be able to reference local data and have it merged in with the information that it specified. an example of this feature is a downloadable file that describes the user's main bookmarks folder. because the file lives remotely, it can be updated whenever the owner of the web site see...
...eature is a downloadable file that describes the user's main bookmarks folder. because the file lives remotely, it can be updated whenever the owner of the web site sees fit. a site admin could add new bookmarks to the file, and then the user would pick them up. however, in order for this to work, the local bookmarks have to be merged in with the remote bookmarks specified by the site. the second reason to have local/remote merging is to save state and/or to record customizations that the user has made to his or her user interface. imagine a remote file that describes the user's personal toolbar. the downloaded file contains an aol instant messenger button, and the user really doesn't want that on the toolbar. now since the aol bookmark was specified by the remote file, the user has no way of go...
...And 2 more matches
Why use RSS - Archive of obsolete content
rss has a huge amount of momentum. ...
... rss has a huge amount of momentum. ...
... rss has a huge amount of momentum. ...
...And 2 more matches
Index - MDN Web Docs Glossary: Definitions of Web-related terms
ment that contains metadata about that document, such as author, description, and links to css or javascript files that should be applied to the html. 203 high-level programming language codingscripting, glossary a high-level programming language has a significant abstraction from the details of computer operation. it is designed to be easily understood by humans and for this reason they must be translated by another software. unlike low-level programming languages, it may use natural language elements, or may automate (or even entirely hide) significant areas of computing systems, making the process of developing simpler and more understandable relative to a lower-level language. the amount of abstraction provided defines how "high-level" a programming language is. 2...
...v4, infrastructure, internet protocol, protocol ipv4 is the fourth version of the communication protocol underlying the internet and the first version to be widely deployed. 221 ipv6 glossary, ipv6, infrastructure, intermediate, web, webmechanics ipv6 is the current version of the communication protocol underlying the internet. slowly ipv6 is replacing ipv4, among other reasons because ipv6 allows for many different ip addresses. 222 irc glossary, infrastructure, internet relay chat, open protocol, irc irc (internet relay chat) is a worldwide chat system requiring an internet connection and an irc client, which sends and receives messages via the irc server. 223 iso glossary, iso, infrastructure, web standards, web specifications ...
...e post method. all safe methods are also idempotent. 227 identifier beginner, codingscripting, glossary, sharing an identifier is a sequence of characters in the code that identifies a variable, function, or property. 228 immutable codingscripting, glossary an immutable object is one whose content cannot be changed. an object can be immutable for various reasons, for example: 229 index glossary, index, mdn meta, navigation found 528 pages: 230 indexeddb api, codingscripting, database, glossary, sql indexeddb is a web api for storing large data structures within browsers and indexing them for high-performance searching. like an sql-based rdbms, indexeddb is a transactional database system. however, it uses javasc...
...And 2 more matches
IPDL Tutorial
e value (e.g. otherfunction above) the parameter is, for both resolve and success callbacks, the returns value itself (as a const reference); if the message returns multiple values (e.g. initasync above), the parameter is, for both resolve and success callbacks, a tuple of the return values (e.g. tuple<bool, bool>). ...
...hand the reject/failure callbacks take a mozilla::ipc::responserejectreason&& and are called in case of a fatal error, such as an ipc error. therefore, besides callback/promise style response handling, these two overloads are functionally equivalent. ...
...on&& and are called in case of a fatal error, such as an ipc error. therefore, besides callback/promise style response handling, these two overloads are functionally equivalent. ...
...And 2 more matches
Index
er for a given crl scope and crl issuer. this extension allows users to easily determine when a particular crl supersedes another crl crlnumber non-critical number where: crlnumber: identifies the name of an extension critical: should be set to 0 since this is non-critical extension number: value of long which identifies the sequential number of a crl. ...
...l issuer. this extension allows users to easily determine when a particular crl supersedes another crl crlnumber non-critical number where: crlnumber: identifies the name of an extension critical: should be set to 0 since this is non-critical extension number: value of long which identifies the sequential number of a crl. ...
...icular crl supersedes another crl crlnumber non-critical number where: crlnumber: identifies the name of an extension critical: should be set to 0 since this is non-critical extension number: value of long which identifies the sequential number of a crl. * add revocation reason code extension: the reasoncode is a non-critical crl entry extension that identifies the reason for the certificate revocation. ...
...And 2 more matches
NSS tools : crlutil
easing sequence number for a given crl scope and crl issuer. this extension allows users to easily determine when a particular crl supersedes another crl crlnumber non-critical number where: crlnumber: identifies the name of an extension critical: should be set to 0 since this is non-critical extension number: value of long which identifies the sequential number of a crl. ...
... given crl scope and crl issuer. this extension allows users to easily determine when a particular crl supersedes another crl crlnumber non-critical number where: crlnumber: identifies the name of an extension critical: should be set to 0 since this is non-critical extension number: value of long which identifies the sequential number of a crl. ...
...y determine when a particular crl supersedes another crl crlnumber non-critical number where: crlnumber: identifies the name of an extension critical: should be set to 0 since this is non-critical extension number: value of long which identifies the sequential number of a crl. * add revocation reason code extension: the reasoncode is a non-critical crl entry extension that identifies the reason for the certificate revocation. ...
...And 2 more matches
NSS Tools crlutil
nd crl issuer. this extension allows users to easily determine when a particular crl supersedes another crl crlnumber non-critical number where: crlnumber: identifies the name of an extension critical: should be set to 0 since this is non-critical extension number: value of long which identifies the sequential number of a crl. ...
...llows users to easily determine when a particular crl supersedes another crl crlnumber non-critical number where: crlnumber: identifies the name of an extension critical: should be set to 0 since this is non-critical extension number: value of long which identifies the sequential number of a crl. ...
...her crl crlnumber non-critical number where: crlnumber: identifies the name of an extension critical: should be set to 0 since this is non-critical extension number: value of long which identifies the sequential number of a crl. add revocation reason code extension: the reasoncode is a non-critical crl entry extension that identifies the reason for the certificate revocation. ...
...And 2 more matches
NSS tools : crlutil
Mozilla › Projects › NSS › tools › crlutil
er for a given crl scope and crl issuer. this extension allows users to easily determine when a particular crl supersedes another crl crlnumber non-critical number where: crlnumber: identifies the name of an extension critical: should be set to 0 since this is non-critical extension number: value of long which identifies the sequential number of a crl. ...
...l issuer. this extension allows users to easily determine when a particular crl supersedes another crl crlnumber non-critical number where: crlnumber: identifies the name of an extension critical: should be set to 0 since this is non-critical extension number: value of long which identifies the sequential number of a crl. ...
...icular crl supersedes another crl crlnumber non-critical number where: crlnumber: identifies the name of an extension critical: should be set to 0 since this is non-critical extension number: value of long which identifies the sequential number of a crl. * add revocation reason code extension: the reasoncode is a non-critical crl entry extension that identifies the reason for the certificate revocation. ...
...And 2 more matches
Window.open() - Web APIs
Web › API › Window › open
location bar or the address bar. if windowfeatures is non-empty, location detaults to off. status if this feature is on, then the new secondary window has a status bar. if windowfeatures is non-empty, status detaults to off. resizable if this feature is on, the new secondary window will be resizable. if windowfeatures is non-empty, resizable detaults to on. ...
...able detaults to on. tip: for accessibility reasons, it is strongly recommended to set this feature always on scrollbars if this feature is on, the new secondary window will show horizontal and/or vertical scrollbar(s) if the document doesn't fit into the window's viewport. if windowfeatures is non-empty, scrollbars detaults to off. see note on scrollbars. tip: for accessibility reasons, it is strongly encouraged to set this feature always on window functionality features noopener if this feature is set, the newly-opened window will open as normal, except that it will not have access back to the originating window (via window.opener — it returns null). in addition, the window.open() call will also return null, so the originating window will not have access to the ne...
...executing a script targeting a secondary window, the browser in the main window will verify that the secondary window has the same domain name. more reading on the cross-domain script security restriction: http://www.mozilla.org/projects/secu...me-origin.html usability issues avoid resorting to window.open() generally speaking, it is preferable to avoid resorting to window.open() for several reasons: most modern desktop browsers offer tab-browsing, and tab-capable browser users overall prefer opening new tabs than opening new windows in a majority of webpage situations. most modern browsers offers a popup-blocking feature. users can be using browser-built-in feature or extensions include opening a link in a new window or not, in the same window, in a new tab or not, in "background" or ...
...And 2 more matches
/loader - Archive of obsolete content
the following built-in pseudo modules in addition to those passed via modules: chrome this pseudo module exposes everything that is typically available for js contexts with system principals under the components global. this alternative approach of providing capabilities via modules makes it possible to build module capability graphs by analyzing require statements. these graphs can be used to reason about modules without diving into implementation details. @loader/options this pseudo module exposes all the options that were used to configure this loader. it enables you to create new loader instances identical to the current one: let { loader } = require('toolkit/loader'); let options = require('@loader/options'); let loader = loader(options); this module is useful in very specific cases.
...server service for defining hooks reacting on the unload of a specific loader. the sdk builds a higher level api on top of this for handling unloads and performing cleanup: let unloadsubject = require('@loader/unload'); let observerservice = cc['@mozilla.org/observer-service;1']. ...
...performing cleanup: let unloadsubject = require('@loader/unload'); let observerservice = cc['@mozilla.org/observer-service;1']. getservice(ci.nsiobserverservice); let observer = { observe: function onunload(subject, topic, reason) { // if this module is unloaded then `subject.wrappedjsobject` will be // `unloadsubject`. `topic` will be `'sdk:loader:destroy'`, and // `reason` will be a string describing the reason (e.g. `'disable'`). ...
...ervice(ci.nsiobserverservice); let observer = { observe: function onunload(subject, topic, reason) { // if this module is unloaded then `subject.wrappedjsobject` will be // `unloadsubject`. `topic` will be `'sdk:loader:destroy'`, and // `reason` will be a string describing the reason (e.g. `'disable'`). if (subject.wrappedjsobject === unloadsubject) console.log("i am about to unload, reason is " + reason); }}; observerservice.addobserver(observer, 'sdk:loader:destroy', false); unload the loader module exposes an unload() function that can be used to unload specific loader instance and undo changes made by modules loaded into it. unload takes loader as a first argument and optionally a reason string identifying the reason why this loader was unloaded. for example in the sdk reaso...
Adding Toolbars and Toolbar Buttons - Archive of obsolete content
r window. the toolbox is the collection of toolbars in firefox, including the main menu bar. let's look at the attributes we used: the toolbarname is the name that will appear on the view > toolbars menulist. this menu allows hiding and showing any toolbar. the customizable attribute determines if the user can customize the toolbar. you should normally set this to true, unless you have strong reasons not to want users changing your toolbar. the mode attribute is set to icons, which is the usual value. this can be changed in the customize dialog by the user. the context attribute should also be set if you want a customizable toolbar. it points to the id of a popup element that holds the customization options that are displayed when the user right-clicks on the toolbar. this popup is already...
...ter shade. on linux, icons are 24x24 pixels by default. since firefox is a gtk application, it uses gtk icons whenever possible. the icons in the image are the ones that aren't provided by gtk. gtk icons are accessed using special urls, like this one: moz-icon://stock/gtk-go-back?size=menu. you can enter this url in firefox on linux, and the corresponding icon will be displayed. this is also the reason this is the only theme that still has colorful icons for its buttons. now let's look at the css work involved in a toolbar that works on the aforementioned systems. if you want your toolbar to look right on all systems, you should consider having different icon sets for each. you should also consider using a graphic designer for this work, as it takes a lot of attention to detail to make good i...
... os-specific entries now use a different package name: xulschoolhello-os. now you just need to be careful about when to use chrome://xulschoolhello/skin/ and when to use chrome://xulschoolhello-os/skin/. it's a bit hacky, but it works well. as for the image files themselves, you may be wondering why it is that all icons are included in a single file instead of having one file for every icon. one reason is that it would be complicated to manage that many files, and it becomes more likely that changes made to some of the files lead to an inconsistent appearance that is not obvious by looking at the individual files. it is easier to be able to edit all icons in one go. there is also a performance gain from using a single file. to get the region that corresponds to a specific state of an icon, the ...
....png"); } #xulschoolhello-hello-world-button { -moz-image-region: rect(0px, 24px, 24px, 0px); } toolbar[iconsize="small"] #xulschoolhello-hello-world-button { list-style-image: url("chrome://xulschoolhello-os/skin/toolbar.png"); -moz-image-region: rect(0px, 16px, 16px, 0px); } several css rules apply by default to all toolbar buttons. these add the button-like look you want. if for some reason you want to override these styles (not recommended), you'll need the following rule: -moz-appearance: none; -moz-appearance can be used in many cases where you want to strip the native look out of an element. this will save you a lot of time trying to remove all the css rules that give the buttons a native look. you'll probably still need to override a couple other css rules to get a completel...
The Essentials of an Extension - Archive of obsolete content
there should...
...alert will say "hello world!" alert(helloitem.getattribute("label")); // wrong helloitem.setattribute("label", "&xulschoolhello.hello2.label;"); // better helloitem.setattribute("label", "alternate message"); // right! ...
...we don't include the insertbefore or insertafter attributes because the ordering of string bundles doesn't make a difference. the element is completely invisible. ...
...ome stat related to the extension. for example: "found 5 words matching the search query". your first idea would probably be to simply concatenate strings, and have one "found" property and another "words matching..." property. this is not a good idea. it greatly complicates the work of localizers, and grammar rules on different languages may change the ordering of the sentence entirely. for this reason it's better to use parameters in the properties: xulschoolhello.search.label = found %s words matching the search query! then you use getformattedstring instead of getstring in order to get the localized string. thanks to this we don't need to have multiple properties, and life is easier for translators. you can read more about it on the text formatting section of the xul tutorial. also hav...
Notes on HTML Reflow - Archive of obsolete content
new reflow state object (based on its container's reflow state object) in which the container will reflow its children. most of the constraints in the new reflow state are computed when the state is created; for example, the available space in the new reflow state is computed by subtracting the container frame's border and padding from the parent reflow state's available space. reflow reason all reflows have a reason , which is maintained in the reflow state object (and may mutate, as described below). the reflow reason controls how a frame reacts during a reflow, and is one of the following: initial, for the very first time that the frame hierarchy is flowed. in this case, a frame knows that there is no residual state that can be used to simplify geometry computation. ...
...tion shell processes the reflow queue by removing a single reflow command from the queue and dispatching it to its target frame. (but cf. the reflow tree work, which will remove several commands from the queue at once.) a path is built from the target frame to the root frame and stored in the reflow command. a reflow state object is created with a reflow reason of incremental, the reflow command is stored in the state, and the reflow method of the root frame is invoked. processing. the root frame notes the incremental reflow reason specified in the reflow state, and inspects the path contained within the reflow command object. specifically, it extracts the next frame along the path from the reflow command object, creates its own reflow state,...
...the incremental reflow proceeds recursively through the frame hierarchy. ...
...t of reflow is the block frame. the block frame treats this sort of change as a `full reflow' (i.e., as a resize). this makes me believe that we could probably eliminate this class altogether. stylechanged indicates that the stylistic information corresponding to the target frame has changed; for example, the font size has increased. this causes the frame to mutate the reflow state's reason to stylechange, which is propagated recursively to the entire subtree beneath the target frame. reflowdirty indicates that container frame has decided to coalesce several incremental reflows targeted at its children into a single reflow. the container frame maintains the necessary state to determine which children must be reflowed. userdefined, for "special situations". currently, this is...
New Skin Notes - Archive of obsolete content
ocs/ now. --dria stuff that's been fixed note that while i've made these fixes, they haven't necessarily been checked in yet. edit page textarea needs to 'scale' better with page width (so large whitespace area's are non-existant), suggest min-width:some-em-size; width: 88%; and max-width set to 95% or something like that. --callek i tried this, but it gets totally screwed up in ie for some reason. i'll try again, but can't guarantee this will be fixed for the initial upgrades. --dria took two days, but i finally got this sorted out. when the skin is updated on test/docs, editform textarea should be resizeable in all browsers. yay! --dria wordpress skins need footer information. -- dria when a page is redirected, need to say-so and what it was redirected from, (see document for an e...
... one currently available here) there's class "wrong" and class "wrong-inline". those will be available after we do the wiki upgrades in the near future. --dria headers need a little padding. h1 could be smaller. --dria is it just me or visited links are not marked as such? --nickolay 07:16, 29 aug 2005 (pdt) imho the visited color looks horrible. we're a documentation site. there's no real reason for user to give him info that he already visited xml main page. it's hardly possible that he'll be interested in it. in all other dev centres there is no "visited link color" and we should remove imho. it looks odd when someone who uses devmo on regular basis sees some violet links just because he already worked with this site yesterday.also, the current color for visited links makes them less v...
...ave the clear:both's in content area without a problem. i understand it might be hard to fix in the skin, but it is very desirable (because we sometimes use the floats and 'clears' in our pages). --nickolay 04:52, 25 aug 2005 (pdt) the clear/boths aren't in the content, they're embedded style information in the .php files in the /includes directory. it's just sloppy coding. i cannot think of any reason for writers or editors to add "clear:both" brs to their document. under what situations does this seem like something that should be embedded directly into the wiki content? --dria when using floated divs - images and such. if you don't use it they overlap with headings, which is something we seldom want. see for example the venkman tutorials (although the clears are down the page) or mdc:freque...
...oper viewing at 800 pixels width ideally in my opinion, i find strange that i'm the only person not too fond of large side bars (or side bars at all, for that matter :) considering that in most articles we scroll down to read the text, and that the side bar scrolls as well, the links aren't there anymore, but the width remains wasted anyway. in the case of a story book, small text columns do seem reasonable, but i don't think this is nice for technical documentation which requires usage of tables, etc... wikipedia's side bar is smaller, btw, probably for the same reasons. since i manage a number of sites for which i must respect quality standards at 800 pixels width for compatibility (we accept break 640 compatibility nowadays except for sites intended for pdas/ppcs), i find myself needing to us...
bootstrap.js - Extensions
the bootstrap.js script should contain several specific functions, which are called by the browser to manage the extension. the script gets executed in a privileged sandbox, which is cached until the extension is shut down. for more information, see bootstrapped extensions. the example below contains the required methods in vsdoc format. ...
...until the extension is shut down. for more information, see bootstrapped extensions. the example below contains the required methods in vsdoc format. ...
...n startup(data, reason) { /// bootstrap data structure @see /docs/extensions/bootstrapped_extensions#bootstrap_data /// string id /// string version /// nsifile installpath /// nsiuri resourceuri /// /// reason types: /// app_startup /// addon_enable /// addon_install /// addon_upgrade /// addon_downgrade } function shutdown(data, reason) { /// bootstrap data structure @see /docs/extensions/bootstrapped_extensions#bootstrap_data /// string id /// string version /// nsifile installpath /// nsiuri resourceuri /// /// reason types: /// app_shutdown /// addon_disable /// addon_uninstall /// addon_upgrade /// addon_downgrade } function install(data, reason) { /// b...
.../// /// reason types: /// app_shutdown /// addon_disable /// addon_uninstall /// addon_upgrade /// addon_downgrade } function install(data, reason) { /// bootstrap data structure @see /docs/extensions/bootstrapped_extensions#bootstrap_data /// string id /// string version /// nsifile installpath /// nsiuri resourceuri /// /// reason types: /// addon_install /// addon_upgrade /// addon_downgrade } function uninstall(data, reason) { /// bootstrap data structure @see /docs/extensions/bootstrapped_extensions#bootstrap_data /// string id /// string version /// nsifile installpath /// nsiuri resourceuri /// /// reason types: /// addon_uninstall /// addon_upgrade ...
CSS and JavaScript accessibility best practices - Learn web development
urce order makes sense, and they can get to it all. absolute positioning (as used in this example) is generally seen as one of the best mechanisms of hiding content for visual effect, because it doesn't stop screen readers from getting to it. on the other hand, you shouldn't use visibility:hidden or display:none, because they do hide content from screen readers. unless of course, there is a good reason why you want this content to be hidden from screen readers. note: invisible content just for screen reader users has a lot more useful detail surrounding this topic. accept that users can override styles accept that users can override your styles it is possible for users to override your styles with their own custom styles, for example: see sarah maddox's how to use a custom style sheet ...
...a custom style sheet (css) with firefox for a useful guide covering how to do this manually in firefox, and how to use a custom style sheet (css) with internet explorer by adrian gordon for the equivalent ie instructions. it is probably easier to do it using an extension, for example the stylish extension is available for firefox, safari, opera, and chrome. users might do this for a variety of reasons. a visually impaired user might want to make the text bigger on all websites they visit, or a user with severe color deficiency might want to put all websites in high contrast colors that are easy for them to see. whatever the need, you should be comfortable with this, and make your designs flexible enough so that such changes will work in your design. as an example, you might want to make sure ...
...text content, good text labels for form elements, or text alternatives, e.g. alt text for images. we also looked at an example of how to use javascript to build in functionality where it is missing — see building keyboard accessibility back in. this is not ideal — really you should just use the right element for the right job — but it shows that it is possible in situations where for some reason you can't control the markup that is used. another way to improve accessibility for non-semantic javascript-powered widgets is to use wai-aria to provide extra semantics for screen reader users. the next article will also cover this in detail. complex functionality like 3d games are not so easy to make accessible — a complex 3d game created using webgl will be rendered on a <canvas> element, w...
... like 3d games are not so easy to make accessible — a complex 3d game created using webgl will be rendered on a <canvas> element, which has no facility at this time to provide text alternatives or other information for severely visually impaired users to make use of. it is arguable that such a game doesn't really have this group of people as a part of its main target audience, and it would be unreasonable to expect you to make it 100% accessible to blind people, however you could implement keyboard controls so it is usable by non-mouse users, and make the color scheme contrasting enough to be usable by those with color deficiencies. the problem with too much javascript the problem often comes when people rely on javascript too much. sometimes you'll see a website where everything has been do...
Fundamental text and font styling - Learn web development
to find a way to know which font is available on the computer used to see our web pages. there is no way to know this in every case, but the web safe fonts are known to be available on nearly all instances of the most used operating systems (windows, macos, the most common linux distributions, android, and ios). ...
..., cursive and fantasy. those are very generic and the exact font face used when using those generic names is up to each browser and can vary for each operating system they are running on. it represents a worst case scenario where the browser will try to do its best to provide at least a font that looks appropriate. serif, sans-serif and monospace are quite predictable and should provide something reasonable. on the other hand, cursive and fantasy are less predictable and we recommend using them very carefully, testing as you go. the five names are defined as follows: term definition example serif fonts that have serifs (the flourishes and other small details you see at the ends of the strokes in some typefaces) my big red elephant sans-serif fonts ...
...sed in code listings. my big red elephant cursive fonts that are intended to emulate handwriting, with flowing, connected strokes. my big red elephant fantasy fonts that are intended to be decorative. my big red elephant font stacks since you can't guarantee the availability of the fonts you want to use on your webpages (even a web font could fail for some reason), you can supply a font stack so that the browser has multiple fonts it can choose from. this simply involves a font-family value consisting of multiple font names separated by commas, e.g. p { font-family: "trebuchet ms", verdana, sans-serif; } in such a case, the browser starts at the beginning of the list and looks to see if that font is available on the machine. if it is, it applies that ...
...} p { font-size: 1.5rem; color: red; font-family: helvetica, arial, sans-serif; } font style, font weight, text transform, and text decoration css provides four common properties to alter the visual weight/emphasis of text: font-style: used to turn italic text on and off. possible values are as follows (you'll rarely use this, unless you want to turn some italic styling off for some reason): normal: sets the text to the normal font (turns existing italics off.) italic: sets the text to use the italic version of the font if available; if not available, it will simulate italics with oblique instead. oblique: sets the text to use a simulated version of an italic font, created by slanting the normal version. font-weight: sets how bold the text is. this has many values...
Index - Learn web development
u are using: 26 what are hyperlinks? beginner, infrastructure, navigation, needsactivelearning hyperlinks, usually called links, are a foundational concept behind the web. to explain what links are, we need to step back to the very basics of web architecture. 27 what do common web layouts contain? beginner, css, design, html, needsactivelearning there's a reason we talk about web design. you start out with a blank page, and you can take it so many directions. and if you don't have much experience, starting out with a blank page might be a bit scary. we have over 25 years' experience and we'll give you some common rules of thumb to help you design your site. 28 what is a domain name? beginner, domain names, infrastructure, intro, needsactiv...
... be tasked with taking some of the knowledge you've picked up in this module's articles and applying it to creating a fun app that generates random silly stories. have fun! 81 storing the information you need — variables arrays, booleans, javascript, numbers, objects, updating, variables, declaring, initializing, l10n:priority, loose typing, strings by now you should know a reasonable amount about javascript variables and how to create them. in the next article, we'll focus on numbers in more detail, looking at how to do basic math in javascript. 82 test your skills: arrays arrays, beginner, javascript, learn, test your skills this aim of this skill test is to assess whether you've understood our arrays article. 83 test your skills: math ...
...ols, cross browser, keyboard hopefully this article has given you a good grounding in the main accessibility problems you might encounter, and how to test and overcome them. 263 implementing feature detection article, beginner, css, codingscripting, javascript, learn, modernizr, testing, tools, cross browser, feature detection this article covered feature detection in a reasonable amount of detail, going through the main concepts and showing you how to both implement your own feature detection tests and use the modernizr library to implement tests more easily. 264 introduction to automated testing article, automation, beginner, codingscripting, learn, sauce labs, testing, tools, web stack, cross browser this was quite a ride, but i'm sure you can s...
...working with user data beginner, featured, forms, guide, html, landing, learn, web this module provides a series of articles that will help you master the essentials of web forms. web forms are a very powerful tool for interacting with users — most commonly they are used for collecting data from users, or allowing them to control a user interface. however, for historical and technical reasons it's not always obvious how to use them to their full potential. in the articles listed below, we'll cover all the essential aspects of web forms including marking up their html structure, styling form controls, validating form data, and submitting data to the server. 309 advanced form styling advanced, css, example, forms, guide, html, web while there are still difficulties...
Graceful asynchronous programming with Promises - Learn web development
ly 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. this is useful for setting up a sequence of async operations to work correctly. this article shows you how promises work, how you'll see them in use with web apis, and how to write your own. prerequisites: basic computer literacy, a reasonable understanding of javascript fundamentals. objective: to understand promises and how to use them. what are promises? we looked at promises briefly in the first article of the course, but here we'll look at them in a lot more depth. essentially, a promise is an object that represents an intermediate state of an operation — in effect, a promise that a result of some kind w...
...aid to be pending. when a promise returns, it is said to be resolved. a successfully resolved promise is said to be fulfilled. it returns a value, which can be accessed by chaining a .then() block onto the end of the promise chain. the executor function inside the .then() block will contain the promise's return value. an unsuccessful resolved promise is said to be rejected. it returns a reason, an error message stating why the promise was rejected. this reason can be accessed by chaining a .catch() block onto the end of the promise chain. running code in response to multiple promises fulfilling the above example showed us some of the real basics of using promises. now let's look at some more advanced features. for a start, chaining processes to occur one after the other is all ...
...dition specified (admittedly, settimeout() doesn't really have a fail condition, so it doesn't matter for this simple example). note: why resolve(), and not fulfill()? the answer we'll give you, for now, is it's complicated. rejecting a custom promise we can create a promise that rejects using the reject() method — just like resolve(), this takes a single value, but in this case, it is the reason to reject with, i.e., the error that will be passed into the .catch() block. let's extend the previous example to have some reject() conditions as well as allowing different messages to be passed upon success. take a copy of the previous example, and replace the existing timeoutpromise() definition with this: function timeoutpromise(message, interval) { return new promise((resolve, reject) =...
...ou'll see the same kind of techniques we discussed above being used there. the following block converts the basic request model used by many indexeddb methods to use promises (see this code, for example). conclusion promises are a good way to build asynchronous applications when we don’t know the return value of a function or how long it will take to return. they make it easier to express and reason about sequences of asynchronous operations without deeply nested callbacks, and they support a style of error handling that is similar to the synchronous try...catch statement. promises work in the latest versions of all modern browsers; the only place where promise support will be a problem is in opera mini and ie11 and earlier versions. we didn't touch on all promise features in this article,...
Storing the information you need — Variables - Learn web development
try these again: myname; myage; you can declare and initialize a variable at the same time, like this: let mydog = 'rover'; this is probably what you'll do most of the time, as it is quicker than doing the two actions on two separate lines. the difference between var and let at this point you may be thinking "why do we need two keywords for defining variables?? why have var and let?". the reasons are somewhat historical. back when javascript was first created, there was only var. this works basically fine in most cases, but it has some issues in the way it works — its design can sometimes be confusing or downright annoying. so, let was created in modern versions of javascript, a new keyword for creating variables that works somewhat differently to var, fixing its issues in the process.
... you use var, you can declare the same variable as many times as you like, but with let you can't. the following would work: var myname = 'chris'; var myname = 'bob'; but the following would throw an error on the second line: let myname = 'chris'; let myname = 'bob'; you'd have to do this instead: let myname = 'chris'; myname = 'bob'; again, this is a sensible language decision. there is no reason to redeclare variables — it just makes things more confusing. for these reasons and more, we recommend that you use let as much as possible in your code, rather than var. there is no reason to use var, unless you need to support old versions of internet explorer with your code (it doesn't support let until version 11; the modern windows edge browser supports let just fine). updating a variabl...
...f — this returns the data type of the variable you type after it. the first time it is called, it should return string, as at that point the mynumber variable contains a string, '500'. have a look and see what it returns the second time you call it. constants in javascript many programming languages have the concept of a constant — a value that once declared can't be changed. there are many reasons why you'd want to do this, from security (if a third party script changed such values it could cause problems) to debugging and code comprehension (it is harder to accidentally change values that shouldn't be changed and mess things up). in the early days of javascript, constants didn't exist. in modern javascript, we have the keyword const, which lets us store values that can never be changed:...
...a new value. in the following example, the second line would throw an error: const daysinweek = 7; daysinweek = 8; test your skills! you've reached the end of this article, but can you remember the most important information? you can find some further tests to verify that you've retained this information before you move on — see test your skills: variables. summary by now you should know a reasonable amount about javascript variables and how to create them. in the next article, we'll focus on numbers in more detail, looking at how to do basic math in javascript. previous overview: first steps next in this module what is javascript? the first splash into javascript what went wrong? troubleshooting javascript storing the information you need — variables basic math in java...
Properly configuring server MIME types - Learn web development
d web servers and applications by guessing what the correct mime type should be. this has sheltered many web administrators from their own errors, since internet explorer will continue to process content as expected even though the web server is misconfigured, e.g. displays an image which is reported to be plain text. ...
...if your stylesheet comes from a different origin than the document, you must serve it with the correct mime type (text/css). ...
...stic that allows the load if the first line in the style sheet appears to be a well-formed css construct; the heuristic has been removed in firefox 4, and you have to properly set the text/css mime types to have your css pages recognized. why browsers should not guess mime types apart from violating the http specification, it is a bad strategy for browsers to guess mime types for the following reasons: loss of control if the browser ignores the reported mime type, web administrators and authors no longer have control over how their content is to be processed. for example, a web site oriented for web developers might wish to send certain example html documents as either text/html or text/plain in order to have the documents either processed and displayed as html or as source code. if the br...
...xample, a web site oriented for web developers might wish to send certain example html documents as either text/html or text/plain in order to have the documents either processed and displayed as html or as source code. if the browser guesses the mime type, this option is no longer available to the author. security some content types, such as executable programs, are inherently unsafe. for this reason these mime types are usually restricted in terms of what actions a web browser will take when given content of that type. an executable program should not be executed on the user's computer and at most should cause a dialog to appear asking the user if they wish to download the file. mime type guessing has led to security exploits in internet explorer which were based upon a malicious author inc...
Handling common accessibility problems - Learn web development
le with disabilities, and how they use the web. we've already talked about other spheres such as responsive design and performance in other places in the module. note: like many things in web development, accessibility isn't about 100% success or not; 100% accessibility is pretty much impossible to achieve for all content, especially as sites get more complex. instead, it is more about making a reasonable effort to make as much of your content accessible to as many people as possible via defensive coding and sticking to best practices. common accessibility issues in this section we'll detail some of the main issues that arise around web accessibility, connected with specific technologies, along with best practices to follow, and some quick tests you can do to see if your sites are going in ...
...example, if you want bigger text, use font-size, not an <h1> element. make sure your source order makes sense without css; you can always use css to style the page any way you want afterward. you should make sure interactive elements like buttons and links have appropriate focus/hover/active states set, to give the user visual clues as to their function. if you remove the defaults for stylistic reasons, make sure you include some replacement styles. there are a few other considerations you should take into account. color and color contrast when choosing a color scheme for your website, you should make sure that the text (foreground) color contrasts well with the background color. your design might look cool, but it is no good if people with visual impairments like color blindness can't rea...
...ource order makes sense, and they can get to it all. absolute positioning (as used in this example) is generally seen as one of the best mechanisms of hiding content for visual effect, because it doesn't stop screen readers from getting to it. on the other hand, you shouldn't use visibility:hidden or display:none, because they do hide content from screenreaders. unless of course, there is a good reason why you want this content to be hidden from screenreaders. note: invisible content just for screen reader users has a lot more useful detail surrounding this topic. javascript javascript has the same kind of problems as css with respect to accessibility — it can be disastrous for accessibility if used badly, or overused. we've already hinted at some accessibility problems related to javasc...
...t are accessible to keyboard-only users (as we said earlier, the default browser controls aren't keyboard-accessible in most browsers). note: webaim's accessible javascript provides some useful further details about considerations for accessible javascript. more complex javascript implementations can create issues with accessibility — you need to do what you can. for example, it would be unreasonable to expect you to make a complex 3d game written using webgl 100% accessible to a blind person, but you could implement keyboard controls so it is usable by non-mouse users, and make the color scheme contrasting enough to be usable by those with color deficiencies. complex functionality one of the main areas problematic for accessibility is complex apps that involve complicated form controls...
Introduction to automated testing - Learn web development
task is written in the same basic format — gulp's task() method is run, and given two parameters — the name of the task, and a callback function containing the actual code to run to complete the task. you can run your gulp task with the following commands — try this now: gulp adding some real tasks to gulp to add some real tasks to gulp, we need to think about what we want to do. a reasonable set of basic functionalities to run on our project is as follows: html-tidy, css-lint, and js-hint to lint and report/fix common html/css/js errors (see gulp-htmltidy, gulp-csslint, gulp-jshint). autoprefixer to scan our css and add vendor prefixes only where needed (see gulp-autoprefixer). babel to transpile any new javascript syntax features to traditional syntax that works in older br...
....hashed_id; request({uri: baseurl + "builds/" + buildid + "/sessions.json"}, function(err, res, body){ console.log(json.parse(body)); }); /* response: [ { automation_session: { name: <string>, duration: <int>, os: <string>, os_version: <string>, browser_version: <string>, browser: <string>, device: <string>, status: <string>, hashed_id: <string>, reason: <string>, build_name: <string>, project_name: <string>, logs: <string>, browser_url: <string>, public_url: <string>, video_url: <string>, browser_console_logs_url: <string>, har_logs_url: <string> } }, { automation_session: { name: <string>, duration: <int>, os: <string>, os_version: <string>, browser_version: <string>, browser: <...
... ] */ } function getsessiondetails(session){ let sessionid = session.automation_session.hashed_id; request({uri: baseurl + "sessions/" + sessionid + ...
... testingbot getting started with testingbot let's get s...
IME handling guide
. in this case, using the last composition string as commit string. however, if the last composition string is only an ideographic space (fullwidth space), the composition string may be a placeholder of some old chinese ime on windows. in this case, although, we should not commit the placeholder character because it's not a character which the user wanted to input but we commit it as is. the reason is, inputting an ideographic space causes a composition. therefore, we cannot distinguish if committing composition is unexpected. if the user uses such old chinese ime, "intl.ime.remove_placeholder_character_at_commit" pref may be useful but we don't support them anymore in default settings (except if somebody will find a good way to fix this issue). the composition is committed synchronously b...
... native password field has focus. this state is set only when <input type="password"> (ime-mode: auto;), <input type="text" style="ime-mode: disabled;"> or <textarea style="ime-mode: disabled;">. plugin this is set only when a windowless plugin has focus. be careful, even if a password field has focus, mimestate may be enabled. when you need to check if a password field has focus for security reasons, you should use inputcontext::ispasswordeditor(). the other is ime open state: dont_change_open_state the open state of ime shouldn't be changed. i.e., gecko should keep the last ime open state. open open ime. this is specified only when ime-mode of the new focused element is active. close close ime. this is specified only when ime-mode of the new focused element is inactive. e.g., on ...
...lement is active. close close ime. this is specified only when ime-mode of the new focused element is inactive. e.g., on linux, applications cannot manage ime open state. on such platforms, this is ignored. ime open state should be changed only when nsiwidget::setinputcontext() is called at dom focus change because changing ime open state while an editor has focus makes users confused. the reason why nsiwidget::setinputcontext() is called is stored in inputcontextaction::mcause. how does gecko disable ime in imm mode on windows every window on windows is associated an imcontext. when gecko disables ime, mozilla::widget::imehandler::setinputcontext() disasociates the context from the window. how does gecko disable ime in tsf mode on windows mozilla::widget::tsftextstore sets focus to ...
... dispatched widgetcompositionevents (they are notified synchronously in chrome or non-e10s mode, but asynchronously from a remote process in e10s mode). at this time, tsftextstore may receive notifications which indicates web application changes the content differently from cache in tsftextstore. however, tsftextstore ignores such fact temporarily until the composition is finished completely. the reason is that, notifying unexpected text or selection changes to tsf and/or tip during composition may behave them odd. when a composition is committed and it receives notify_ime_of_composition_event_handled, tsftextstore clears the cache of contents and notifying tsf of merged text changes and the last selection change if they are not caused by composition. by this step, tsf and tip may sync its inte...
Gecko Profiler FAQ
ranges (it won’t work on windows.) high frequency sampling may also be an area where native profilers are a useful alternative tool to try. how do we profile "leaks" that show up after running firefox for > 40 mins? the gecko profiler has been designed specifically for the use case of having it run always in the background, and it’s pretty good at that! it is quite reasonable to actually run the browser for 40 minutes and once the said leaks have happened capture the profiles and study what went wrong. [ehsan] i have been profiling my real browser usage for months now, and so can you. :-) however, if it’s really just “leaks” that are the problem, it’s possible that those profiles only show you that we spend a lot of time in gc / cc...
...page faults? (i.e. when we are accessing a virtual memory page that needs to reload from disk) the gecko profiler does not know about page faults. on linux, perf does a good job at visualizing page faults, for example, they will show up as part of the same call stack as the user-space call stack for the program you are profiling. ...
... complicated is to find out the reason the page has been purged? ...
... typically we wouldn’t be optimizing away a single page fault anyway. ...
Python binding for NSS
. exception error messages now include pr error text if available. ...
...ed_cert_der pkcs12decodeitem.type signeddata.data signeddata.der the following module functions were added nss.nss.dump_certificate_cache_info() nss.nss.find_slot_by_name() nss.nss.fingerprint_format_lines() nss.nss.get_internal_slot() nss.nss.is_fips() nss.nss.need_pw_init() nss.nss.nss_init_read_write() nss.nss.pk11_disabled_reason_name() nss.nss.pk11_disabled_reason_str() nss.nss.pk11_logout_all() nss.nss.pkcs12_cipher_from_name() nss.nss.pkcs12_cipher_name() nss.nss.pkcs12_enable_all_ciphers() nss.nss.pkcs12_enable_cipher() nss.nss.pkcs12_export() nss.nss.pkcs12_map_cipher() nss.nss.pkcs12_set_nickname_collision_callback() nss.nss.pkcs12_set_preferred_cipher() nss.nss...
...ssl, connection class, http class usage the following classes were added: authkeyid basicconstraints crldistributionpoint crldistributionpts certificateextension generalname signedcrl dn rdn ava certificaterequest the following module functions were added: nss.nss.nss_is_initialized() nss.nss.cert_crl_reason_from_name() nss.nss.cert_crl_reason_name() nss.nss.cert_general_name_type_from_name() nss.nss.cert_general_name_type_name() nss.nss.cert_usage_flags() nss.nss.decode_der_crl() nss.nss.der_universal_secitem_fmt_lines() nss.nss.import_crl() nss.nss.make_line_pairs() nss.nss.oid_dotted_decimal() nss.nss.oid_str() nss.nss.oid_tag() nss.nss.o...
...method if the name is suffixed with (), a propety otherwise socket.next() socket.readlines() socket.sendall() sslsocket.next() sslsocket.readlines() sslsocket.sendall() authkeyid.key_id authkeyid.serial_number authkeyid.get_general_names() crldistributionpoint.issuer crldistributionpoint.get_general_names() crldistributionpoint.get_reasons() certdb.find_crl_by_cert() certdb.find_crl_by_name() certificate.extensions certificateextension.critical certificateextension.name certificateextension.oid certificateextension.oid_tag certificateextension.value generalname.type_enum generalname.type_name generalname.type_string secitem.der_to_hex() secitem.get_oid_sequence() ...
Index
Mozilla › Tech › XPCOM › Index
rs must call exactly one method if nsiauthprompt2.asyncpromptauth() returns successfully. they must not call any method on this interface before nsiauthprompt2.asyncpromptauth() returns. 347 nsiauthpromptprovider authentication, interfaces, interfaces:scriptable, xpcom, xpcom api reference, xpcom interface reference this method requests a prompt interface for the given prompt reason. 348 nsiauthpromptwrapper authentication, interfaces, interfaces:scriptable, xpcom, xpcom api reference, xpcom interface reference the nsiauthpromptwrapper interface is an override of nsiauthprompt which performs some action on the data going through nsiauthprompt methods. persisting data from the prompts and using it to pre-fill subsequent prompts would be one such action. ...
... xpcom interface reference initialize this pipe. 827 nsiplacesimportexportservice bookmarks, interfaces, interfaces:scriptable, places, xpcom interface reference in the past, this interface also offered methods for importing places data, but those methods are now part of the bookmarkhtmlutils.jsm javascript code module. the interface name has been kept for compatibility reasons for code using the export service. 828 nsiplacesview developing mozilla, interfaces, places, xpcom the nsiplacesview interface provides a view-agnostic way to access information about a places view. 829 nsipluginhost interfaces, interfaces:scriptable, needscontent, reference, référence(2), xpcom, xpcom interface reference to create temp file with conte...
... interfaces:scriptable, xpcom, xpcom interface reference notifies the object that an interface pointer has been duplicated. 931 addref documentation is now located at nsisupports.addref(). 932 release documentation is now located at nsisupports.release(). 933 nsisupports proxies needshelp, needsupdate, obsolete, xpcom the main reason for nsisupports proxies is that javascript and ui are on a single thread. when one is busy, the other is blocked. a good example of this is the old install.js scripts that were used in xpinstall in older mozilla versions. they from the majority of javascript code, which is small and can be quickly run. xpinstall installation scripts are sometimes very complex and can require long execution time d...
... called when the update check is completed. 1044 nsiupdatechecker interfaces, interfaces:scriptable, update service, xpcom, xpcom api reference, xpcom interface reference checks for available updates, notifying a listener of the results. 1045 nsiupdateitem constants representing types of update checks. constants that callers can use to indicate the reason for an add-on update check. internal code uses other constants in nsextensionmanager.js.in. 1046 nsiupdatemanager interfaces, interfaces:scriptable, update service, xpcom, xpcom api reference, xpcom interface reference returns the update at the specified index into the history list. 1047 nsiupdatepatch interfaces, interfaces:scriptable, xpcom, xpcom api referen...
nsIDownloadManagerUI
ownload manager. if you wish to replace the default download manager user interface, implement this interface. ...
...w void getattention(); void show([optional] in nsiinterfacerequestor awindowcontext, [optional] in unsigned long aid, [optional] in short areason); attributes attribute type description visible boolean true if the download manager ui is visible; otherwise false. read only. constants constant value description reason_user_interacted 0 when opening the download manager user interface, this value indicates that it's being done at the user's request. reason_new_download 1 when opening the download manager user interface, this value indicates that the user interface is being displayed because a new download is being started. methods getattention() calls attention to the download mana...
... already open. the ui need not be visible to call this function, nor will the ui be made visible. void getattention(); parameters none. exceptions thrown ns_error_unexpected the user interface isn't currently open. show() shows the download manager's user interface to the user. ...
...cerequestor awindowcontext, optional in unsigned long aid, optional in short areason optional ); parameters awindowcontext optional the parent window context to show the user interface. with this information, it's possible to put the download manager in a tab in the same window as the parent. aid optional the id of the download to be preselected upon opening the download manager ui. areason optional one of the reason constants indicating why the user interface should be displayed. see also the download manager schema ...
nsIProtocolProxyService
proxy auto config (pac) ...
...aflags a bit-wise combination of the resolve_ flags defined above. pass 0 to specify the default behavior. any additional bits that do not correspond to a resolve_ flag are reserved for future use. acallback the object to be notified when the result is available. return value an nsicancelableobject that can be used to cancel the asynchronous operation. if canceled, the cancellation status (areason) will be forwarded to the callback's nsiprotocolproxycallback.onproxyavailable() method via the astatus parameter. newproxyinfo() this method may be called to construct a nsiproxyinfo instance from the given parameters. this method may be useful in conjunction with nsisockettransportservice.createtransport() for creating, for example, a socks connection. nsiproxyinfo newproxyinfo( in acstrin...
...nds) to ignore this proxy if this proxy fails. pass pr_uint32_max to specify the default timeout value, causing nsiproxyinfo::failovertimeout to be assigned the default value. afailoverproxy specifies the next proxy to try if this proxy fails. this parameter may be null. return value an nsiproxyinfo object. getfailoverforproxy() if the proxy identified by aproxyinfo is unavailable for some reason, this method may be called to access an alternate proxy that may be used instead. as a side-effect, this method may affect future result values from resolve/asyncresolve as well as from getfailoverforproxy. nsiproxyinfo getfailoverforproxy( in nsiproxyinfo aproxyinfo, in nsiuri auri, in nsresult areason ); parameters aproxyinfo the proxy that was unavailable. auri the uri that was ...
...this value may be used to tune the delay before this proxy is used again. ...
Storage
. executing a statement you may execute statements either synchronously (which is supported in firefox gecko 1.8 and 1.9) or asynchronously (starting in gecko 1.9.1). if your code needs to work with applications based on gecko 1.8 or 1.9, you should the technique covered in the section synchronously below. otherwise, it's strongly recommended that you use asynchronous execution, for performance reasons. asynchronously gecko 1.9.1 introduced support for asynchronous execution of a statement by calling mozistoragestatement.executeasync() on the statement. multiple statements can be executed in a transaction by calling mozistorageconnection.executeasync() on the connection and passing in an array of statements. both of these methods have similar signatures that accept an object as input that ...
...see its documentation for more details on each method. the callback is optional, however, so if you do not want to receive feedback, you can pass nothing. synchronously...
...see its documentation for more details on each method. the callback is optional, however, so if you do not want to receive feedback, you can pass nothing. synchronously if you are ok wit...
...see its documentation for more details on each method. the callback is optional, however, so if you do not want to receive feedback, you can pass nothing. synchronously if you are ok with the possibility of locking up your user interface, or if yo...
Getting Started Guide
is shorter, cleaner, clearer, and safer, than you can with raw xpcom interface pointers. xpcom basics: ownership and reference counting this is a quick refresher on some fundamental issues of xpcom. you should already know this, and should be able to just skim this short section. if this is unfamiliar material, you're not ready for nscomptrs yet. a good place to learn about the basic rules and reasoning behind com is in essential com by don box. don box gets into more of the details, traps, and pitfalls of com in effective com. you should also have a reasonable knowledge of c++. probably the three most helpful books on this topic are the c++ programming language by bjarne stroustrup, effective c++, and more effective c++ by scott meyers. all xpcom objects are allocated on the heap. clients d...
...omatically |release|s the old value in |mfooptr|, if any, and |addref|s the new one, in the appropriate sequence to avoid the ownership bug mentioned earlier. */ mfooptr = afooptr; additionally, the class using raw xpcom interface pointers will need a destructor to release mfooptr; and a constructor to ensure that mfooptr is initially set to null (or some other reasonable value). nscomptr helps you write code that is leak-proof, exception safe, and significantly less verbose than you would with raw xpcom interface pointers. with nscomptr, you may never have to call addref, release, or queryinterface by hand. you still have to understand xpcom. you still have to know which functions return interface pointers that have already been addrefed and which don't. yo...
... remember, the c++ type system and the xpcom type system are really two independent things. because xpcom interfaces are expressed as abstract c++ base classes, you may be tempted to let c++ handle the differences, or to use c++ casts to navigate between interface types. this is wrong. the only sanctioned way to get between xpcom types is with queryinterface. in the example above, there is no reason to assume that the nsifoo* c++ pulls out of p would be the same one that p->queryinterface() would return. dont_addref is a similar directive that helps you when you assign in a pointer that has already been addrefed, e.g., because you called a getter that returned the pointer as its function result. using dont_addref. nscomptr<nsifoo> foo(dont_addref(createfoo())); // |create...
...ptr to call it with do_queryinterface. the do_queryinterface directive allows you to do the query as part of the assignment. this better facilitates constructing an nscomptr directly from the right value, rather than constructing it and assigning in the correct value later. construction alone is more efficient than construction followed by assignment. prefer construction over assignment whereever reasonable. be careful not to apply do_queryinterface to a function returning an addrefed pointer (see this short section for an explanation) for more details, continue on to the reference manual. ...
Reference Manual
here is a sample demonstrating the various positions these `annotations' can appear in, using dont_addref // controlling assignment into an |nscomptr|... // in constructors... nscomptr<nsifoo> foo1( dont_addref(rawfoo1ptr) ); nscomptr<nsifoo> foo2 = dont_addref(rawfoo2ptr); // note that t...
...ructors and assignment operators. // raw xpcom interface pointers... nsifoo* foo; getfoo(&foo); getfoo2(foo); getsomething((void**)&foo); // |nscomptr|s... nscomptr<nsifoo> foo; getfoo(getter_addrefs(foo)); getfoo2(*getter_addrefs(foo)); getsomething(getter_addrefs(foo)); why not just overload operator& to do this work? several reasons: it would become inconvenient take the address of an nscomptr in all other situations; the name "getter_addrefs" enforces the notion that a certain behavior is required of the getter; and once upon a time, there was another possibility (as you're about to learn). is there a getter_doesnt_addref( nscomptr& ) for getters that return non-addrefed results through a parameter? no, there isn't. once u...
...f an nscomptr in all other situations; the name "getter_addrefs" enforces the notion that a certain behavior is required of the getter; and once upon a time, there was another possibility (as you're about to learn). is there a getter_doesnt_addref( nscomptr& ) for getters that return non-addrefed results through a parameter? no, there isn't. once upon a time, there was, but it went away for three reasons: it is against the rules of xpcom for a getter to return a non-addrefed interface pointer through a parameter (if you see it, report a bug). getter_doesnt_addref had complex ramifications that ended up making nscomptrs either bigger or slower than raw xpcom interface pointers. you can still call such a getter and put the result into an nscomptr with a temporary, e.g., ...
... by-passed, cause any extra run-time cost for nscomptr over raw xpcom interface pointers. space and time trade-offs are finely balanced in nscomptr. the factored routines are the direct result of bloat measurements. prefer construction to assignment the most efficient way, in both time and space, to get a value into an nscomptr is at construction time. prefer construction over assignment whenever reasonable. initialize member nscomptrs in the member initialization clause of your constructor. // initialize member |nscomptr|s in the member initialization clause of your // constructor... class bar { public: bar( nsifoo* initial_fooptr ); // ... private: nscomptr<nsifoo> mfooptr; }; bar::bar( nsifoo* initial_fooptr ) : mfooptr(initial_foo...
FileSystemFlags - Web APIs
this option has no effect.ie no support noopera no support nosafari no support nowebview android full support yesprefixed full support ...
...this option has no effect.opera android no support nosafari ios no support nosamsung internet android full support yesprefixed full support yesprefixed prefixed implemented wi...
...this option has no effect.ie no support noopera no support nosafari no support nowebview android full support yesprefixed full support ...
...this option has no effect.opera android no support nosafari ios no support nosamsung internet android full support yesprefixed full support yesprefixed prefixed implemented wi...
PromiseRejectionEvent() - Web APIs
ng representing the name of the type of the promiserejectionevent. this is case-sensitive and should be one of "rejectionhandled" or "unhandledrejection", to match the event names of the possible (non-synthetic) promiserejectionevent events that user agents can actually fire). options an object specifying details about the rejection which occurred: promise the promise that was rejected. reason any value or object which represents the reason the promise was rejected. this can be anything from a numeric error code to an error domstring to an object which contains detailed information describing the situation resulting in the promise being rejected. return value a new promiserejectionevent configured as specified by the parameters. examples this example creates a new unhandledr...
... the promise was rejected. this can be anything from a numeric error code to an error domstring to an object which contains detailed information describing the situation resulting in the promise being rejected. return value a new promiserejectionevent configured as specified by the parameters. ...
...m a numeric error code to an error domstring to an object which contains detailed information describing the situation resulting in the promise being rejected. return value a new promiserejectionevent configured as specified by the parameters. examples this example creates a new unhandledrejection event for the promise mypromise with the reason being the string "my house is on fire". ...
...n event for the promise mypromise with the reason being the string "my house is on fire". the reason could just as easily be a number, or even an object with detailed information including the home address, how serious the fire is, and the phone number of an emergency contact who should be notified. let myrejectionevent = new promiserejectionevent("unhandledrejection", { promise : mypromise, reason : "my house is on fire" }); specifications specification status comment html living standardthe definition of 'the promiserejectionevent interface' in that specification. living standard initial definition. ...
:visited - CSS: Cascading Style Sheets
Web › CSS › :visited
the :visited css pseudo-class represents links that the user has already visited. for privacy reasons, the styles that can be modified using this selector are very limited. /* selects any <a> that has been visited */ a:visited { color: green; } styles defined by the :visited pseudo-class will be overridden by any subsequent link-related pseudo-class (:link, :hover, or :active) that has at least equal specificity. to style links appropriately, put the :visited rule after the :link rule but before the :hover and :active rules, as defined by the lvha-order: :link — :visited — :hover — :active. ...
...n; } styles defined by the :visited pseudo-class will be overridden by any subsequent link-related pseudo-class (:link, :hover, or :active) that has at least equal specificity. to style links appropriately, put the :visited rule after the :link rule but before the :hover and :active rules, as defined by the lvha-order: :link — :visited — :hover — :active. styling restrictions for privacy reasons, browsers strictly limit which styles you can apply using this pseudo-class, and how they can be used: allowable css properties are color, background-color, border-color, border-bottom-color, border-left-color, border-right-color, border-top-color, column-rule-color, outline-color, text-decoration-color, and text-emphasis-color. allowable svg attributes are fill and stroke. the alpha compon...
...onent of the element's non-:visited state will be used instead, except when that component is 0, in which case the style set in :visited will be ignored entirely. although these styles can be change the appearance of colors to the end user, the window.getcomputedstyle method will lie and always return the value of the non-:visited color. note: for more information on these limitations and the reasons behind them, see privacy and the :visited selector. syntax :visited examples properties that would otherwise have no color or be transparent cannot be modified with :visited. of the properties that can be set with this pseudo-class, your browser probably has a default value for color and column-rule-color only. thus, if you want to modify the other properties, you'll need to give them a bas...
...on of ':visited' in that specification. working draft no change. selectors level 3the definition of ':visited' in that specification. recommendation no change. css level 2 (revision 1)the definition of ':visited' in that specification. recommendation lifts the restriction to only apply :visited to the <a> element. lets browsers restrict its behavior for privacy reasons. css level 1the definition of ':visited' in that specification. recommendation initial definition. browser compatibility the compatibility table on this page is generated from structured data. if you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. desktopmobilechromeedgefirefoxinternet exploreropera...
Relationship of flexbox to other layout methods - CSS: Cascading Style Sheets
ss became a more feature rich language, maintaining one huge specification became problematic, with different parts of css moving on at different speeds. css was therefore modularised, and the various css specifications are different modules that make up css today. these modules relate to each other, and are at different stages of development. the box alignment module for many people the first reason they start to look at flexbox is because of the ability to properly align flex items inside a flex container. flexbox provides access to properties that allow the alignment of items on their cross axis and justification of items on the main axis. these properties started life in the flexbox specification, but are now also part of the box alignment specification. this specification details how al...
...llow the alignment of items on their cross axis and justification of items on the main axis. these properties started life in the flexbox specification, but are now also part of the box alignment specification. this specification details how alignment works in all layout — not just flexbox. box alignment deals with alignment and justification, and also distribution of space along an axis. the reason that the box alignment properties remain detailed in the flexbox specification as well as being in box alignment is to ensure that completion of the flexbox spec is not held up by box alignment, which has to detail these methods for all layout types. there is a note in the flexbox spec stating that in the future, once it is completed, the definitions in box alignment level 3 will supersede those ...
...tion, which details how css supports the various different writing modes that exist internationally. we need to be aware of how this will impact our flex layouts as writing mode changes the direction that blocks are laid out in our document. understanding block and inline directions is key to new layout methods. it is worth noting that we might want to change the writing mode of our document for reasons other than publishing content in a language that uses a different writing mode. see this article for a full description of writing modes and ways to use them, both for content in other languages and for creative reasons. the writing modes the writing modes specification defines the following values of the writing-mode property, which serve to change the direction that blocks are laid out on t...
... we are removing has an orange background colour. this also disappears when the box disappears. browser support for display:contents is limited and required for this demo to work. firefox supports display: contents already, and the value is being implemented in chrome. once there is better browser support this feature will be very useful in circumstances where you need the markup for semantic reasons but do not want to display the box that it would generate by default. ...
Event reference
itionupdate a character is added to a passage of text being composed. compositionend the composition of a passage of text has been completed or canceled. view events event name fired when fullscreenchange an element was toggled to or from fullscreen mode. fullscreenerror it was impossible to switch to fullscreen mode for technical reasons or because the permission was denied. resize the document view has been resized. scroll the document view or an element has been scrolled. clipboard events event name fired when cut the selection has been cut and copied to the clipboard copy the selection has been copied to the clipboard paste the item from t...
... has the listener attached or onto one of its children. mouseout a pointing device is moved off the element that has the listener attached or off one of its children. mouseup a pointing device button is released over an element. pointerlockchange the pointer was locked or released. pointerlockerror it was impossible to lock the pointer for technical reasons or because the permission was denied. select some text is being selected. wheel a wheel button of a pointing device is rotated in any direction. drag & drop events event name fired when drag an element or text selection is being dragged (fired continuously every 350ms). dragend a drag operation is being ended (by releasi...
... focusin focusevent dom l3 an element is about to receive focus (bubbles). focusout focusevent dom l3 an element is about to lose focus (bubbles). fullscreenchange event full screen an element was toggled to or from fullscreen mode. fullscreenerror event full screen it was impossible to switch to fullscreen mode for technical reasons or because the permission was denied. gamepadconnected gamepadevent gamepad a gamepad has been connected. gamepaddisconnected gamepadevent gamepad a gamepad has been disconnected. gotpointercapture pointerevent pointer events element receives pointer capture. hashchange hashchangeevent html5 the fragment identifier of th...
...revent pointer events pointing device is moved inside the hit-testing boundary. pointerleave pointerevent pointer events pointing device is moved out of the hit-testing boundary. pointerlockchange event pointer lock the pointer was locked or released. pointerlockerror event pointer lock it was impossible to lock the pointer for technical reasons or because the permission was denied. pointermove pointerevent pointer events the pointer changed coordinates. pointerout pointerevent pointer events the pointing device moves out of the hit-testing boundary or leaves detectable hover range. pointerover pointerevent pointer events the pointing device is moved into the hit-testing boundary. ...
Browser detection using the user agent - HTTP
; blink; opera). browser makers do pay attention to bug reports, and the analysis may hint about other workarounds for the bug. are you trying to check for the existence of a specific feature? your site needs to use a specific web feature that some browsers don't yet support, and you want to send those users to an older web site with fewer features but that you know will work. this is the worst reason to use user agent detection because odds are eventually all the other browsers will catch up. in addition, it is not practical to test every one of the less popular browsers and test for them. you should never do user agent sniffing. there is always the alternative of doing feature detection instead. do you want to provide different html depending on which browser is being used? this is usua...
...ing that syntax throws and // islookbehindsupported remains false. } var splitupstring = islookbehindsupported ? function(str) { return (""+str).split(new regexp("(?<=[a-z])")); } : function(str) { return str.replace(/[a-z]/g,"z$1").split(/z(?=[a-z])/g); }; as the above code demonstrates, there is always a way to test browser support without user agent sniffing. there is never any reason to check the user agent string for this. lastly, the above code snippets bring about a critical issue with cross-browser coding that must always be taken into account. don't unintentionally use the api you are testing for in unsupported browsers. this may sound obvious and simple, but sometimes it is not. for example, in the above code snippets, using lookbehind in short-regexp notation (e.g. /...
...e page's content together meaningfully. although it is off-topic, perhaps the following detailed example might give you insights and ideas that persuade you to forgo user agent sniffing. let us imagine a page composed of boxes of information; each box is about a different feline breed or canine breed. each box has an image, an overview, and a historical funfact. the pictures are kept to a maximum reasonable size even on large screens. for the purposes of grouping the content meaningfully, all the cat boxes are separated from all the dog boxes such that the cat and dog boxes are not intermixed together. on a large screen, it saves space to have multiple columns to reduce the space wasted to the left and to the right of the pictures. the boxes can be separated into multiple columns via two equally...
...ut also often its version and information on the relying hardware (32 or 64 bits, or intel/ppc for mac). like in all cases, these strings may change in the future, one should use them only in conjunction with the detection of already released browsers. a technological survey must be in place to adapt the script when new browser versions are coming out. mobile, tablet or desktop the most common reason to perform user agent sniffing is to determine which type of device the browser runs on. the goal is to serve different html to different device types. never assume that a browser or a rendering engine only runs on one type of device. especially don't make different defaults for different browsers or rendering engines. never use the os token to define if a browser is on mobile, tablet or desk...
Closures - JavaScript
t glance, it might seem unintuitive that this code still works. in some programming languages, the local variables within a function exist for just the duration of that function's execution. once makefunc() finishes executing, you might expect that the name variable would no longer be accessible. however, because the code still works as expected, this is obviously not the case in javascript. the reason is that functions in javascript form closures. a closure is the combination of a function and the lexical environment within which that function was declared. this environment consists of any local variables that were in-scope at the time the closure was created. in this case, myfunc is a reference to the instance of the function displayname created when makefunc is run. the instance of displayna...
...xical environment within which that function was declared. this environment consists of any local variables that were in-scope at the time the closure was created. in this case, myfunc is a reference to the instance of the function displayname created when makefunc is run. the instance of displayname maintains a reference to its lexical environment, within which the variable name exists. for this reason, when myfunc is invoked, the variable name remains available for use, and "mozilla" is passed to alert. here's a slightly more interesting example—a makeadder function: function makeadder(x) { return function(y) { return x + y; }; } var add5 = makeadder(5); var add10 = makeadder(10); console.log(add5(2)); // 7 console.log(add10(2)); // 12 in this example, we have defined a functi...
...fiddle. the helptext array defines three helpful hints, each associated with the id of an input field in the document. the loop cycles through these definitions, hooking up an onfocus event to each one that shows the associated help method. if you try this code out, you'll see that it doesn't work as expected. no matter what field you focus on, the message about your age will be displayed. the reason for this is that the functions assigned to onfocus are closures; they consist of the function definition and the captured environment from the setuphelp function's scope. three closures have been created by the loop, but each one shares the same single lexical environment, which has a variable with changing values (item). this is because the variable item is declared with var and thus has functio...
...ations it is unwise to unnecessarily create functions within other functions if closures are not needed for a particular task, as it will negatively affect script performance both in terms of processing speed and memory consumption. for instance, when creating a new object/class, methods should normally be associated to the object's prototype rather than defined into the object constructor. the reason is that whenever the constructor is called, the methods would get reassigned (that is, for every object creation). consider the following case: function myobject(name, message) { this.name = name.tostring(); this.message = message.tostring(); this.getname = function() { return this.name; }; this.getmessage = function() { return this.message; }; } because the previous code...
Web audio codec guide - Web media technologies
ginal, uncompressed audio signal the output seems to be when heard by the human ear. because of the differences in how lossy codecs work compared to lossless ones, especially the fact that lossless ones have to be much more conservative with their compression, lossy codecs nearly always result in significantly smaller compressed audio than lossless codecs do. generally speaking, the most common reasons to choose lossless audio are because you require archival-quality storage, or because the audio samples will be remixed and recompressed, and you wish to avoid the amplification of artifacts in the audio due to recompression. for real-time streaming of audio, a lossy codec is usually required in order to ensure the flow of data can keep up with the audio playback rate regardless of network perfo...
...when a codec is designed or configured to represent human speech rather than a broad range of sounds. human speech generally resides within the audio frequency range of 300 hz to 18 khz. however, the vast majority of human vocalizations exist in the range 300 hz to 8 khz, and you can capture enough of human vocalizations in the frequency range 500 hz to 3 khz to still be understandable. for that reason, speech-specific codecs often begin by dropping sound that falls outside a set range. that range is the audio frequency bandwidth. g.722, for example, strips away sounds outside the audio frequency bandwidth of 50 hz to 7 khz. this reduces the amount of data that needs to be encoded from the outset. codec details below we take a brief look at each of these codecs, looking at their basic capabil...
...this capability was introduced on each platform in different firefox releases: mp3 support with external library, by platform, in firefox platform first firefox version with mp3 support windows (vista and later) 22 android 20 ...
...enerally used on the web that are used for voice-only encoding are g.722 and amr. amr is a narrowband codec, encoding only the frequencies between 200 hz and 3,400 hz at bit rates typically around 7.4 kbps, while g.722 is a wideband codec that expands the audio bandwidth to 50 hz to 7,000 hz at much higher bit rates—usually 64 kbps. if you have plenty of network bandwidth to work with, and are reasonably certain your users will as well, g.722 is the better choice. to maximize the storage and network efficiency in a constrained environment, choose amr. example: audio clips for professional mixing when compressing audio that will be getting mixed or remixed, you typically want zero or close to zero loss of fidelity, which suggests a lossless codec may be in order. however, because lossless en...
Web video codec guide - Web media technologies
pproximate the appearance of the following frame. the more successive frames differ from one another, the larger these differences are, and the less effective the compression is at avoiding the introduction of artifacts into the compressed video. the complexity introduced by motion results in larger intermediate frames due to the higher number of differences between frames). for this and other reasons, the more motion there is in a video, the larger the output file will typically be. noise picture noise (such as film grain effects, dust, or other grittiness to the image) introduces variability. variability generally makes compression more difficult, resulting in more lost quality due to the need to drop details to achieve the same level of compression. the more variability—su...
...g forward, however, you should stay within the limits of the level you choose. the primary drawback to av1 at this time is that it is very new, and support is still in the process of being integrated into most browsers. additionally, encoders and decoders are still being optimized for performance, and hardware encoders and decoders are still mostly in development rather than production. for this reason, encoding a video into av1 format takes a very long time, since all the work is done in software. for the time being, because of these factors, av1 is not yet ready to be your first choice of video codec, but you should watch for it to be ready to use in the future. supported bit rates varies depending on the video's level; theoretical maximum reaches 800 mbps at level 6.3[2] ...
...cture), or bppmaxkb. during encoding, a value is selected for bppmaxkb, and then the video cannot exceed this value for each frame. the final bit rate will depend on this, the frame rate, the compression, and the chosen resolution and block format. h.263 has been superseded by h.264 and is therefore considered a legacy media format which you generally should avoid using if you can. the only real reason to use h.263 in new projects is if you require support on very old devices on which h.263 is your best choice. h.263 is a proprietary format, with patents held by a number of organizations and companies, including telenor, fujitsu, motorola, samsung, hitachi, polycom, qualcomm, and so on. to use h.263, you are legally obligated to obtain the appropriate licenses. supported bit rates ...
... but ideally 96khz) and encoded with complex encoding rather than fast encoding. <video controls> <source type="video/webm" src="filename.webm"> <source type="video/mp4" src="filename.mp4"> </video> recommendations for archival, editing, or remixing there are not currently any lossless—or even near-lossless—video codecs generally available in web browsers. the reason for this is simple: video is huge. lossless compression is by definition less effective than lossy compression. for example, uncompressed 1080p video (1920 by 1080 pixels) with 4:2:0 chroma subsampling needs at least 1.5 gbps. using lossless compression such as ffv1 (which is not supported by web browsers) could perhaps reduce that to somewhere around 600 mbps, depending on the content. that's st...
Content Scripts - Archive of obsolete content
page after this script will be able to access foo. but a content script will not: // main.js 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, contentscript: "console.log(window.foo);" }) tabs.open(pageurl); console.log: my-addon: null there are good reasons for this insulation. first, it means that content scripts don't leak objects to web pages, potentially opening up security holes. second, it means that content scripts can create objects without worrying about whether they might clash with objects added by page scripts. this insulation means that, for example, if a web page loads the jquery library, then the content script won't be able to see ...
...);" + "}"; require("sdk/page-mod").pagemod({ include: "*", contentscript: myscript, contentscriptwhen: "start" }); this will work fine on most pages, but will fail on pages which also assign to onclick: <html> <head> </head> <body> <script> window.onclick = function() { window.alert("it's my click now!"); } </script> </body> </html> for these reasons, it's better to add event listeners using addeventlistener(), defining the listener as a function: var themessage = "hello from content script!"; anelement.onclick = function() { alert(themessage); }; anotherelement.addeventlistener("click", function() { alert(themessage); }); communicating with the add-on to enable add-on scripts and content scripts to communicate with each other, each...
...ort api see the reference page for the port object. the postmessage api before the port object was added, add-on code and content scripts communicated using a different api: the content script called self.postmessage() to send and self.on() to receive the add-on script called worker.postmessage() to send and worker.on()to receive the api is still available and documented, but there's no reason to use it instead of the port api described here. the exception is the context-menu module, which still uses postmessage. content script to content script content scripts can only communicate with each other directly if they have been loaded into the same context. for example, if a single call to tab.attach() attaches two content scripts, then they can see each other directly, just as page scri...
ui/frame - Archive of obsolete content
: window.addeventlistener("message", handlepong, false); sending json in all cases, you can send a string as a message or a json object. if you send a json object, the sdk takes care of serializing and deserializing it for you: // frame.js var label = window.document.getelementbyid("linky"); label.addeventlistener("click", function() { window.parent.postmessage({ "type" : "ping", "reason" : "they clicked me" }, "*"); }, true); // main.js var { frame } = require("sdk/ui/frame"); var frame = new frame({ url: "./frame.html" }); frame.on("message", pong); function pong(e) { if (e.data.type == "ping") { console.log(e.data.reason); e.source.postmessage("pong", event.origin); } } globals constructors frame(options) creates an frame. once created, the frame need...
...an use as the targetorigin argument to postmessage() if you want to communicate with this particular frame instance. data, which represents the event's payload. ...
...window.document.getelementbyid("linky"); label.addeventlistener("click", function() { window.parent.postmessage({ "type" : "ping", "reason" : "they clicked me" }, "*"); }, true); // main.js var { frame } = require("sdk/ui/frame"); var frame = new frame({ url: "./frame.html" }); frame.on("message", pong); function pong(e) { if (e.data.type == "ping") { console.log(e.data.reason); e.source.postmessage("pong", e.origin); } } ...
MMgc - Archive of obsolete content
(gc) memory must use the drcwb macro. this is true whether the object containing the pointer is gcobject or rcobject. class myobject : public mmgc::rcobject { ... }; class myothermanagedgcobject : public mmgc::gcobject { drcwb(myobject*) myobject; }; class myothermanagedrcobject : public mmgc::rcobject { drcwb(myobject*) myobject; }; the rcobject must zero itself out on deletion. for this reason, rcobject's always have finalizers. declare a destructor that zeros out all of the fields of your rcobject. see zeroing rcobjects for more information. class myobject : public mmgc::rcobject { public: myobject() { x = 1; y = 2; z = 3; } ~myobject() { x = y = z = 0; } private: int x; int y; int z; }; gcroot if you have a pointer to a gcobject from an object in unmanaged memory, the unmanag...
...eference count must be maintained. write barriers are not needed for c++ objects that exist purely on the stack, and never in the heap. the flash player class "nativeinfo" is a good example. such objects are essentially the same as stack-based local variables. zeroing rcobjects all rcobjects (including all subclasses) must zero themselves out completely upon destruction. asserts enforce this. the reason is that our collector zeroes memory upon free and this was hurting performance. since mmgc must traverse objects to decrement refcounts properly upon destruction, i just made destructors do zeroing too. this mostly applies to non-pointer fields as drcwb smart pointers do this for you. poisoned memory in debug builds, mmgc writes "poison" into deallocated memory as a debugging aid. here's what the...
... since your already reading/writing from that page. the result will be at the end of the mark cycle fewer things need to be marked. these two optimizations can be combined. increment time slice before diving into the this it should be acknowledged that another way to go about this is to use a background thread and not worry about incremental marking. ...
Migrate apps from Internet Explorer to Mozilla - Archive of obsolete content
atextvalue. insertbefore( anewnode, achildnode ) inserts anewnode before achildnode, which must be a child of the current node. removechild( achildnode ) removes achildnode and returns a reference to it. replacechild( anewnode, achildnode ) replaces achildnode with anewnode and returns a reference to the removed node. document fragments for performance reasons, you can create documents in memory, rather than working on the existing document's dom. dom level 1 core introduced document fragments, which are lightweight documents that contain a subset of a normal document's interfaces. for example, getelementbyid does not exist, but appendchild does. you can also easily add document fragments to existing documents. mozilla creates document fragments thro...
.... mozilla uses it for the following conditions: if a page is sent with a text/xml mimetype or any other xml or xhtml mimetype for any "doctype html system" doctype (for example, <!doctype html system "http://www.w3.org/tr/rec-html40/strict.dtd">), except for the ibm doctype for unknown doctypes or doctypes without dtds almost standards mode mozilla introduced almost standards mode for one reason: a section in the css 2 specification breaks designs based on a precise layout of small images in table cells. instead of forming one image to the user, each small image ends up with a gap next to it. the old ibm homepage shown in figure 5 offers an example. figure 5. image gap almost standards mode behaves almost exactly as standards mode, except when it comes to an image gap issue. the issu...
...e called after open() is called. string status the status code of the http response. xslt differences mozilla supports xsl transformations (xslt) 1.0. it also allows javascript to perform xslt transformations and allows running xpath on a document. mozilla requires that you send the xml and xslt files with an xml mimetype (text/xml or application/xml). this is the most common reason why xslt won't run in mozilla but will in internet explorer. mozilla is strict in that way. internet explorer 5.0 and 5.5 supported xslt's working draft, which is substantially different than the final 1.0 recommendation. the easiest way to distinguish what version an xslt file was written against is to look at the namespace. the namespace for the 1.0 recommendation is http://www.w3.org/1999/xsl...
Modularization techniques - Archive of obsolete content
ns_imethod queryinterface(const nsiid &aiid, void **aresult) = 0; ns_imethod_(nsrefcnt) addref(void) = 0; ns_imethod_(nsrefcnt) release(void) = 0; }; the ns_imethod and ns_imethod_(type) macros are basically shorthand for virtual nsresult and virtualtype. on windows they expand to virtual nsresult __stdcall and virtual type __stdcall for com compatibility reasons. you don't have to use them in your interfaces unless you're concerned with com compatibility. all mozilla interfaces inherit from nsisupports. inheriting from nsisupports allows any interface to be interrogated about other interfaces that its instance may support, and insures that reference counting facilities are always available. the iid for nsisupports is defined as ns_isupports_iid. query...
...pically have a foofactory associated with it. the nsifactory interface is the equivalent of com's iclassfactory. /* * the nsifactory interface */ class nsifactory: public nsisupports { public: ns_imethod createinstance(nsisupports *aouter, const nsiid &aiid, void **aresult) = 0; ns_imethod lockfactory(prbool alock) = 0; the reason for using factories is that it provides a mechanism for creating an object without having access to the class declaration for that object. calling new foo() requires that at compile time you have access to the class declaration of foo(). a factory allows an implementor to hide both the class declaration and creation details of an object, an extremely important step for allowing maximum flexibilit...
...ormat. xpcom uses these typelibraries to allow other languages, such as javascript, to implement and call xpcom objects. we also do cross-thread proxying calls using the typelib and nspr's event queues. microsoft provides an extensive support infrastructure for com. this technology is built into windows, but not most other platforms. the technology can be licensed from microsoft, but for obvious reasons we are not going to be doing that. in house equivalents to the important elements of this technology will be developed as needed. links the component object model specification revision history feb 25, 1998, created oct 19, 1998, dusted off momentarily oct 10, 1999, added comments about xpidl, language-independentness original document information author(s): will scullin last u...
appendNotification - Archive of obsolete content
popup: null }; buttons.push(but...
... popup: null }; buttons.push(button1); let button2 = { ...
... popup: null }; buttons.push(button1); let button2 = { isdefault: ...
Menus - Archive of obsolete content
ar across the top of the window. on the macintosh, the menubar is placed along the top of the screen. you do not have to do anything to handle this difference. the first menubar encountered when parsing the xul window will be used as the main menu bar for the window, and on the macintosh, will be hidden from the main window and transformed into a native menu bar at the top of the screen. for this reason, a window should only have one menu bar, however, each window can have a different menu bar. the menubar should have menu elements within it, one for each menu. the example below shows a menubar with three menus. <menubar id="sample-menubar"> <menu id="file-menu" label="file"> ... </menu> <menu id="tools-menu" label="tools"> ... </menu> <menu id="help-menu" label="help"> .
...els of submenus. for information about submenus, see submenus below. the label for the menu element is specified using the label attribute. in the example below, the menu has the label 'view'. <menu label="view"> <menupopup> <menuitem label="toolbar"/> <menuitem label="status bar"/> </menupopup> </menu> when the menu is clicked, it opens the menupopup contained within it. for this reason, a menupopup should be placed as a direct child of the menu. the menu can also be opened by using the keyboard. the user can press a key to highlight the menu labels and navigate with the cursor keys. the key is different for each platform; on windows f10 can be used. another way is to add shortcut keys called access keys for each menu element to make it easier to access the menu commands. on so...
...he user can press a key to highlight the menu labels and navigate with the cursor keys. the key is different for each platform; on windows f10 can be used. another way is to add shortcut keys called access keys for each menu element to make it easier to access the menu commands. on some platforms, adding an access key will underline a letter in the menu label indicating the key to press. for this reason, the access key should always correspond to a character that appears in the menu label. to set an access key for a menu, use the accesskey attribute, as in the example below. <menu label="file" accesskey="f"/> this menu can then be opened by pressing the access key (typically in combination with the alt key). naturally, the access keys should be unique on a menubar. so if you wanted to have ...
Writing JavaScript for XHTML - Archive of obsolete content
in practise, very few xhtml documents are served over the web with the correct mime media type, application/xhtml+xml. whilst authored to the stricter rules of xml, they are sent with the media type for html (text/html). the receiving browser considers the content to be html, and does not utilise its xml parser. there are a number of reasons for this. ...
.... partially it is because, prior to version 9, internet explorer was incapable of handling xhtml sent with the official xhtml media type at all. (rather than displaying content, it would present the user with a file download dialog.) but it is also founded in the experience that javascript, authored carefully for html, can break when placed with an xml environment. this article shows some of the reasons alongside with strategies to remedy the problems. it will encourage web authors to use more xml features and make their javascript interoperable with real xhtml applications. (note that xhtml documents which behave correctly in both application/xhtml+xml and text/html environments are sometimes known as 'polyglot' documents.) to test the following examples locally, use firefox's extension swit...
...rage object. although this feature is not free of critics, you can use it to bypass the non-existing cookie, if your document is of type xml. again, you will have to write your own wrapper to respect any given combination of mime type and browser. problem: i can't use document.write() this problem has the same cause as the one above. this method does not exist in xmldocuments anymore. there are reasons why this decision was made, one being that a string of invalid markup will instantly break the whole document. solution: use dom methods many people avoided dom methods because of the typing to create one simple element, when document.write() worked. now you can't do this as easily as before. use dom methods to create all of your elements, attributes and other nodes. this is xml proof, as long...
Common causes of memory leaks in extensions - Extensions
e of leaks is forgetting to unload javascript code modules in bootstrapped add-ons. when your add-on gets updated and re-enabled, the previous module version that is still loaded will be used, which might break your add-on entirely. ...
...at is still loaded will be used, which might break your add-on entirely. ...
...re/modules/services.jsm"); function startup(data, reason) { // this assumes your add-on did register some chrome components.utils.import("chrome://myaddon/content/mymodule.jsm"); } function shutdown(data, reason) { // no need to do regular clean up when the application is closed // unless you need to break circular references that might negatively // impact the shutdown process. if (reason == app_shutdown) return; // your add-on needs to unload all modules it ships and imported! components.utils.unload("chrome://myaddon/content/mymodule.jsm"); } note: modules not belonging to your add-on — such as services.jsm — should not be unloaded by your add-on, as this might cause errors and/or performance regressions and will actually increase the memory usage. other information ...
HTML basics - Learn web development
ike keywords and a page description that you want to appear in search results, css to style our content, character set declarations and more. <meta charset="utf-8"> — this element sets the character set your document should use to utf-8 which includes most characters from the vast majority of written languages. essentially, it can now handle any textual content you might put on it. there is no reason not to set this and it can help avoid some problems later on. <title></title> — the <title> element. this sets the title of your page, which is the title that appears in the browser tab the page is loaded in. it is also used to describe the page when you bookmark/favourite it. <body></body> — the <body> element. this contains all the content that you want to show to web users when they visi...
... <img src="images/firefox-icon.png" alt="my test image"> as we said before, it embeds an image into our page in the position it appears. it does this via the src (source) attribute, which contains the path to our image file. we have also included an alt (alternative) attribute. in this attribute, you specify descriptive text for users who cannot see the image, possibly because of the following reasons: they are visually impaired. users with significant visual impairments often use tools called screen readers to read out the alt text to them. something has gone wrong causing the image not to display. for example, try deliberately changing the path inside your src attribute to make it incorrect. if you save and reload the page, you should see something like this in place of the image: t...
...ou'll commonly only use 3 to 4 at most: <h1>my main title</h1> <h2>my top level heading</h2> <h3>my subheading</h3> <h4>my sub-subheading</h4> now try adding a suitable title to your html page just above your <img> element. note: you'll see that your heading level 1 has an implicit style. don't use heading elements to make text bigger or bold, because they are used for accessibility and other reasons such as seo. try to create a meaningful sequence of headings on your pages, without skipping levels. paragraphs as explained above, <p> elements are for containing paragraphs of text; you'll use these frequently when marking up regular text content: <p>this is a single paragraph</p> add your sample text (you should have it from what should your website look like?) into one or a few paragrap...
Getting started with HTML - Learn web development
is a paragraph by enclosing it in a paragraph (<p>) element: <p>my cat is very grumpy</p> note: tags in html are case-insensitive. this means they can be written in uppercase or lowercase. for example, a <title> tag could be written as <title>, <title>, <title>, <title>, etc., and it will work. however, it is best practice to write all tags in lowercase for consistency, readability, and other reasons. anatomy of an html element let's further explore our paragraph element from the previous section: the anatomy of our element is: the opening tag: this consists of the name of the element (in this example, p for paragraph), wrapped in opening and closing angle brackets. this opening tag marks where the element begins or starts to take effect. in this example, it precedes the start of th...
...inline. this article will stay with these two terms. note: the terms block and inline, as used in this article, should not be confused with the types of css boxes that have the same names. while the names correlate by default, changing the css display type doesn't change the category of the element, and doesn't affect which elements it can contain and which elements it can be contained in. one reason html5 dropped these terms was to prevent this rather common confusion. note: find useful reference pages that include lists of block and inline elements. see block-level elements and inline elements. empty elements not all elements follow the pattern of an opening tag, content, and a closing tag. some elements consist of a single tag, which is typically used to insert/embed something in the...
...sults, css to style content, character set declarations, and more. you'll learn more about this in the next article of the series. <meta charset="utf-8">: this element specifies the character set for your document to utf-8, which includes most characters from the vast majority of human written languages. with this setting, the page can now handle any textual content it might contain. there is no reason not to set this, and it can help avoid some problems later. <title></title>: the <title> element. this sets the title of the page, which is the title that appears in the browser tab the page is loaded in. the page title is also used to describe the page when it is bookmarked. <body></body>: the <body> element. this contains all the content that displays on the page, including text, images, vide...
Introducing asynchronous JavaScript - Learn web development
previous overview: asynchronous next in this article we briefly recap the problems associated with synchronous javascript, and take a first look at some of the different asynchronous techniques you'll encounter, showing how they can help us solve such problems. prerequisites: basic computer literacy, a reasonable understanding of javascript fundamentals. objective: to gain familiarity with what asynchronous javascript is, how it differs from synchronous javascript, and what use cases it has. synchronous javascript to allow us to understand what asynchronous javascript is, we ought to start off by making sure we understand what synchronous javascript is. this section recaps some of the information we saw in the previous article. a lot of the functionali...
...n the example above, after you've clicked the button the paragraph won't appear until after the ok button is pressed in the alert box. you can try it for yourself: <button>click me</button> note: it is important to remember that alert(), while being very useful for demonstrating a synchronous blocking operation, is terrible for use in real world applications. asynchronous javascript for reasons illustrated earlier (e.g. related to blocking), many web api features now use asynchronous code to run, especially those that access or fetch some kind of resource from an external device, such as fetching a file from the network, accessing a database and returning data from it, accessing a video stream from a web cam, or broadcasting the display to a vr headset. why is this difficult to get to...
...: console.log ('all done! ' + image.src + 'displayed.'); you should now get an error in your console instead of the third message: typeerror: image is undefined; can't access its "src" property this is because at the time the browser tries to run the third console.log() statement, the fetch() block has not finished running so the image variable has not been given a value. note: for security reasons, you can't fetch() files from your local filesystem (or run other such operations locally); to run the above example locally you'll have to run the example through a local webserver. active learning: make it all async! to fix the problematic fetch() example and make the three console.log() statements appear in the desired order, you could make the third console.log() statement run async as we...
Cooperative asynchronous JavaScript: Timeouts and intervals - Learn web development
previous overview: asynchronous next this tutorial looks at the traditional methods javascript has available for running code asychronously after a set time period has elapsed, or at a regular interval (e.g. a set number of times per second), discusses what they are useful for, and considers their inherent issues. prerequisites: basic computer literacy, a reasonable understanding of javascript fundamentals. objective: to understand asynchronous loops and intervals and what they are useful for. introduction for a long time, the web platform has offered javascript programmers a number of functions that allow them to asynchronously execute code after a certain time interval has elapsed, and to repeatedly execute a block of code asynchronously until you tel...
...; } draw(); let's now see how to do the same thing using setinterval(): function draw() { // drawing code goes here } setinterval(draw, 17); as we covered earlier, you don't specify a time interval for requestanimationframe(). it just runs it as quickly and smoothly as possible in the current conditions. the browser also doesn't waste time running it if the animation is offscreen for some reason, etc. setinterval(), on the other hand requires an interval to be specified. we arrived at our final value of 17 via the formula 1000 milliseconds / 60hz, and then rounded it up. rounding up is a good idea; if you rounded down, the browser might try to run the animation faster than 60 fps, and it wouldn't make any difference to the animation's smoothness, anyway. as we said before, 60hz is the s...
...time = timestamp; } currenttime = timestamp - starttime; // do something based on current time requestanimationframe(draw); } draw(); browser support requestanimationframe() is supported in more recent browsers than setinterval()/settimeout(). interestingly, it is available in internet explorer 10 and above. so, unless you need to support older versions of ie, there is little reason to not use requestanimationframe(). a simple example enough with the theory! let's build your own personal requestanimationframe() example. you're going to create a simple "spinner animation"—the kind you might see displayed in an app when it is busy connecting to the server, etc. note: in a real world example, you should probably use css animations to run this kind of simple animation. how...
Focus management with Vue refs - Learn web development
ocument.getelementbyid) when using frameworks, because it results in the vdom and real dom going out of sync. instead, if you need to access the underlying dom nodes (like when setting focus), you can use vue refs. for custom vue components, you can also use refs to directly access the internal structure of a child component, however this should be done with caution as it can make code harder to reason about and understand. to use a ref in a component, you add a ref attribute to the element that you want to access, with a string identifier for the value of the attribute. it's important to note that a ref needs to be unique within a component. no two elements rendered at the same time should have the same ref. adding a ref to our app so, let's attach a ref to our "edit" button in todoitem.vue...
...n. however, unlike with the edit form, we don’t have a clear location for focus to move to when an element is deleted. we also need a way to provide assistive technology users with information that confirms that an element was deleted. we're already tracking the number of elements in our list heading — the <h2> in app.vue — and it's associated with our list of to-do items. this makes it a reasonable place to move focus to when we delete a node. first, we need to add a ref to our list heading. we also need to add a tabindex="-1" to it — this makes the element programmatically focusable (i.e. it can be focused via javascript), when by default it is not. inside app.vue, update your <h2> as follows: <h2 id="list-summary" ref="listsummary" tabindex="-1">{{listsummary}}</h2> note: tabi...
...ered in the app, you do not need to worry about using $nexttick of lifecycle methods to handle focusing it. deletetodo(todoid) { const itemindex = this.todoitems.findindex(item => item.id === todoid); this.todoitems.splice(itemindex, 1); this.$refs.listsummary.focus(); } now, when you delete an item from your list, focus should be moved up to the list heading. this should provide a reasonable focus experience for all of our users. summary so that's it for focus management, and for our app! congratulations for working your way through all our vue tutorials. in the next article we'll round things off with some further resources to take your vue learning further. note: if you need to check your code against our version, you can find a finished version of the sample vue app code i...
Eclipse CDT
ing a previous debug session, after which you've since rebuilt). remove any such breakpoints and restart your debug session. known issues there are various known limitations and bugs when it comes to using eclipse with mozilla. eclipse is open source, of course so if anyone feels like doing a bit of java hacking to fix these issues that'd be great. headers are only parsed once for performance reasons, eclipse only processes header files that have include guards once, using the compiler options for the first source file it encounters that includes that header (eclipse bug 380511). this is responsible for most of the parse errors in the source files displayed in eclipse. one problem with the "parse once" strategy is that the compiler options for the original source file may ifdef out sections ...
...ipse's "allow heuristic resolution of includes" option (enabled by default) will generally allow the included headers to be found when eclipse processes source files, that don't have any build output parser data. however, when the object directory is outside the source directory, eclipse doesn't know about it - or the headers it contains - unless the user takes extra steps to tell it. this is the reason that the instructions in the initial project properties section above instruct users that have their object directory outside their source directory to explicitly add {objdir}/dist/include to the project's "cdt user setting entries". fixing eclipse bug 381601 would considerably reduce the impact of the "unresolved inclusion" issue. (update 2017-03-28: the option index all header variants has bee...
...der that lets you specify that as an option, in which case eclipse sends the names of all changed files to your build tool. the build tool is a perl script that figures out if a faster build is possible and if so, does it. faq here are some frequently asked questions. why does eclipse need an object directory? to provide good code assistance eclipse needs you to have a build directory for two reasons. first, eclipse needs to be able to collect a usable set of defines, include paths, and preinclude files for the source files in the tree, as explained in the code assistance section above. second, eclipse cdt's indexer needs an object directory because virtually all mozilla source files include header files (directly or indirectly) that have been copied to or generated in the object directory...
Displaying Places information using views
a view so you've got a places view. how do you interact with it? because it is fairly complex, the built-in tree view provides uniquely tailored interfaces to make it easier to use. if you write your own complex view, you might do something similar. but all places views should provide a minimal interface so that you and controllers have a consistent, general way to interact with them. ...
... changing the way a built-in view displays dates or other data. inserting information into the display that is not determined by the underlying data. ...
...ng a custom view might include (but are in no way limited to): displaying custom columns alongside those provided by the built-in tree view. changing the way a built-in view displays dates or other data. inserting information into the display that is not determined by the underlying data. displaying places information in an element not covered by one of the built-in views. potentially bad reasons for creating a custom view might include (but are not limited to): changing only the superficial appearance of a built-in view rather than the content it displays. try css here. hiding columns of the built-in tree view. just leave out the treecol elements you want to hide. managing how the view responds to clicks, commands, and other user interaction. don't break the separation of concerns ...
Promise.jsm
three states: pending, when the final value is not available yet. this is the only state that may transition to one of the other two states. fulfilled, when and if the final value becomes available. a fulfillment value becomes permanently associated with the promise. this may be any value, including undefined. rejected, if an error prevented the final value from being determined. a rejection reason becomes permanently associated with the promise. this may be any value, including undefined, though it is generally an error object, like in exception handling. a reference to an existing promise may be received by different means, for example as the return value of a call into an asynchronous api. in this case, the state of the promise can be observed but not directly controlled. to observe t...
... example, unhandled exceptions in the callbacks cause the new promise to be rejected, even if the original promise is fulfilled. see the documentation of the then method for details. promises may also be created using the new promise() constructor. method overview deferred defer(); obsolete since gecko 30 promise resolve([optional] avalue); promise reject([optional] areason); methods defer() creates a new pending promise and provides methods to resolve or reject it. deferred defer(); obsolete since gecko 30 parameters none. return value a new object, containing the new promise in the promise property, and the methods to change its state in the resolve and reject properties. see the deferred documentation for details. resolve() creates a new promise ...
...f this value is not a promise, including undefined, it becomes the fulfillment value of the returned promise. if this value is a promise, then the returned promise will be resolved with the value, i.e. it will eventually assume the same state as the provided promise. return value a promise that can be pending, fulfilled, or rejected. reject() creates a new promise rejected with the specified reason. promise reject( areason ); parameters areason optional the rejection reason for the returned promise. although the reason can be undefined, it is generally an error object, like in exception handling. note: this argument should not be a promise. specifying a rejected promise would make the rejection reason equal to the rejected promise itself, and not its rejection reason. retur...
Deferred
methods resolve() fulfills the associated promise with the specified value, or propagates the state of an existing promise. ...
...e( avalue ); parameters avalue optional if this value is not a promise, including undefined, it becomes the fulfillment value of the associated promise. 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). reject() rejects the associated promise with the specified reason. ...
...w the state as the provided promise (including any future transitions). reject() rejects the associated promise with the specified reason. if the promise has already been resolved, either to a value, a rejection, or another promise, this method does nothing. note: this function is exactly same as promise constructor's reject argument, and can be called with any value of this. void reject( areason ); parameters areason optional the rejection reason for the associated promise. although the reason can be undefined, it is generally an error object, like in exception handling. note: this argument should not be a promise. specifying a rejected promise would make the rejection reason equal to the rejected promise itself, and not its rejection reason. ...
A guide to searching crash reports
nature the "proto signature" field is just the raw unprocessed crash stack concatenated together. you can do things like: search for crashes where the signature is foo, and the proto signature contains bar. this is helpful if you have a fairly generic signature and you want to see how many of them are a particular case of it that you've come across. or instead of a signature foo, a moz crash reason or something else. use it as a facet. this lets you skim the full signatures of crashes at a glance, bucketed together a bit. note that because the proto signature includes the entire signature, things aren't grouped all that well. grouping in the previous section we saw one example of grouping, in the "signature facet" tab that is shown by default. but there are many other interesting ways t...
...fault, it contains the value "signature", which explains why we saw a "signature facet" tab in the earlier search results. but we can change the values in this field and get different facet tabs in the search results. 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. the first of these is a "platform facet" tab, with results like those shown in the following screenshot. this has the same columns as the "signature facet" tab we saw earlier, except for the "bugs" column, because that is a special column that only applies to the signature facet. this tab shows the distribution of crash reports across the various pl...
...e columns as the "signature facet" tab we saw earlier, except for the "bugs" column, because that is a special column that only applies to the signature facet. this tab shows the distribution of crash reports across the various platforms. crash reports always include a platform field (though it may be empty if something has gone wrong) and so the percentages add up to 100. grouping by "moz crash reason" the second facet tab is a "moz crash reason facet" tab, with results like those shown in the following screenshot. this immediately shows which moz_crash calls are being hit frequently by users. only a subset of crash reports have the "moz crash reason" field -- those that crashed due to hitting a moz_crash call -- so all crashes that lack that field are omitted from this tab. for that reaso...
NSS_3.12_release_notes.html
ert_checknamespace (see cert.h) cert_encodecertpoliciesextension (see cert.h) cert_encodeinfoaccessextension (see cert.h) cert_encodeinhibitanyextension (see cert.h) cert_encodenoticereference (see cert.h) cert_encodepolicyconstraintsextension (see cert.h) cert_encodepolicymappingextension (see cert.h) cert_encodesubjectkeyid (see certdb/cert.h) cert_encodeusernotice (see cert.h) cert_findcrlentryreasonexten (see cert.h) cert_findcrlnumberexten (see cert.h) cert_findnameconstraintsexten (see cert.h) cert_getclassicocspdisabledpolicy (see cert.h) cert_getclassicocspenabledhardfailurepolicy (see cert.h) cert_getclassicocspenabledsoftfailurepolicy (see cert.h) cert_getpkixverifynistrevocationpolicy (see cert.h) cert_getusepkixforvalidation (see cert.h) cert_getvaliddnspatternsfromcert (see cert.h) ...
... tls session ticket extension (off by default) see ssl_enable_session_tickets in ssl.h new ssl error codes (see sslerr.h) ssl_error_unsupported_extension_alert ssl_error_certificate_unobtainable_alert ssl_error_unrecognized_name_alert ssl_error_bad_cert_status_response_alert ssl_error_bad_cert_hash_value_alert ssl_error_rx_unexpected_new_session_ticket ssl_error_rx_malformed_new_session_ti...
...indows, and mac bug 90426: use of obsolete typedefs in public nss headers bug 113323: the first argument to pk11_findcertfromnickname should be const. ...
NSS Developer Tutorial
also used. miscellaneous goto can be used, to simplify resource deallocation, before returning from a function. a data buffer is usually represented as: unsigned char *data; unsigned int len; the buffer pointer is unsigned char *, as opposed to void *, so we can perform pointer arithmetic without casting. use char * only if the data is interpreted as text characters. for historical reasons, the buffer length is unsigned int, as opposed to size_t. unfortunately, this can be a source of integer overflow bugs on 64-bit systems. c features nss requires c99. however, not all features from c99 are equally available. variables can be declared, at the point they are first used. the inline keyword can be used. variadic macro arguments are permitted, but their use should be limited ...
...ers,which may be included by files in other directories, are in the private_exports variable. private headers, that are only included by files in the same directory, are not listed in either variable. only functions listed in the symbol export lists (nss.def, ssl.def, smime.def, etc.) are truly public functions. unfortunately, public headers may declare private functions, for historical reasons. the symbol export lists are the authoritative source of public functions. behavioral changes bug/quirk compatible: occasionally we cannot fix a bug, because applications may depend on the buggy behavior. we would need to add a new function to provide the desired behavior. similarly, new options often need to be disabled by default. nss review/feature approval process nss doesn’t have 'su...
...ide the desired behavior. similarly, new options often need to be disabled by default. nss review/feature approval process nss doesn’t have 'super reviewers'. we wish to increase the number of nss developers, who have broad understanding of nss. one review is usually enough for the review to pass. for critical code reviews, such as a patch release of a stable branch, two reviews may be more reasonable. for new features, especially those that appear controversial, try to find a reviewer from a different company or organization than your own, to avoid any perceptions of bias. update nss in mozilla-inbound and mozilla-central the procedure is documented at https://developer.mozilla.org/docs/updating_nspr_or_nss_in_mozilla-central. if it is necessary to apply private patches, please docum...
sslfnc.html
ble_hello tells the ssl library whether or not to send ssl3 client hello messages in ssl2-compatible format. if an ssl3 client hello message is sent to a server that only understands ssl2 and not ssl3, then the server will interpret the ssl3 client hello as a very large message, and the connection will usually seem to "hang" while the ssl2 server expects more data that will never arrive. for this reason, the ssl3 spec allows ssl3 client hellos to be sent in ssl2 format, and it recommends that ssl3 servers all accept ssl3 client hellos in ssl2 format. when an ssl2-only server receives an ssl3 client hello in ssl2 format, it can (and probably will) negotiate the protocol version correctly, not causing a "hang". some applications may wish to force ssl3 client hellos to be sent in ssl3 format, no...
...you use ssl_optionset to turn one of these on when the other one is already turned on for a particular socket, the function returns with the error code set to sec_error_invalid_args. likewise, using ssl_enabledefault to turn on the global default for one of these when the global default for the other one is already turned for a particular socket generates the same error. however, there is no good reason for these to be mutually exclusive. this restirction will be removed in future releases. if a socket that is already connected gets imported into ssl after it has been connected (that is, after pr_accept or pr_connect has returned), then no implicit ssl handshake configuration as a client or server will have been done by pr_connect or pr_accept on that socket. in this case, a call to ssl_reseth...
...oes, treating the remote end as a client. pr_false means the callback function should evaluate the certificate as a client does, treating the remote end as a server. the callback function returns one of these values: if authentication is successful, secsuccess. if authentication is not successful, secfailure. if the callback returns secfailure, the callback should indicate the reason for the failure (if possible) by calling pr_geterror with the appropriate error code. the callback function obtains the certificate to be authenticated by calling ssl_peercertificate. if isserver is false, the callback should also check that the domain name in the remote server's certificate matches the desired domain name specified in a previous call to ssl_seturl. to obtain that domain nam...
Invariants
(the jsval encoding depends on this.) the jsstackframe::down chain never forms a cycle. (it's a stack. but note that a stack frame is not necessarily newer than the next stack frame down, thanks to generators!) an object's scope chain (found by chasing jsobject::fslots[jsslot_parent]) never forms a cycle. ...
...ulates the parent from cx->fp->scopechain, which can be stale if we're on trace.) the chain of properties starting at any jsshape and chasing jsshape::parent never forms a cycle and does not contain any duplicate jsscopeproperty::slot values other than -1. (a cycle would be very silly and could cause infloops. the same slot being allocated to more than one property would be a problem for obvious reasons.) all jsshapes in dictionary-mode objects have the in_dictionary flag set. all jsshapes in property trees have it cleared. if an object is inextensible, its dslots will never again change. (we don't bother locking when accessing slots of a sealed object. the locking is going away regardless.) compartments suppose obj = js_getscopechain(cx) is not null. then cx->compartment == obj->compartmen...
...i, js::switchtocompartment, that lets you break this invariant, and of course in xpconnect we use that from time to time when we know we aren't going to be creating any new objects (other than global objects, which have no parent or prototype) or doing anything that might call back into native code that could create objects. we do this in order to save some cpu cycles (in other words, for no good reason whatsoever). if !js_isrunning(cx) && cx->globalobject == null, then cx->compartment == cx->runtime->defaultcompartment. while executing a script, cx->compartment == script->compartment. but this is true only so long as we are actually in the interpreter or jit code. a jsnative or other callback may move cx to another compartment, as long as it returns cx to the script's compartment before retur...
JIT Optimization Strategies
lowing operations: getproperty (obj.prop) setproperty (obj.prop = val) getelement (obj[elemname]) setelement (obj[elemname] = val) call (func(...)) at each operation site, ionmonkey tries a battery of strategies, from the most optimized but most restrictive to the least optimized but least restrictive. for each strategy attempted, its outcome is tracked. an outcome is either success or a reason why the strategy failed to apply. this page documents the various optimization strategies and their outcomes. it provides information on what they attempt to do, what general level of speed-up they provide, what kind of program characteristics can prevent them from being used, and common ways to enable the engine to utilize that optimization. getproperty getproperty_argumentslength attempts t...
... // y is a definite slot property somecomplicatedfunctioncall(); this.z = 20; // z is not a definite slot property. } in the above example, the properties x and y can always be determined to exist on any instance of someconstructor at definite locations, allowing the engine to infer deterministically the position of x without a shape guard. this optimization can fail for a number of reasons. if the types observed at the property access are polymorphic (more than one type), this optimization cannot succeed. furthermore, even if the object type is monomorphic, the optimization will fail if the property being accessed is not a definite slot as described above. getprop_unboxed similar to getprop_definiteslot. unboxed property reads are possible on properties which satisfy all the cha...
... // y is a definite slot property somecomplicatedfunctioncall(); this.z = 20; // z is not a definite slot property. } in the above example, the properties x and y can always be determined to exist on any instance of someconstructor at definite locations, allowing the engine to infer deterministically the position of x without a shape guard. this optimization can fail for a number of reasons. if the types observed at the property access are polymorphic (more than one type), this optimization cannot succeed. furthermore, even if the object type is monomorphic, the optimization will fail if the property being written is not a definite slot as described above. setprop_unboxed similar to setprop_definiteslot. unboxed property writes are possible on properties which satisfy all the cha...
Handling Mozilla Security Bugs
d other organizations involved with mozilla. the mozilla security module owner and peers the mozilla security module owner will have a similar level of power and responsibility as other mozilla module owners. also, as with other mozilla module owners, mozilla.org staff will oversee the work of the security module owner and select a new security module owner should that ever be necessary for any reason. the mozilla security module owner will work with mozilla.org staff to select one or more people to act as peers to the security module owner in investigating and resolving security vulnerabilities; the peers will share responsibility for overseeing and coordinating any and all activities related to security bugs. the mozilla security bug group the mozilla security module owner and peers will ...
...ll 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. we reserve the right to cap the membership at some reasonable level, either by refusing new applications or, if necessary and appropriate, by removing existing members of the security bug group to make room for new ones. disclosure of security vulnerabilities the security module owner, peers, and other members of the mozilla security bug group will not be asked to sign formal nondisclosure agreements or other legal paperwork. however, we do expect mem...
...lic. however, we will ask all individuals and organizations reporting security bugs through bugzilla to follow the voluntary guidelines below: before making a security bug world-readable, please provide a few days notice to the mozilla security bug group by sending an email to the private security bug group mailing list. please try not to keep bugs in the security-sensitive category for an unreasonably long amount of time. please try to be understanding and accommodating if a mozilla distributor has a legitimate need to keep a bug in the security-sensitive category for some reasonable additional time period, e.g., to get a new release distributed to users. (regarding this point, if all mozilla distributors have a representative on the security bug group, then even if a bug remains in the s...
Introduction to XPCOM for the DOM
ase also note that some interfaces are not refcounted, like the frames and views. for those you have to use raw interface pointers, and you don't have to perform any manual refcounting. let's say that you now want to execute a function declared on the nsifoo2 interface, also implemented by nsfoo. however, ifooptr does not give you access to that function, since it is a pointer to nsifoo, for the reasons mentioned in section 1.b. xpcom provides a handy method to get a pointer to an interface when you have a pointer to another interface, and both interfaces are implemented by the same object. this method is queryinterface(). it is defined on the nsisupports interface. every single interface in mozilla inherits from nsisupports. this is one of the main rules of xpcom. the goal is the following: fi...
...tr<nsinotimplemented> iptr(do_queryinterface(ifooptr)); if(!iptr) { // nsfoo doesn't implement nsinotimplemented. iptr is thus null. return ns_ok; } it is also worth noting that queryinterface is null-safe. for example, in the previous example, nothing bad will happen if ifooptr is null. additionally, the return value of a call to queryinterface should not be returned unless there is a good reason for that. if you are concerned that it could return ns_nointerface, return ns_ok, as the previous example shows. at the beginning of this section, i talked about a second solution to get a pointer to an interface. this should be used in the case a getter function is not available. as you probably know, the "this" member of an object is a pointer to that object. you can thus simply cast "this" st...
...ore advanced topics of object-oriented c++ , interface inheritance, and other fun stuff. tutorial : how to add a new interface introduction the purpose of this tutorial is to describe the process of adding a new interface to the dom and then implementing it. a good understanding of the previous sections is preferred to understand this tutorial. you could want to add a new interface for several reasons, like the addition of a new dom object, or to respect an eventual "interface freeze". first we will take a look at xpidl and how it can help you define interfaces. next we will describe the build system, makefiles, etc... and finally, we will look at the implementation of our new interface through the creation of an nsidomfabian interface (fabian is my first name ;-). xpidl xpidl stands for cr...
mozIStorageStatementCallback
ler that the storage api calls with result, error, and completion notifications while handling asynchronous database queries. storage/public/mozistoragestatementcallback.idlscriptable please add a summary to this article. ...
...d a summary to this article. last changed in gecko 1.9.1 (firefox 3.5 / thunderbird 3.0 / seamonkey 2.0) inherits from: nsisupports method overview void handlecompletion(in unsigned short areason); void handleerror(in mozistorageerror aerror); void handleresult(in mozistorageresultset aresultset); constants constant value description reason_finished 0 the statement has finished executing normally. reason_canceled 1 the statement stopped executing because it was canceled. ...
...ndlecompletion(in unsigned short areason); void handleerror(in mozistorageerror aerror); void handleresult(in mozistorageresultset aresultset); constants constant value description reason_finished 0 the statement has finished executing normally. reason_canceled 1 the statement stopped executing because it was canceled. reason_error 2 the statement stopped executing because an error occurred. methods handlecompletion() called when a statement finishes executing. void handlecompletion( in unsigned short areason ); parameters areason the reason the statement stopped executing; see the list of possible values in the constants section. handleerror() called when an error occurs while executing a ...
nsIRadioInterfaceLayer
ance, use: var radiointerfacelayer = components.classes["@mozilla.org/telephony/system-worker-manager;1"] .getservice(components.interfaces.nsiinterfacerequestor) .createinstance(components.interfaces.nsiradiointerfacelayer); method overview void answercall(in unsigned long callindex); void deactivatedatacall(in domstring cid, in domstring reason); void dial(in domstring number); void enumeratecalls(in nsiriltelephonycallback callback); void getdatacalllist(); unsigned short getnumberofmessagesfortext(in domstring text); void hangup(in unsigned long callindex); void registercallback(in nsiriltelephonycallback callback); void registerdatacallcallback(in nsirildatacallback callback); void rejectcall(in unsigned long callinde...
...void dial( in domstring number ); parameters number missing description exceptions thrown missing exception missing description enumeratecalls() will continue calling callback.enumeratecallstate until the cal...
...void dial( in domstring number ); parameters number missing description exceptions thrown missing exception missing description enumeratecalls() will continue calling callback.enumeratecallstate until the callback returns false. void enumeratecalls( in ...
nsIWebSocketListener
void onacknowledge( in nsisupports acontext, in pruint32 asize ); parameters acontext user defined context. asize ...
...y be called without this method ever getting called. no additional messages through onmessageavailable(), onbinarymessageavailable()() or onacknowledge()() will be delievered to the listener after onserverclose() is called, but outgoing messages can still be sent through the nsiwebsocketchannel connection. void onserverclose( in nsisupports acontext, in unsigned short acode, in autf8string areason ); parameters acontext user defined context. acode the websocket closing handshake status code; see status codes for possible values. areason a text string explaining the reason for the closure of the connection. onstart() called to signify the establishment of the message stream. any listener that receives onstart() will also receive onstop(). void onstart( in nsisup...
... the completion of the message stream. this is the final notification the listener will receive; once it's been received, the websocket connection is complete. this event can be received in error cases even if nsiwebsocketchannel.close() has not been called. void onstop( in nsisupports acontext, in nsresult astatuscode ); parameters acontext user defined context. astatuscode reason for stopping (ns_ok if completed successfully). see also websockets nsiwebsocketchannel ...
WebIDL bindings
ck> getbar(); void setbar(mycallback*); a consumer of mycallback would be able to use it like this: void someclass::dosomethingwithcallback(mycallback& acallback) { errorresult rv; int32_t number = acallback.getsomenumber(rv); if (rv.failed()) { // the error has already been reported to the js console; you can handle // things however you want here. return; } // for some reason we want to catch and rethrow exceptions from setsomenumber, say. acallback.setsomenumber(2*number, rv, erethrowexceptions); if (rv.failed()) { // the exception is now stored on rv. this code must report // it usefully; otherwise it will assert. } } external interfaces external interfaces are represented in c++ as objects that xpconnect knows how to unwrap to. this can mean xpcom ...
... mycallback would be able to use it like this: void someclass::dosomethingwithcallback(mycallback& acallback, myinterface& ainterfaceinstance) { errorresult rv; int32_t number = acallback.call(ainterfaceinstance, false, rv); if (rv.failed()) { // the error has already been reported to the js console; you can handle // things however you want here. return; } // now for some reason we want to catch and rethrow exceptions from the callback, // and use "this" as the this value for the call to js. number = acallback.call(*this, true, rv, erethrowexceptions); if (rv.failed()) { // the exception is now stored on rv. this code must report // it usefully; otherwise it will assert. } } sequences sequence arguments are represented by const sequence<t>&, where t...
...es a key. returns a boolean, true if key exists and was deleted, false otherwise. this.__dom_impl__.__delete(akey) // completely clear all values from maplike storage this.__dom_impl__.__clear(); determining the principal of the caller that invoked the webidl api this can be done by calling component.utils.getwebidlcallerprincipal(). throwing exceptions from js-implemented apis there are two reasons a js implemented api might throw. the first reason is that some unforeseen condition occurred and the second is that a specification requires an exception to be thrown. when throwing for an unforeseen condition, the exception will be reported to the console, and a sanitized ns_error_unexpected exception will be thrown to the calling content script, with the file/line of the content code that in...
DOM Inspector internals - Firefox Developer Tools
toolboxoverlay.xul this overlay fills in the inspector toolbox, including toolbar buttons and the location bar and its "inspect" button. toolboxoverlay.xul also defines the structure of the menubar, without defining the contents of any of the menus themselves. popupoverlay.xul this overlay defines most of the static structure of the menus in the menubar, with some exceptions. for obvious reasons, the contents of dynamic menus are not defined here. the dynamic menus include the inspect menus' ("inspect content document" and "inspect chrome document") popups from the file menu, and the "document viewer" and "object viewer" menus from the view menu. the preference menuitems in the view menu that affect only the dom nodes viewer ("blink selected element", et cetera) are added by that viewer...
... viewer ("blink selected element", et cetera) are added by that viewer's popup overlay (resources/content/viewers/dom/popupoverlay.xul). the same is true for the find menuitems and the "select element by click" menuitem in the edit menu, since no other viewers besides the dom nodes viewer support these features. the other edit menu items are also used in several viewers' context menus. for that reason, only those menuitems' ids are referenced here, and the complete definitions are imported from editingoverlay.xul. viewers which include one or more of these menuitems in their context menus follow the same practice. the tooltip used for the inspect menus—the one used to show a document's title (if any) and its uri for a given menuitem—is also defined here. commandoverlay.xul the popupo...
... any) and its uri for a given menuitem—is also defined here. commandoverlay.xul the popupoverlay.xul-provided menuitems that delegate to external command elements have their commands defined here. keysetoverlay.xul some popupoverlay.xul-provided menuitems have their keys defined here. as of this writing, all of the keys that correspond to edit menu items live in editingoverlay for no good reason. statusbaroverlay.xul this defines the contents of the dom inspector's status bar. dom inspector doesn't have a status bar, so this is entirely useless. ...
Debugger.Memory - Firefox Developer Tools
is incremental, a full collection cycle may consist of multiple discrete collection slices with the js mutator running interleaved. for each collection slice that occurred, there is an entry in the collections array with the following form: { "starttimestamp":timestamp, "endtimestamp":timestamp, } here the timestamp values are timestamps of the gc slice’s start and end events. reason a very short string describing the reason why the collection was triggered. known values include the following: “api” “eager_alloc_trigger” “destroy_runtime” “last_ditch” “too_much_malloc” “alloc_trigger” “debug_gc” “compartment_revived” “reset” “out_of_nursery” “evict_nursery” “full_store_buffer” “s...
...otherwise, null is returned. known values include the following: “gc mode” “malloc bytes trigger” “allocation trigger” “requested” gccyclenumber ...
...otherwise, null is returned. ...
Debugger - Firefox Developer Tools
api observe activity in only those globals that are reachable by the api’s user, thus imposing capability-based restrictions on a debugger’s reach. however, the onnewglobalobject method allows the api user to monitor all global object creation that occurs anywhere within the javascript system (the “jsruntime”, in spidermonkey terms), thereby escaping the capability-based limits. for this reason, onnewglobalobject is only available to privileged code. function properties of the debugger prototype object the functions described below may only be called with a this value referring to a debugger instance; they may not be used as methods of other kinds of objects. adddebuggee(global) add the global object designated byglobal to the set of global objects this debugger instance is d...
...serve activity in only those globals that are reachable by the api’s user, thus imposing capability-based restrictions on a debugger’s reach. however, the addallglobalsasdebuggees method allows the api user to monitor all global object creation that occurs anywhere within the javascript system (the “jsruntime”, in spidermonkey terms), thereby escaping the capability-based limits. for this reason, addallglobalsasdebuggees is only available to privileged code. removedebuggee(global) remove the global object designated byglobal from this debugger instance’s set of debuggees. return undefined. this method interpretsglobal using the same rules that adddebuggee does. removing a global as a debuggee from this debugger clears all breakpoints that belong to that debugger in that globa...
...t functions provided by this debugger api observe activity in only those globals that are reachable by the api’s user, thus imposing capability-based restrictions on a debugger’s reach. however, findallglobals allows the api user to find all global objects anywhere within the javascript system (the “jsruntime”, in spidermonkey terms), thereby escaping the capability-based limits. for this reason, findallglobals is only available to privileged code. makeglobalobjectreference(global) return the debugger.object whose referent is the global object designated byglobal, without adding the designated global as a debuggee. ifglobal does not designate a global object, throw a typeerror. determine which global is designated byglobal using the same rules as debugger.prototype.adddebuggee. adop...
Waterfall - Firefox Developer Tools
are recorded: name and description color detailed information dom event javascript code that's executed in response to a dom event. event type for example, "click" or "message". event phase for example, "target" or "capture". javascript functions executed in the page are labeled with the reason the function was called: script tag setinterval settimeout requestanimationframe promise callback promise init worker javascript uri event handler stack call stack, with links to functions. parse html time spent parsing the page's html. stack call stack, with links to fun...
...animations force forcedescendants layout calculating the position and size of page elements. this operation is sometimes called "reflow". paint drawing pixels to the screen. garbage collection garbage collection event. non-incremental gc events are labeled "(non-incremental)". reason a string indicating the reason gc was performed. non-incremental reason if the gc event was non-incremental, the string indicates the reason non-incremental gc was performed. new in firefox 46: if the gc event was caused by allocation pressure, a link appears, labeled "show allocation triggers". click the link to see the allocation profile leading up to this gc event...
...ine when gc is needed, and when non-incremental gc in particular is needed. in general, though: gc is needed when a lot of memory is being allocated non-incremental gc is usually needed when the memory allocation rate is high enough that spidermonkey may run out of memory during incremental gc when the waterfall records a gc marker it indicates: whether the gc was incremental or not the reason the gc was performed if the gc was non-incremental, the reason it was non-incremental starting in firefox 46, if the gc event was caused by allocation pressure, a link appears, labeled "show allocation triggers". click the link to see the allocation profile leading up to this gc event. see allocations and garbage collection for more details. adding markers with the console api two markers ar...
DOMException - Web APIs
scribed in web apis. each exception has a name, which is a short "camelcase" style string identifying the error or abnormal condition. constructor domexception() returns a domexception object with a specified message and name. properties domexception.code read only returns a short that contains one of the error code constants, or 0 if none match. this field is used for historical reasons. new dom exceptions don't use this anymore: they put this info in the domexception.name attribute. domexception.message read only returns a domstring representing a message or description associated with the given error name. domexception.name read only returns a domstring that contains one of the strings associated with an error name. error names common error names are listed here. som...
...lid_node_type_err) datacloneerror the object can not be cloned. (legacy code value: 25 and legacy constant name: data_clone_err) encodingerror the encoding or decoding operation failed (no legacy code value and constant name). notreadableerror the input/output read operation failed (no legacy code value and constant name). unknownerror the operation failed for an unknown transient reason (e.g. out of memory) (no legacy code value and constant name). constrainterror a mutation operation in a transaction failed because a constraint was not satisfied (no legacy code value and constant name). dataerror provided data is inadequate (no legacy code value and constant name). transactioninactiveerror a request was placed against a transaction that is currently not active or is...
...ctive or is finished (no legacy code value and constant name). readonlyerror the mutating operation was attempted in a "readonly" transaction (no legacy code value and constant name). versionerror an attempt was made to open a database using a lower version than the existing version (no legacy code value and constant name). operationerror the operation failed for an operation-specific reason (no legacy code value and constant name). notallowederror the request is not allowed by the user agent or the platform in the current context, possibly because the user denied permission (no legacy code value and constant name). specifications specification status comment web idlthe definition of 'constructor' in that specification. candidate recommendation adds...
Introduction to the File and Directory Entries API - Web APIs
ntries api includes both asynchronous and synchronous versions of the interfaces. the asynchronous api can be used in cases where you don't want an outstanding operation to block the ui. the synchronous api, on the other hand, allows for simpler programming model, but it must be used with webworkers. usefulness of the api the file and directory entries api is an important api for the following reasons: it lets apps have offline and storage features that involve large binary blobs. it can improve performance by letting an app pre-fetch assets in the background and cache locally. it lets users of your web app directly edit a binary file that's in their local file directory. it provides a storage api that is already familiar to your users, who are used to working with file systems. for ...
...stems. for examples of features you can create with this app, see the sample use cases section. the file and directory entries api and other storage apis the file and directory entries api is an alternative to other storage apis like indexeddb, websql (which has been deprecated since november18, 2010), and appcache. the api is a better choice for apps that deal with blobs for the following reasons: the file and directory entries api offers client-side storage for use cases that are not addressed by databases. if you want to have large mutable chunks of data, the file and directory entries api is a much more efficient storage solution than a database. while firefox supports blob storage for indexeddb, chrome currently does not (chrome is still implementing support for blob storage in i...
...g: xmlhttprequest (such as the send() method for file and blob objects) drag and drop api web workers (for the synchronous version of the file and directory entries api) the input element (to programmatically obtain a list of files from the element) the file and directory entries api is case sensitive the filesystem api is case-sensitive, and case-preserving. restrictions for security reasons, browsers impose restrictions on file access. if you ignore them, you will get security errors. the file and directory entries api adheres to the same-origin policy the file and directory entries api does not let you create and rename executable files the file system is sandboxed you cannot run your app from file:// the file and directory entries api adheres to the same-origin policy an...
MediaDevices.getUserMedia() - Web APIs
cannot find all media tracks with the specified types that meet the constraints given, then the returned promise is rejected with notfounderror. the following requests both audio and video without any specific requirements: { audio: true, video: true } if true is specified for a media type, the resulting stream is required to have that type of track in it. if one cannot be included for any reason, the call to getusermedia() will result in an error. while information about a user's cameras and microphones are inaccessible for privacy reasons, an application can request the camera and microphone capabilities it needs and wants, using additional constraints. the following expresses a preference for 1280x720 camera resolution: { audio: true, video: { width: 1280, height: 720 } } the...
...des it. to require a capability, use the keywords min, max, or exact (a.k.a. min == max). the following demands a minimum resolution of 1280x720: { audio: true, video: { width: { min: 1280 }, height: { min: 720 } } } if no camera exists with this resolution or higher, then the returned promise will be rejected with overconstrainederror, and the user will not be prompted. the reason for the difference in behaviour is that the keywords min, max, and exact are inherently mandatory. whereas plain values and a keyword called ideal are not. here's a full example: { audio: true, video: { width: { min: 1024, ideal: 1280, max: 1920 }, height: { min: 576, ideal: 720, max: 1080 } } } an ideal value, when used, has gravity, which means that the browser will try to fin...
...than requesting a more general permission. here, indicate we need the ability to use both camera and microphone: <iframe src="https://mycode.example.net/etc" allow="camera;microphone"> </iframe> read our guide, using feature policy, to learn more about how it works. encryption based security the getusermedia() method is only available in secure contexts. a secure context is one the browser is reasonably confident contains a document which was loaded securely, using https/tls, and has limited exposure to insecure contexts. if a document isn't loaded in a secure context, the navigator.mediadevices property is undefined, making access to getusermedia() impossible. attempting to access getusermedia() in this situation will result in a typeerror. document source security because of the obvious...
Capabilities, constraints, and settings - Web APIs
ssing needed properties, so handle that error. ...
... } else { let constraints = { width: { min: 640, ideal: 1920, max: 1920 }, height: { min: 400, ideal: 1080 }, aspectratio: 1.777777778, framerate: { max: 30 }, facingmode: { exact: "user" } }; mytrack.applyconstraints(constraints).then(function() => { /* do stuff if constraints applied successfully */ }).catch(function(reason) { /* failed to apply constraints; reason is why */ }); } here, after ensuring that the constrainable properties for which matches must be found are supported (width, height, framerate, and facingmode), we set up constraints which request a width no smaller than 640 and no larger than 1920 (but preferably 1920), a height no smaller than 400 (but ideally 1080), an aspect ratio of 16:9 (1.777777778), and a frame rate no greater than 30...
...et='_blank'>" + constraint + "</a></code>"; supportedconstraintlist.appendchild(elem); } } error handling we also have some simple error handling code; handleerror() is called to handle promises which fail, and the log() function appends the error message to a special logging <div> box under the video. function log(msg) { logelement.innerhtml += (msg + "<br>"); } function handleerror(reason) { log("error <code>" + reason.name + "</code> in constraint <code>" + reason.constraint + "</code>: " + reason.message); } result here you can see the complete example in action. specifications specification status comment media capture and streamsthe definition of 'constrainable pattern' in that specification. candidate recommendation initial de...
Page Visibility API - Web APIs
the page visibility api provides events you can watch for to know when a document becomes visible or hidden, as well as features to look at the current visibility state of the page. notes: the page visibility api is especially useful for saving resources and improving performance by letting a page avoid performing unnecessary tasks when the document isn't visible. when the user minimizes the window or switches to another tab, the api sends a visibilitychange event to let listeners know the state of the page has changed. you can detect the event and perform some actions or behave differently. ...
..., user agents typically have a number of policies in place to mitigate the performance impact of background or hidden tabs. these may include: most browsers stop sending requestanimationframe() callbacks to background tabs or hidden <iframe>s in order to improve performance and battery life. timers such as settimeout() are throttled in background/inactive tabs to help improve performance. see reasons for delays longer than specified for more details. budget-based background timeout throttling is now available in modern browsers (firefox 58+, chrome 57+), placing an additional limit on background timer cpu usage. this operates in a similar way across modern browsers, with the details being as follows: in firefox, windows in background tabs each have their own time budget in millisecond...
... with the details being as follows: in firefox, windows in background tabs each have their own time budget in milliseconds — a max and a min value of +50 ms and -150 ms, respectively. chrome is very similar except that the budget is specified in seconds. windows are subjected to throttling after 30 seconds, with the same throttling delay rules as specified for window timers (again, see reasons for delays longer than specified). in chrome, this value is 10 seconds. timer tasks are only permitted when the budget is non-negative. once a timer's code has finished running, the duration of time it took to execute is subtracted from its window's timeout budget. the budget regenerates at a rate of 10 ms per second, in both firefox and chrome. some processes are exempt from thi...
ReadableStream.ReadableStream() - Web APIs
f pull() returns a promise, then it won't be called again until that promise fulfills; if the promise rejects, the stream will become errored. the controller parameter passed to this method is a readablestreamdefaultcontroller or a readablebytestreamcontroller, depending on the value of the type property. this can be used by the developer to control the stream as more chunks are fetched. ...
... type optional this property controls what type of readable stream is being dealt with. if it is included with a value set to "bytes", the passed controller object will be a readablebytestreamcontroller capable of handling a byob (bring your own buffer)/byte stream. ...
...ue is neither "bytes" nor undefined. examples in the following simple example, a custom readablestream is created using a constructor (see our simple random stream example for the full code). the start() function generates a random string of text every second and enqueues it into the stream. a cancel() fuction is also provided to stop the generation if readablestream.cancel() is called for any reason. when a button is pressed, the generation is stopped, the stream is closed using readablestreamdefaultcontroller.close(), and another function is run, which reads the data back out of the stream. const stream = new readablestream({ start(controller) { interval = setinterval(() => { let string = randomchars(); // add the string to the stream controller.enqueue(string); ...
Screen Wake Lock API - Web APIs
n ebook, map navigation, following a recipe, presenting to an audience, scanning a qr/barcode or applications that use voice or gesture control, rather than tactile input (the default way to keep a screen awake). you acquire a wakelocksentinel object by calling the navigator.wakelock.request() promise based method that resolves if the platform allows it. a request may be rejected for a number of reasons, including system settings (such as power save mode or low battery level) or if the document is not active or visible. the sentinel is attached to the underlying system wake lock. it can be released by the system, again if the battery power is too low or the document is not active or visible. it can also be released manually via the wakelocksentinel.release() method. it is good practice to stor...
...ake lock request fails - usually system related, such as battery statuselem.textcontent = `${err.name}, ${err.message}`; } } releasing wake lock the following example shows how to release the previously acquired wake lock. 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). wakelock.addeventlistener('release', () => { // the wake lock has been released statuselem.textcontent = 'wake lock has been released'; }); reacquiring a wake lock the following code reacquires the wake lock should the visibility of the document change and the wake lock is released. document.addeventlistener('visibilitychange', () =>...
...bilitychange', () => { if (wakelock !== null && document.visibilitystate === 'visible') { wakelock = await navigator.wakelock.request('screen'); } }); putting it all together you can find the complete code on github here. the demo uses a button to acquire a wake lock and also release it, which in turn updates the ui. the ui also updates if the wake lock is released automatically for any reason. there's a checkbox which when checked, will automatically reacquire the wake lock if the document's visibility state changes and becomes visible again. performance considerations release the screen wake lock when user ends activity that required always-on screen. for example, a ticketing app which uses qr codes to transmit ticket information, might acquire screen wake lock when the qr code i...
Using Service Workers - Web APIs
appcache-implied behaviors with a fine degree of granularity, allowing you to handle this problem and many more. 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). this is already available with native apps, which is one of the main reasons native apps are often chosen over web apps. setting up to play with service workers many service workers features are now enabled by default in newer versions of supporting browsers. if however you find that demo code is not working in your installed versions, you might need to enable a pref: firefox nightly: go to about:config and set dom.serviceworkers.enabled to true; restart browser. c...
...mental-web-platform-features; restart browser (note that some features are now enabled by default in chrome.) opera: go to opera://flags and enable support for serviceworker; restart browser. microsoft edge: go to about:flags and tick enable service workers; restart browser. you’ll also need to serve your code via https — service workers are restricted to running across https for security reasons. github is therefore a good place to host experiments, as it supports https. in order to facilitate local development, localhost is considered a secure origin by browsers as well. basic architecture with service workers, the following steps are generally observed for basic set up: the service worker url is fetched and registered via serviceworkercontainer.register(). if successful, the ser...
...own above, browsers that don’t support service workers can just use your app online in the normal expected fashion. furthermore, if you use appcache and sw on a page, browsers that don’t support sw but do support appcache will use that, and browsers that support both will ignore the appcache and let sw take over. why is my service worker failing to register? this could be for the following reasons: you are not running your application through https. the path to your service worker file is not written correctly — it needs to be written relative to the origin, not your app’s root directory. in our example, the worker is at https://mdn.github.io/sw-test/sw.js, and the app’s root is https://mdn.github.io/sw-test/. but the path needs to be written as /sw-test/sw.js, not /sw.js. the ...
Window: unhandledrejection event - Web APIs
nsole. you can prevent this by calling preventdefault() on the promiserejectionevent; see preventing default handling below for an example. examples here we have a few examples showing ways you can make use of the unhandledrejection event. the event includes two useful pieces of information: promise the actual promise which was rejected with no handler available to deal with the rejection. ...
...an prevent this by calling preventdefault() on the promiserejectionevent; see preventing default handling below for an example. examples here we have a few examples showing ways you can make use of the unhandledrejection event. the event includes two useful pieces of information: promise the actual promise which was rejected with no handler available to deal with the rejection. ...
... with no handler available to deal with the rejection. reason the reason that would have been passed into the rejection handler if one had existed. see catch() for details. basic error logging this example simply logs information about the unhandled promise rejection to the console. window.addeventlistener("unhandledrejection", event => { console.warn(`unhandled promise rejection: ${event.reason}`); }); you can also use the onunhandledrejection event handler property to set up the event listener: window.onunhandledrejection = event => { console.warn(`unhandled promise rejection: ${event.reason}`); }; preventing default handling many environments (such as node.js) report unhandled promise rejections to the console by default. you can prevent that from happening by adding a handler...
WindowOrWorkerGlobalScope.setTimeout() - Web APIs
ction[, delay, arg1, arg2, ...]); var timeoutid = scope.settimeout(function[, delay]); var timeoutid = scope.settimeout(code[, delay]); parameters function a function to be executed after the timer expires. code an alternative syntax that allows you to include a string instead of a function, which is compiled and executed when the timer expires. ...
... arg1, ..., argn optional additional arguments which are passed through to the function specified by function. note: passing additional parameters to the function in the first syntax does not work in internet explorer 9 and below. if you want to enable this functionality on that browser, you must use a polyfill (see the polyfill section). ...
...imeout() has the same associated problems as using eval. // recommended window.settimeout(function() { alert('hello world!'); }, 500); // not recommended window.settimeout("alert('hello world!');", 500); a string passed to settimeout is evaluated in the global context, so local symbols in the context where settimeout() was called will not be available when the string is evaluated as code. reasons for delays longer than specified there are a number of reasons why a timeout may take longer to fire than anticipated. this section describes the most common reasons. timeouts throttled to ≥ 4ms in modern browsers, settimeout()/setinterval() calls are throttled to a minimum of once every 4 ms when successive calls are triggered due to callback nesting (where the nesting level is at least a ...
ARIA annotations - Accessibility
n be set on an element to provide a brief descriptive label when it isn't appropriate to have the label actually appearing in the ui, for example a search input in a horizontal nav bar. aria-labelledby="" can be set on an element and given a value the same as the id of an element that contains a label for the element. this is useful when the element’s label is available in the ui, but for some reason a conventional <label> won’t work. aria-description="" works the same as aria-label="", but is used when you want to give an element a more detailed description, rather than a short label. aria-describedby="" works the same as aria-labelledby="", but is used when you want to associate the element with a more detailed description, rather than a short label. aria-details="" works in the same w...
...itor or author accepts or rejects those changes. the semantics for this have long been available in html, via the <ins> and <del> elements: <p>freida’s pet is a <del>black cat called luna</del><ins>purple tyrannosaurus rex called tiny</ins>.</p> with the new additions, you now have new roles available to provide the same semantics, should you be unable to use <ins> and <del> elements for some reason: <p>freida’s pet is a <span role="deletion">black cat called luna</span><span role="insertion">purple tyrannosaurus rex called tiny</span>.</p> however, this often isn’t enough — when you’ve got a content change like the one above that involves an insertion and a deletion, there is no way for a screenreader user to work out if the two are related or not. this is the job of role="suggest...
... since aria-details can now accept multiple ids, we can associate multiple comments with the same annotation, like so: <p>the last half of the song is a slow-rising crescendo that peaks at the <mark aria-details="thread-1 thread-2">end of the guitar solo</mark>, before fading away sharply.</p> ...
Controlling Ratios of Flex Items Along the Main Axis - CSS: Cascading Style Sheets
allowed to shrink and so they overflow the box. change the flex-shrink value to 1 and you will see each item shrink by the same amount, in order that all of the items now fit in the box. they have become smaller than their initial width in order to do so. combining flex-shrink and flex-basis you could say that flex-shrink works in pretty much the same way as flex-grow. however there are two reasons why it isn’t quite the same. while it is usually subtle, defined in the specification is one reason why flex-shrink isn’t quite the same for negative space as flex-grow is for positive space: “note: the flex shrink factor is multiplied by the flex base size when distributing negative space. this distributes negative space in proportion to how much the item is able to shrink, so that e.g...
... why flex-shrink isn’t quite the same for negative space as flex-grow is for positive space: “note: the flex shrink factor is multiplied by the flex base size when distributing negative space. this distributes negative space in proportion to how much the item is able to shrink, so that e.g. a small item won’t shrink to zero before a larger item has been noticeably reduced.” the second reason is that flexbox prevents small items from shrinking to zero size during this removal of negative free space. the items will be floored at their min-content size — the size that they become if they take advantage of any soft wrapping opportunities available to them. you can see this min-content flooring happen in the below example, where the flex-basis is resolving to the size of the content. i...
... the size of the content. if you change the width on the flex container — increasing it to 700px for example — and then reduce the flex item width, you can see that the first two items will wrap, however they will never become smaller than that min-content size. as the box gets smaller space is then just removed from the third item. in practice the shrinking behaviour does tend to give you reasonable results. you don’t usually want your content to disappear completely or for boxes to get smaller than their minimum content, so the above rules make sense in terms of sensible behaviour for content that needs to be shrunk in order to fit into a container. giving items different flex-shrink factors in the same way as flex-grow, you can give flex-items different flex-shrink factors. this ca...
Variable fonts guide - CSS: Cascading Style Sheets
ze headings in different weights for better readability at each size, or using a slightly narrower width for data-dense displays. ...
...the publication — giving a much wider range of styles than currently typical on the web (or indeed practical for performance reasons alone). a note about font families, weights, and variants you might notice that we have been talking about having a specific font file for every weight and style (i.e. bold and italic and bold italic), rather than relying upon the browser to synthesize them. the reason for this is that most typefaces have very specific designs for bolder weights and italics that often include completely different characters (lower-case 'a' and 'g' are often quite different in italics, for example). in order to most accurately reflect the typeface design and avoid differences between browsers and how they may or may not synthesize the different styles, it's more accurate to load...
...-settings: 'opsz' <num>, you can supply a numeric value. in most cases you would want to match the font-size (the physical size the type is being rendered) with the opsz value (which is how optical sizing is intended to be applied when using auto). the option to provide a specific value is provided so that should it be necessary to override the default — for legibility, aesthetic, or some other reason — a specific value can be applied. font-optical-sizing: auto; font-variation-settings: 'opsz' 36; the following live example's css can be edited to allow you to play with optical size values. custom axes custom axes are just that: they can be any axis of design variation that the typeface designer imagines. there may be some that become fairly common — or even become registered — but...
<img>: The Image Embed element - HTML: Hypertext Markup Language
Web › HTML › Element › img
e <img> element: the src attribute is required, and contains the path to the image you want to embed. the alt attribute holds a text description of the image, which isn't mandatory but is incredibly useful for accessibility — screen readers read this description out to their users so they know what the image means. alt text is also displayed on the page if the image can't be loaded for some reason: for example, network errors, content blocking, or linkrot. there are many other attributes to achieve various purposes: referrer/cors control for security and privacy: see crossorigin and referrerpolicy. use both width and height to set the intrinsic size of the image, allowing it to take up space before it loads, to mitigate content layout shifts. responsive image hints with sizes and sr...
...tributes this element includes the global attributes. alt defines an alternative text description of the image. note: browsers do not always display images. there are a number of situations in which a browser might not display images, such as: non-visual browsers (such as those used by people with visual impairments) the user chooses not to display images (saving bandwidth, privacy reasons) the image is invalid or an unsupported type in these cases, the browser may replace the image with the text in the element's alt attribute. for these reasons and others, provide a useful value for alt whenever possible. omitting alt altogether indicates that the image is a key part of the content and no textual equivalent is available. setting this attribute to an empty string (alt=""...
...ow the browser should load the image: eager: loads the image immediately, regardless of whether or not the image is currently within the visible viewport (this is the default value). lazy: defers loading the image until it reaches a calculated distance from the viewport, as defined by the browser. the intent is to avoid the network and storage bandwidth needed to handle the image until it's reasonably certain that it will be needed. this generally improves the performance of the content in most typical use cases. note: loading is only deferred when javascript is enabled. this is an anti-tracking measure, because if a user agent supported lazy loading when scripting is disabled, it would still be possible for a site to track a user's approximate scroll position throughout a session, by st...
HTML documentation index - HTML: Hypertext Markup Language
Web › HTML › Index
che, application cache the manifest attribute of <html> element specifies a url of a application cache manifest that is downloaded in the early stages of page load. 114 <i>: the idiomatic text element element, html, html text-level semantics, reference, web, em the html idiomatic text element (<i>) represents a range of text that is set off from the normal text for some reason, such as idiomatic text, technical terms, taxonomical designations, among others. 115 <iframe>: the inline frame element content, element, embedded content, embedding, frames, html, html embedded content, inline frames, reference, web, embedded, iframe the html inline frame element (<iframe>) represents a nested browsing context, embedding another html page into the current o...
...contains style information for a document, or part of a document. 199 <sub>: the subscript element baseline, element, footnotes, html, html text-level semantics, html:flow content, html:palpable content, html:phrasing content, reference, subscript, web, sub the html subscript element (<sub>) specifies inline text which should be displayed as subscript for solely typographical reasons. 200 <summary>: the disclosure summary element disclosure box, disclosure control, disclosure summary, element, html, html interactive elements, reference, summary, web the html disclosure summary element (<summary>) element specifies a summary, caption, or legend for a <details> element's disclosure box. 201 <sup>: the superscript element element, html, html ...
...mmary>) element specifies a summary, caption, or legend for a <details> element's disclosure box. 201 <sup>: the superscript element element, html, html text-level semantics, html:flow content, html:palpable content, html:phrasing content, reference, web the html superscript element (<sup>) specifies inline text which is to be displayed as superscript for solely typographical reasons. 202 <table>: the table element element, html, html tabular data, reference, tables, web the html <table> element represents tabular data — that is, information presented in a two-dimensional table comprised of rows and columns of cells containing data. 203 <tbody>: the table body element element, html, html tabular data, reference, table body, table content...
Connection management in HTTP/1.x - HTTP
grades from optimum by persisting to transmit over a new, cold connection. this model is the default model used in http/1.0 (if there is no connection header, or if its value is set to close). in http/1.1, this model is only used when the connection header is sent with a value of close. unless dealing with a very old system, which doesn't support a persistent connection, there is no compelling reason to use this model. persistent connections short-lived connections have two major hitches: the time taken to establish a new connection is significant, and performance of the underlying tcp connection gets better only when this connection has been in use for some time (warm connection). to ease these problems, the concept of a persistent connection has been designed, even prior to http/1.1. alt...
...e rtt that will be used, as well as the effective bandwidth, have a direct incidence on the improvement provided by the pipeline. without knowing these, important messages may be delayed behind unimportant ones. the notion of important even evolves during page layout! http pipelining therefore brings a marginal improvement in most cases only. pipelining is subject to the hol problem. for these reasons, pipelining has been superseded by a better algorithm, multiplexing, that is used by http/2. by default, http requests are issued sequentially. the next request is only issued once the response to the current request has been received. as they are affected by network latencies and bandwidth limitations, this can result in significant delay before the next request is seen by the server. pipeli...
...lthough the demand in size of http requests continues to grow. not all types of http requests can be pipelined: only idempotent methods, that is get, head, put and delete, can be replayed safely: should a failure happen, the pipeline content can simply be repeated. today, every http/1.1-compliant proxy and server should support pipelining, though many have limitations in practice: a significant reason no modern browser activates this feature by default. domain sharding unless you have a very specific immediate need, don't use this deprecated technique; switch to http/2 instead. in http/2, domain sharding is no longer useful: the http/2 connection is able to handle parallel unprioritized requests very well. domain sharding is even detrimental to performance. most http/2 implementations use a...
Promise() constructor - JavaScript
catch() block that invokes rejectionfunc upon error. the signatures of these two functions are simple, they accept a single parameter of any type. of course, the actual names of these functions can be whatever is desired, i.e. they are named as the parameters of executor. each function is used by simply calling it when appropriate. resolutionfunc(value) // call on fulfilled rejectionfunc(reason) // call on rejected the returned value can be another promise object, in which case the promise gets dynamically inserted into the chain. return value promiseobj when called via new, the promise constructor returns a promise object. the promise object will become "resolved" when either of the functions resolutionfunc or rejectionfunc are invoked. note that if you call resolutionfunc o...
...ed using the new keyword and its constructor. this constructor takes a function, called the "executor function", as its parameter. this function should take two functions as parameters. the first of these functions (resolve) is called when the asynchronous task completes successfully and returns the results of the task as a value. ...
...sk completes successfully and returns the results of the task as a value. the second (reject) is called when the task fails, and returns the reason for failure, which is typically an error object. ...
Promise.prototype.then() - JavaScript
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. ...
...if it is not a function, it is internally replaced with a "thrower" function (it throws an error it received as argument). return value once a promise is fulfilled or rejected, the respective handler function (onfulfilled or onrejected) will be called asynchronously (scheduled in the current thread loop). the behavior of the handler function follows a specific set of rules. ...
...ise {[[promisestatus]]: "resolved", [[promisevalue]]: 33} description as the then and promise.prototype.catch() methods return promises, they can be chained — an operation called composition. examples using the then method var p1 = new promise((resolve, reject) => { resolve('success!'); // or // reject(new error("error!")); }); p1.then(value => { console.log(value); // success! }, reason => { console.error(reason); // error! }); chaining the then method returns a promise which allows for method chaining. if the function passed as handler to then returns a promise, an equivalent promise will be exposed to the subsequent then in the method chain. the below snippet simulates asynchronous code with the settimeout function. promise.resolve('foo') // 1. receive "foo", concaten...
Mobile first - Progressive web apps (PWAs)
ty is simple, legible and distraction-free as much as possible. mobile navigation when developing mobile app layouts, you often run into problems with navigation menus. the concept is the same regardless of the target device — you want to provide a mechanism for users to search for things and get to different views/pages of the application — but because mobile screens are so much smaller, a reasonable desktop navigation can spoil the experience by filling up most of the initial view of the app, covering up the content. there several ways to solve the problem of navigation getting in the way on mobile, a few of which i'll discuss here. the main objective is to put the content first and to hide away the navigation until the user really needs it. first of all, you can consider a different n...
...there is very little going on here, and anyone with a basic understanding of css should be able to understand most of it by just looking at the source code in app.css. particular bits of interest to point out are as follows. article { display: table; } nav { display: table-caption; caption-side: bottom; } this is a rather nice hacky bit of css you can use to mak...
... desktop version of the site requiring a webgl library like three but didn't want it included in the mobile version? you could create a block to only load the library in the case of narrow screen devices: if(window.matchmedia("(min-width: 481px)").matches) { require('three'); } we can, therefore, save the bandwidth for browsers that don't need it. modernizr css and js back to modernizr! the reason why it is so useful is that it provides a mechanism to selectively serve both css and javascript. modernizr stores the results of all its feature tests as classes on the html element. for example, the modernizr in our example app is testing for multiple background image and rgba support. when they are not supported, the <html> tag looks like this: <html class=" js no-rgba no-multiplebgs"> when ...
Using the WebAssembly JavaScript API - WebAssembly
ar i = 0; i < 10; i++) { i32[i] = i; } var sum = results.instance.exports.accumulate(0, 10); console.log(sum); note how we create the uint32array view on the memory object’s buffer (memory.prototype.buffer), not on the memory itself. memory imports work just like function imports, only memory objects are passed as values instead of javascript functions. memory imports are useful for two reasons: they allow javascript to fetch and create the initial contents of memory before or concurrently with module compilation. they allow a single memory object to be imported by multiple module instances, which is a critical building block for implementing dynamic linking in webassembly. note: you can find our complete demo at memory.html (see it live also) . tables a webassembly table is ...
... also) . tables a webassembly table is a resizable typed array of references that can be accessed by both javascript and webassembly code. while memory provides a resizable typed array of raw bytes, it is unsafe for references to be stored in a memory since a reference is an engine-trusted value whose bytes must not be read or written directly by content for safety, portability, and stability reasons. tables have an element type, which limits the types of reference that can be stored in the table. in the current iteration of webassembly, there is only one type of reference needed by webassembly code — functions — and thus only one valid element type. in future iterations, more element types will be added. function references are necessary to compile languages like c/c++ that have fun...
...embly code — functions — and thus only one valid element type. in future iterations, more element types will be added. function references are necessary to compile languages like c/c++ that have function pointers. in a native implementation of c/c++, a function pointer is represented by the raw address of the function’s code in the process’s virtual address space and so, for the safety reasons mentioned above, cannot be stored directly in linear memory. instead, function references are stored in a table and their indexes, which are integers and can be stored in linear memory, are passed around instead. when the time comes to call a function pointer, the webassembly caller supplies the index, which can then be safety bounds checked against the table before indexing and calling the in...
system/unload - Archive of obsolete content
a destructor method with a wrapper method that will never call the destructor more than once. it ensures that this wrapper method is called when the object's module is unloaded. therefore, when you register an object with ensure(), you can call its destructor method yourself, you can let it happen for you, or you can do both. the destructor will be called with a single argument describing the reason for the unload; see when(). if object does not have the expected destructor method, then an exception is thrown when ensure() is called. parameters object : object an object that defines a destructor method. name : string optional name of the destructor method. default is unload. when(callback) registers a function to be called when the module is unloaded. parameters callback : function ...
...ameters object : object an object that defines a destructor method. name : string optional name of the destructor method. default is unload. when(callback) registers a function to be called when the module is unloaded. parameters callback : function a function that will be called when the module is unloaded. it is called with a single argument, one of the following strings describing the reason for unload: "uninstall", "disable", "shutdown", "upgrade", or "downgrade". if a reason could not be determined, undefined will be passed instead. note that if an add-on is unloaded with reason "disable", it will not be notified about "uninstall" while it is disabled. see bug 571049. ...
HTML in XUL for rich tooltips - Archive of obsolete content
} } window.addeventlistener('load', htmltip.onload, false); in the xul overlay, xmlns:html is used to enable html tags to be used inside the xul. our enhanced xul tooltip is an element that is written ahead of time, and it contains an html div element whose type attribute lowers its privileges to being that content element, although it is an element of chrome. this is recommended for security reasons, especially if remote html is to be inserted. a number of menuitems have a tooltip attribute pointing to the same tooltip. that tooltip is empty now, but we will use the mouseover event to dynamically populate the tooltip (which is about to be shown) with a different message for each menuitem. this is done by calling the onmousetooltip function, which will take the tooltiphtml attribute of the ...
...is about to be shown) with a different message for each menuitem. this is done by calling the onmousetooltip function, which will take the tooltiphtml attribute of the element that is being hovered over and safely convert that into dom and inject it into the tooltip that will soon be shown. the tooltiphtml attribute is an html string which is set sometime beforehand for each element. for security reasons, the conversion will strip out some of the more dangerous elements in the html string, like javascript and iframes. non-dynamic html in xul tooltip it is also possible to avoid using dynamic html to accomplish this. you would have to have a separate xul tooltip element assigned to each element that you wish to have a rich tooltip with. you should write the html straight into the xul. <?xml ve...
Custom about: URLs - Archive of obsolete content
factory.unregister(); // .... } and there you have it, your own custom about page. ...
...mponent.prototype.classid, this); } } instantiation firefox 4+ now in the startup procedure of your bootstrapped addon make sure to do register the factory, for example: let factory; function startup(adata, areason) { // ... factory = new factory(aboutcustom); // ... } and then on shutdown of your bootstrapped addon make sure to destroy the factory: function shutdown(adata, areason) { if (areason == app_shutdown) { return } // ... factory.unregister(); // .... } and there you have it, your own custom about page. ...
Appendix C: Avoiding using eval in Add-ons - Archive of obsolete content
settimeout(alert.bind(null, xhr.responsetext), 100); function.bind() returns a new function. this is important to know in particular when you later want to call removeeventlistener: you'll have to pass the resulting function from the first .bind() call. calling .bind() again with removeeventlistener will not work. also, calling .bind() in a tight (inner) loop should be avoided for performance reasons, as calling .bind() does require some work and memory. overriding/extending/amending existing functions a common thing add-ons do during their initialization is overriding/extending existing browser functions by using function.tostring/function.tosource and eval to "string-patch" the function body. // do not use! var functionbody = gbrowser.addtab.tosource(); var afterbracket = functionbody.
...arameter naming (or changes in naming in future application versions) or short-hand/arrow functions. note: it is not safe to remove such an override again, as this method constitutes in a single-linked function chain. if you want to disable your overrides again, then use a flag indicating that, or similar. at the same time, it is also not safe to "un-string-patch" a function, for the exact same reason. note: there are still some scenarios where incompatibilities may arise, such as trying to cancel the function call under a certain set of conditions when other add-ons have overridden the same function. again, this is a problem with the "string-patch" method, too. how to handle this is inter-add-on specific and not addressed in this article. overriding/extending/amending existing objects (or o...
Setting Up a Development Environment - Archive of obsolete content
xpi again. you can clean up the bin directory by just running the following command (again, from the src directory): make clean you can also run these commands from komodo. click on tools > run command.... in the "run" textbox you should type this: bash -c "make" or replace "make" with "make clean" for the clean command. the "bash -c" part forces komodo to use bash, which for some reason can't be set properly as the default command shell. it isn't necessary to add this, but it's better so that it is consistent with the make command we'll see next. in the "start in" textbox you should choose %p (directory path of active project). if you don't see this textbox, click on the "more" button. you also have the option to save the command, by clicking on the "add to toolbox" checkbox. t...
... by clicking on the "add to toolbox" checkbox. to see the toolbox, click on view > tabs > toolbox, from the main menu. with that, you should now have a very easy way to build your xpi, by just double clicking on the created commands. we can make it even better. once you're testing and debugging your code, you'll find that constantly building and installing an xpi can be very tedious. this is the reason why we introduced "make install". this only works if your extension is already installed in a firefox profile. just like in the provided project, you need the add-on id and profile location set in the file makefile. we use this information to locate the installation path of the extension and overwrite the installed files. if firefox is open at the time you run "make install", you'll have to resta...
JavaScript Client API - Archive of obsolete content
o install and use a local version of the firefox sync server for multiple account testing and that any use of mozilla’s hosted firefox sync services is subject to mozilla’s firefox sync terms of service at https://services.mozilla.com/tos/. ...
... weave object: weave.fooengine = fooengine; and add "foo" to the services.sync.registerengines preference (it's a comma separated list of engine names). you can also set up a component that registers a weave:service:ready observer and at that time, imports main.js as well as your engine. also, for me, doing weave.engines.register(fooengine) worked better then doing weave.fooengine = fooengine. reason for this is, weave will iterate through the registerengines preference and try to instantiate each engine it has there before you the line mentioned above ever has a chance to execute.this means the constructor to your engine is not ready when weave tries to instantiate it. testing and debugging your engine set observers in the tracker to tell when your datatype changes, after which the score n...
Frequently Asked Questions - Archive of obsolete content
note: this page is extremely out of date. what is the status of the svg implementation? we currently maintain two documents to help answer this question: a status page for svg in firefox 1.5+ and a status page for svg in the development trunk. why does mozilla show source code/gibberish instead of svg? there are two possible reasons for this: a simple mistake in the svg file, or a misconfigured server. 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. to be valid the root <svg> tag in svg files must have at least the following two "namespace bindings". <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"> actually the se...
...zilla's native implementation of svg, not adobe/corel/whoever's plug-in. however, we might as well answer this question to save you searching for this information elsewhere. see these install instructions on mozdev.org. it's also useful to know that you can check whether mozilla has recognised your plug-ins by typing 'about:plugins' into your address bar (linking to that doesn't work for security reasons). does mozilla work with corel's svg plug-in? there are reports that it does, but that it's slower than the adobe plug-in. see this document for information on how to install it. can you have both native svg support and an svg plug-in installed? yes. if the plug-in works with the equivalent non-svg version of mozilla, then it should also work in the svg enabled version. to be able to use it,...
modDateChanged - Archive of obsolete content
m a moddate on a separate file, as in the following example, in which the dates of two files are compared. ...
...moddatechanged(filesource1, err1); logcomment("file.moddatechanged should return 'false' = " + err2); // the reason it expects false is we're comparing // the return 'time stamp' value for // file1.txt with the actual file1.txt itself. // thus, no change in 'time stamp' values. err3 = file.moddatechanged(filesource2, err1); logcomment("file.moddatechanged should return 'true' = " + err2); // the reason it expects true is we're comparing // the return 'time stamp' value for // file1.txt with another file, file2.txt, with a different // 'time stamp' value. ...
Introduction to XUL - Archive of obsolete content
filetypes xml is of course case sensitive. xul is equally so. our current code tends not to be strict about enforcing this, especially for tags and attributes in the html namespace. this will change: tags and attributes will, as a rule, always be lower case as suggested in the xhtml working draft. mozilla gives a special meaning to xul files; it expects to find ui descriptions within. for this reason, we've defined a mime type "text/xul" mapped to files with the extension ".xul". (for standards purposes, we will probably need to change the the mime type to something like "text/x-xul".) these files are processed using the same parser as "text/xml" files (and therefore subject to xml syntax rules, as they should be). it's possible to load a xul document from an xml file (one named *.xml). the r...
...ng an xml document to be a window. so currently, a single xul file must contain a single window. <?xml version="1.0"?> <?xml-stylesheet href="xul.css" type="text/css"?> <!doctype window> <window xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> ... </window> we would like to head more toward the "package" implementation in the future. internationalization for practical reasons, the locale-specific attributes of a ui description would be most happily developed (and possibly distributed) in separate files, where localization can be performed by altering only a subset of the ui description devoted expressly to localization issues. that is, a separate file of localized strings. internationalization is discussed more completely in the xul coding style guidelines document.
Multiple Rule Example - Archive of obsolete content
the ?date variable in this rule. but, you could use a <binding> to get the date without requiring it to match the conditions. of course, the variable doesn't have to be ?date in the second rule. you might notice that the ?title variable is used in the first rule whereas the ?phototitle variable is used for the second rule, despite that they both store the value of the title predicate. there is no reason for this -- it is only used in this example to show that there is no connection between the variables used in the two rules. you can use different variables if it makes sense in the context of the template or the data, although in this example it would seem more reasonable to use the same variable name. the only exception to this is that the container and member variables (those that are referred...
...looking back at the results listed above, the palace photo appears twice so the second one will be removed, leaving only three matches. ...
The Joy of XUL - Archive of obsolete content
e rich cross-platform applications that can run connected to or disconnected from the internet. these applications are easily customized with alternative text, graphics, and layout so they can be readily branded or localized for various markets. web developers already familiar with dynamic html (dhtml) will learn xul quickly and can start building applications right away. also described are some reasons application developers might choose to leverage xul and mozilla technology for building cross-platform applications. this same investigation will provide sufficient explanation of mozilla's motivation to build xul and why the mozilla platform is constructed using it. the key features and benefits of xul will be explored followed by an examination of supporting mozilla technologies. finally, a mi...
...by an examination of supporting mozilla technologies. finally, a mini case study of a calendar application written in xul will reinforce the benefits of building applications with mozilla. key features and benefits powerful widget-based markup language the goal of xul is to build cross platform applications, in contrast with dhtml which is intended for developing web pages. for this reason, xul is oriented toward application artifacts such as windows, labels, and buttons instead of pages, heading levels, and hypertext links. in fact, many developers invest a significant amount of effort to achieve these results in their dhtml web applications but at the cost of complexity and performance and without any supporting standards. based on existing standards xul is an...
Adding HTML Elements - Archive of obsolete content
ve added some buttons, let's add some other elements. adding html elements to a window in addition to all of the xul elements that are available, you can also add html elements directly within a xul file. you can actually use any html element in a xul file, meaning that java applets and tables can be placed in a window. you should avoid using html elements in xul files if you can. (there are some reasons, and the main one concerns the control of the layout described later). however, this section will describe how to use them anyway. remember that xml is case-sensitive though, so you'll have to enter the tags and attributes in lowercase. xhtml namespace in order to use html elements in a xul file, you must declare that you are doing so using the xhtml namespace. this way, mozilla can distinguish ...
...of displaying text enclosing it. to have this text appear, you would need to put it inside the div tag, or enclose the text in a description tag. note: due to bug 554290, this text actually does render in gecko 1.9.2 and later. invalid html elements <html:po>case 1</html:po> <div>case 2</div> <html:description value="case 3"/> all three of the cases above will not display, each for a different reason. case 1 po is not a valid html tag and mozilla has no idea what to do with it. case 2 div is valid but only in html. to get it to work, you will need to add the html: qualifier. case 3 a description element is only valid in xul and not in html. it should not have the html: qualifier. next, we will learn how to adding spacing between elements. « previousnext » ...
Simple Menu Bars - Archive of obsolete content
can, there's rarely a need to disable an entire menu. this attribute can be set to either true or false. of course, the latter is the default. accesskey this is the key that the user can press to activate the menu item. this letter is typically shown underlined on the menu title. mozilla will look at the label attribute and add an underline character to the character specified here. for that reason, you should specify a character that exists in the text (although the key will still work if it doesn't). the menu element is normally placed on a menubar, although it does not have to be. however, it will be given a different look. the image here shows what the earlier example would look like without the menu bar. menupopup element the menupopup element creates the popup window containing ...
...ean attribute determines whether the menu item is disabled. this attribute can be set to either true or false where the latter is the default. accesskey this is the key that the user can press to activate the menu item. this letter is typically shown underlined on the menu title. mozilla will look at the label attribute and add an underline character to the character specified here. for that reason, you should specify a character that exists in the text. acceltext this specifies the shortcut key text to appear next to the menu command text. it does not associate a key action with the menuitem however. we'll look at how to do this later. menuseparator element the menuseparator has no special attributes. it just creates a horizontal bar between the menuitems next to it. next, we'll l...
XUL accessibility guidelines - Archive of obsolete content
rm field. initial dialog focus the initial focus in a xul dialog (i.e., the focus when the dialog is first opened) should always be on a specific control, not on the dialog itself. in a tabbed dialog, focus should normally start on the first control in the selected tab. in all other dialogs, focus should just start on the first control (although it can be on any other control if there is a good reason for, just not on the dialog itself). testing keyboard access to test keyboard accessibility, simply unplug or disable your mouse and attempt to use your application with only your keyboard. verify that the tab order is logical. make sure you have access to all functionality either directly or through alternative means such as menu items or context menus. ensure that the user can read all conten...
...plications adapt well to the user's environment. system defaults maintain system defaults. many users set their computers to use larger than normal fonts and/or specific color themes. by default, xul menus, labels, and other widgets get their font, size, and color settings from the user settings specified in the operating system. respect these defaults unless you have a specific and unavoidable reason to change them. if you must change them, use css to size elements relative to the default sizes (for example, use % or em rather than specific point or pixel sizes). color color is an important tool. different colors can give different meanings to objects and text. however, color alone is inadequate for conveying meaning or information to the user. some users may override the default color sche...
Mozilla release FAQ - Archive of obsolete content
email at qc@apk.net i'll try to keep this section with only debates that are frequent that seem to have a right answer. how about a mozilla operating system? mozilla is positioned well as an application software. however, it makes very little sense to try to make mozilla into an operating sense, almost as little sense as it would to make a word processor or a mp3 player into one. beyond technical reasons, the operating system market is currently glutted, and a new entry would be unlikely to attract enough users to ensure the writing of drivers for a new system, a critical mass point. people who want to work on an operating system no doubt would be welcomed by the bsd teams, the linux team, the freedows team, or any of the many other open source operating system groups out there. how about a nets...
...mages turned off or lack capabilities to use a certain type of media. dynamically generated pages make this nearly impossible. devising a system that would handle all of these situations would make web servers more complex, slower, and likely hurt the transfer time that this proposal is attempting to save. also, progressive display of the webpage would be completely gone with this idea. for these reasons, this is generally considered a bad idea. i'd like to port mozilla to xxxos. any advice? if you're targeting a relatively recent unix, you probably will have very few problems. otherwise, the more unixlike the target system is, the easier your port will go. i would suggest that before you devote much time and effort to your port, you consider: how many users the os has that are likely to use ...
NPP_URLNotify - Archive of obsolete content
« gecko plugin api reference « plug-in side plug-in api summary notifies the plug-in instance of the completion of a url request. syntax #include <npapi.h> void npp_urlnotify(npp instance, const char* url, npreason reason, void* notifydata); parameters the function has the following parameters: instance pointer to the current plug-in instance. url url of the npn_geturlnotify() or npn_posturlnotify() request that has completed. reason reason code for completion of request. values: npres_done (most common): completed normally. npres_user_break: user canceled stream directly by clicking the stop button or indirectly by some action such as deleting the instance or initiating higher-priorit...
...ork, disk i/o, lack of memory, or other problems. notifydata plug-in-private value for associating a previous npn_geturlnotify() or npn_posturlnotify() request with a subsequent npp_urlnotify() call. description the browser calls npp_urlnotify() after the completion of a npn_geturlnotify() or npn_posturlnotify() request to inform the plug-in that the request was completed and supply a reason code for the completion. the most common reason code is npres_done, indicating simply that the request completed normally. other possible reason codes are npres_user_break, indicating that the request was halted due to a user action (for example, clicking the stop button), and npres_network_err, indicating that the request could not be completed, perhaps because the url could not be found. the ...
Introduction to SSL - Archive of obsolete content
ck known as "man in the middle." clients must perform this step and must refuse to authenticate the server or establish a connection if the domain names don't match. if the server's actual domain name matches the domain name in the server certificate, the client goes on to step 5. the server is authenticated. the client proceeds with the ssl handshake. if the client doesn't get to step 5 for any reason, the server identified by the certificate cannot be authenticated, and the user will be warned of the problem and informed that an encrypted and authenticated connection cannot be established. if the server requires client authentication, the server performs the steps described in "client authentication." after the steps described here, the server must successfully use its private key to decryp...
...tory is identical to the user's certificate presented in the ssl handshake, the server goes on to step 6. is the authenticated client authorized to access the requested resources? the server checks what resources the client is permitted to access according to the server's access control lists (acls) and establishes a connection with appropriate access. if the server doesn't get to step 6 for any reason, the user identified by the certificate cannot be authenticated, and the user is not allowed to access any server resources that require authentication. original document information author(s): [author names] other contributors: giacomo magnini last updated date: september 26, 2005 copyright information: © 2001 sun microsystems, inc. used by permission. © 2005 red hat, inc. all rights ...
Vulnerabilities - Archive of obsolete content
enable sending data between devices within a local network. however, an attacker could generate false arp messages to poison a system’s arp table and thereby launch a denial-of-service or a man-in-the-middle attack. 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. it may be hard to differentiate software feature misuse vulnerabilities from the other two categories. for example, both software flaws and misuse vulnerabilities may be caused by deficiencies in software design processes. however, software flaws are purely negative—they provide no positive benefit to security or functionality—while software feature misuse vulnerabilities occur as...
...ave any known software flaws, but security configuration issues and software feature misuse vulnerabilities are always present. misuse vulnerabilities are inherent in software features because each feature must be based on trust assumptions—and those assumptions can be broken, albeit involving significant cost and effort in some cases. security configuration issues are also unavoidable for two reasons. first, many configuration settings increase security at the expense of reducing functionality, so using the most secure settings could make the software useless or unusable. second, many security settings have both positive and negative consequences for security. an example is the number of consecutive failed authentication attempts to permit before locking out a user account. setting this to...
Styling the Amazing Netscape Fish Cam Page - Archive of obsolete content
graphs of text about the fish. here's a typical (and short) example. <div class="card"> <img src="thumb_clown_trigger.jpg" alt="clown trigger" border="0" width="150" height="115"> <h3>clown trigger</h3> <p> our clown trigger is a bold little fish, though for a few weeks he slept a lot and didn't look well in general. he's much better now. </p> </div> basically, that's all that was needed. the reason for the class value being card is that the original idea was to style each fish's description like a trading card. although this design approach was abandoned fairly quickly, the class name stuck, kind of like a barnacle. giving the fish some style with the markup all set, it was time to style. the idea was to have the fish listed in a side-by-side arrangement, sort of like a two-column table, ...
...ded that trying to overcome this error in document flow wasn't worth the effort. the layout wasn't bad if the fish weren't laid out next to each other, so i moved on. floating fish with the cards set up to float, the next step was to place the images appropriately. this involved floating the image inside the floated div. it just seemed like a fish cam page should have a lot of floating for some reason. i also added a border to the image, so that it would have a nice frame. div.card {float: left; width: 45%; margin: 1em 2% 0 2%;} div.card img {float: left; border: 1px solid #339;} that done, it was time to style the fish names. these are enclosed in h3 elements, so the field was pretty wide open in terms of what we could do. since the image was floated, any background or border we set on th...
Reference - Archive of obsolete content
are also available for function and vice versa ... --aaike82 18:54, 18 august 2006 (pdt) actual answer: object > (function, everything else). everything in javascript is descended from object, including functions. all functions in javascript (that is, every object that has an internal [[call]] or [[construct]] property) are functions as well as objects (including the function object itself). the reason object instanceof function evaluates to true is because object can be used as a constructor function. a subset of the "object > (function, everything else)" chain could be object > function > (object, function, array, string, boolean, number, date, regexp, error). array, for example, as a constructor function is an instance of the function object, which happens to be an instance of object; theref...
...al property" are synonyms, and all global functions are global objects/properties. is there something i'm missing? ruakh 20:31, 26 february 2007 (pst) this was something that was supposed to be fixed in the reorganization, which has still yet to occur. sevenspade 22:34, 26 february 2007 (pst) since it doesn't look like the reorganization is going to happen in the very near future, is there any reason i shouldn't take care of this now? ruakh 14:40, 27 february 2007 (pst) please don't start making large changes without getting an ok from dev-mdc. what did you have in mind? fwiw, i brought up the topic of jsref reorg again recently . imo, it's useful to have separates lists for global functions, global constructors, and other global properties on the contents page.--nickolay 19:10, 7 march ...
Choosing Standards Compliance Over Proprietary Practices - Archive of obsolete content
r service. even within organizations, their processes are fine-tuned to work within the existing culture. when this happens, a development standard is created and is expected to be followed. it is easy to get caught up in the process and forget why organizations have these processes in place. bottom line, organizations have them because they save money, time, and resources. sure, there are other reasons -– accountability, checkpoints, and scheduling, for example. the end result, however, is having a process in place that maximizes the organization's investment. other standards it is also important to follow other types of standards across an organization. there are numerous standards organizations that affect how and why we do what we do. for example, in the accounting arena there is fasb (...
...e users and won some others over. an example of how consistent user experience wins user loyalty can be seen in how microsoft ensures common behavior across applications. for example, in word, excel, and other windows applications, we know that pressing ctl+c within any microsoft product means copy. the behavior is consistent and predictable and has subsequently become the de-facto standard. the reason it is consistent and predictable is because microsoft has established a corporate set of usability standards and supports the relevant international standards. accessibility no organization can afford to overlook or ignore accessibility standards. within the web environment, the accessibility standards are closely tied to html, xml, xhtml, and other w3c standards. by integrating and supporting ...
RDF in Mozilla FAQ - Archive of obsolete content
ed in tools for cleaning / re-processing / storing the dmoz data too. see the sites using odp data pages for some directories based on the odp rdf dumps. what is a datasource? rdf can generally be viewed in two ways: either as a graph with nodes and arcs, or as a "soup" of logical statements. a datasource is a subgraph (or collection of statements, depending on your viewpoint) that are for some reason collected together. some examples of datasources that exist today are "browser bookmarks", "browser global history", "imap mail accounts", "nntp news servers", and "rdf/xml files". in mozilla, datasources can be composed together using the composite data source. this is like overlaying graphs, or merging collections of statements ("microtheories") together. statements about the same rdf resource...
...oaded!"); } else { alert("the datasource wasn't loaded, but it's loading now!"); } say the datasource wasn't loaded, and is loading asynchronously. using this api and javascript's settimeout(), one could set up a polling loop that would continually check the loaded property. this is kludgy, and even worse, won't detect a failed load, for example, if there wasn't any data at the url! for this reason, there is an observer interface that allows you to spy on a datasource's progress. the following code illustrates its usage: // this is the object that will observe the rdf/xml load's progress var observer = { onbeginload: function(asink) {}, oninterrupt: function(asink) {}, onresume: function(asink) {}, onendload: function(asink) { asink.removexmlsinkobserver(th...
Archive of obsolete content
here at mdn, we try to avoid outright deleting content that might be useful to people targeting legacy platforms, operating systems, and browsers. perhaps your target audience is people that are using older hardware, for example, and can't upgrade to the latest and greatest browsers. or for "reasons," your company is required to use very old software and you need to build web content that runs on that software. or perhaps you're just curious about the history of an obsolete feature or api, and how it worked. there are many reasons older documentation can be useful. so, we've established this area into which we can archive older documentation. material in this archived content zone should not be used for building new web sites or a...
... and it is maintained by pat gunn, who is not affiliated with netscape. various other people have contributed to this faq. newsgroup summaries obsolete: xpcom-based scripting for npapi plugins plugins that used to take advantage of being scriptable via liveconnect in 4.x netscape browsers lost this possibility in the new world. the main reason for this is that there is no guarantee of java compatibility on a binary level due to the jri/jni switch. the new mozilla xpcom architecture allows xpcom components be scriptable via a different mechanism called xpconnect. we leverage some of these ideas to help you make your netscape communicator 4.x plugins exposed to javascript in mozilla based browsers. plug...
Audio for Web games - Game development
ated event. 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. for other more active sounds that are to be used during the game we could consider priming them as soon as something like a start button is pressed. to prime audio like this we want to play a part of it; for this reason it is useful to include a moment of silence at the end of your audio sample. jumping to, playing, and then pausing that silence will mean we can now use javascript to play that file at arbitrary points. you can find out more about best practises with the autoplay policy here. note: playing part of your file at zero volume could also work if the browser allows you to change volume (see below). a...
... your audio does not guarantee that a small piece of audio won't be played. note: adding a web app to your mobile's homescreen may change its capabilities. in the case of autoplay on ios, this appears to be the case currently. if possible, you should try your code on several devices and platforms to see how it works. volume programmatic volume control may be disabled in mobile browsers. the reason often given is that the user should be in control of the volume at the os level and this shouldn't be overridden. buffering and preloading likely as an attempt to mitigate runaway mobile network data use, we also often find that buffering is disabled before playback has been initiated. buffering is the process of the browser downloading the media in advance, which we often need to do to ensure ...
Implementing controls using the Gamepad API - Game development
arameter and assigns the gamepad object to the gamepadapi.controller variable. we are using only one gamepad for this game, so it's a single object instead of an array of gamepads. we then set the turbo property to true. (we could use the gamepad.connected boolean for this purpose, but we wanted to have a separate variable for turning on turbo mode without needing to have a gamepad connected, for reasons explained above.) disconnect: function(evt) { gamepadapi.turbo = false; delete gamepadapi.controller; console.log('gamepad disconnected.'); }, the disconnect function sets the gamepad.turbo property to false and removes the variable containing the gamepad object. gamepad object there's lots of useful information contained in the gamepad object, with the states of buttons and axes being...
...is case, pressing or holding a will fire the bullet and pressing b will pause the game. axis threshold the buttons have only two states: 0 or 1, but the analog sticks can have many different values — they have a float range between -1 and 1 along both the x and y axes. gamepads can get dusty from lying around inactive, meaning that checking for exact -1 or 1 values can be a problem. for this reason, it can be good to set a threshold for the value of the axis to take effect. for example, the fridge tank will turn right only when the x value is bigger than 0.5: if(gamepadapi.axesstatus[0].x > 0.5) { this.player.angle += 3; this.turret.angle += 3; } even if we move it a little by mistake or the stick doesn't make it back to its original position, the tank won't turn unexpectedly. specif...
Efficient animation for web games - Game development
if you are using dom for your ui, which i would certainly recommend, you really ought to use css transitions and/or css animations, rather than javascript-powered animations. though javascript animations can be easier to express at times, unless you have a great need to synchronise ui animation state with game animation state, you’re unlikely to be able to do a better job than the browser. the reason for this is that css transitions/animations are much higher level than javascript, and express a very specific intent. because of this, the browser can make some assumptions that it can’t easily make when you’re manually tweaking values in javascript. 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...
...oticeable. measure performance there are some popular animation-related libraries and ui toolkits with animation functions that still do things like using settimeout to drive their animations, drive all their animations completely individually, or other similar things that aren’t conducive to maintaining a high frame-rate. one of the goals for the puzzowl game is for it to be a solid 60fps on reasonable hardware (for the record, it’s almost there on galaxy nexus-class hardware) while still being playable on low-end devices (such as a firefox os geeksphone keon). it would have been good to use as much third party software as possible, but most of what we tried was either too complicated for simple use-cases, or had performance issues on mobile. how this conclusion was reached, however, is ...
Polyfill - MDN Web Docs Glossary: Definitions of Web-related terms
a polyfill is a piece of code (usually javascript on the web) used to provide modern functionality on older browsers that do not natively support it. for example, a polyfill could be used to mimic the functionality of an html canvas element on microsoft internet explorer 7 using a silverlight plugin or mimic support for css rem units, or text-shadow, or whatever you want. the reason why polyfills are not used exclusively is for better functionality and better performance. native implementations of apis can do more and are faster than polyfills. for example, the object.create polyfill only contains the functionalities that are possible in a non-native implementation of object.create. other times, polyfills are used to address issues where browsers implement the same features in differe...
...s. for example, the object.create polyfill only contains the functionalities that are possible in a non-native implementation of object.create. other times, polyfills are used to address issues where browsers implement the same features in different ways. the polyfill uses non-standard features in a certain browser to give javascript a standards-compliant way to access the feature. although this reason for polyfilling is very rare today, it was especially prevalent back in the days of ie6, netscape, and nnav where each browser implemented javascript very differently. the 1st version of jquery was an early example of a polyfill. it was essentially a compilation of browser-specific workarounds so that javascript developers could have a single common api that worked in all browsers. at the time, j...
HTML: A good basis for accessibility - Learn web development
find more out about whales, <a href="whales.html">click here</a>.</p> note: you can find a lot more about link implementation and best practices in our creating hyperlinks article. you can also see some good and bad examples at good-links.html and bad-links.html. form labels are also important for giving you a clue about what you need to enter into each form input. the following seems like a reasonable enough example: fill in your name: <input type="text" id="name" name="name"> however, this is not so useful for disabled users. there is nothing in the above example to associate the label unambiguously with the form input and make it clear how to fill it in if you cannot see it. if you access this with some screen readers, you may only be given a description along the lines of "edit text."...
...""> tyrannosaurus rex: the king of the dinosaurs </h3> there may be times where an image is included in a page's design, but its primary purpose is for visual decoration. you'll notice in the code example above that the image's alt attribute is empty — this is to make screen readers recognize the image, but not attempt to describe the image (instead they'd just say "image", or similar). the reason to use an empty alt instead of not including it is because many screen readers announce the whole image url if no alt is provided. in the above example, the image is acting as a visual decoration to the heading it's associated with. in cases like this, and in cases where an image is only decoration and has no content value, you should include an empty alt in your img elements. another alternative...
HTML: A good basis for accessibility - Learn web development
find more out about whales, <a href="whales.html">click here</a>.</p> note: you can find a lot more about link implementation and best practices in our creating hyperlinks article. you can also see some good and bad examples at good-links.html and bad-links.html. form labels are also important for giving you a clue about what you need to enter into each form input. the following seems like a reasonable enough example: fill in your name: <input type="text" id="name" name="name"> however, this is not so useful for disabled users. there is nothing in the above example to associate the label unambiguously with the form input and make it clear how to fill it in if you cannot see it. if you access this with some screen readers, you may only be given a description along the lines of "edit text."...
...""> tyrannosaurus rex: the king of the dinosaurs </h3> there may be times where an image is included in a page's design, but its primary purpose is for visual decoration. you'll notice in the code example above that the image's alt attribute is empty — this is to make screen readers recognize the image, but not attempt to describe the image (instead they'd just say "image", or similar). the reason to use an empty alt instead of not including it is because many screen readers announce the whole image url if no alt is provided. in the above example, the image is acting as a visual decoration to the heading it's associated with. in cases like this, and in cases where an image is only decoration and has no content value, you should include an empty alt in your img elements. another alternative...
What is accessibility? - Learn web development
phic made using webgl, you might want to include a data table as an accessible alternative representation of the data. or, you might want to just include the table and get rid of the 3d pie chart — the table is accessible by everyone, quicker to code, less cpu-intensive, and easier to maintain. on the other hand, if you are working on a gallery website showing interesting 3d art, it would be unreasonable to expect every piece of art to be perfectly accessible to visually impaired people, given that it is an entirely visual medium. to show that you care and have thought about accessibility, publish an accessibility statement on your site that details what your policy is toward accessibility, and what steps you have taken toward making the site accessible. if someone does complain that your si...
... people, given that it is an entirely visual medium. to show that you care and have thought about accessibility, publish an accessibility statement on your site that details what your policy is toward accessibility, and what steps you have taken toward making the site accessible. if someone does complain that your site has an accessibility problem, start a dialog with them, be empathic, and take reasonable steps to try to fix the problem. note: our handling common accessibility problems article covers accessibility specifics that should be tested in more detail. to summarize: consider accessibility from the start of a project, and test early and often. just like any other bug, an accessibility problem becomes more expensive to fix the later it is discovered. bear in mind that a lot of a...
Organizing your CSS - Learn web development
ing which won't appear in the code you can jump from section to section by searching for it — below we have used ||. /* || general styles */ ... /* || typography */ ... /* || header and main navigation */ ... you don't need to comment every single thing in your css, as much of it will be self-explanatory. what you should comment are the things where you made a particular decision for a reason. you may have used a css property in a specific way to get around older browser incompatibilities, for example: .box { background-color: red; /* fallback for older browsers that don't support gradients */ background-image: linear-gradient(to right, #ff0000, #aa0000); } perhaps you followed a tutorial to achieve something, and the css is a little non-obvious. in that case you could add the...
...ain a couple of the things that sass can do, which are really helpful in terms of organisation, even if you don't use any of the other sass features. if you want to learn a lot more about sass, start with the sass basics article, then move on to their other documentation. defining variables css now has native custom properties, making this feature increasingly less important, however one of the reasons you might use sass is to be able to define all of the colors and fonts used in a project as settings, then use that variable around the project. this means that if you realise you have used the wrong shade of blue, you only need change it in one place. if we created a variable called $base-color as in the first line below, we could then use it through the stylesheet anywhere that required that ...
Styling links - Learn web development
r things. if you don't want to underline links, at least highlight them in some other way. make them react in some way when hovered/focused, and in a slightly different way when activated. the default styles can be turned off/changed using the following css properties: color for the text color. cursor for the mouse pointer style — you shouldn't turn this off unless you've got a very good reason. outline for the text outline (an outline is similar to a border, the only difference being that border takes up space in the box and an outline doesn't; it just sits over the top of the background). the outline is a useful accessibility aid, so think carefully before turning it off; you should at least double up the styles given to the link hover state on the focus state too. note: you are n...
...rd ones), and we can select this with an attribute selector: a[href*="http"] selects <a> elements, but only if they have an href attribute with a value that contains "http" somewhere inside it. so that's it — try revisiting the active learning section above and trying this new technique out! note: the href values look strange — we've used dummy links here that don't really go anywhere. the reason for this is that if we used real links, you would be able to load an external site in the <iframe> the live example is embedded in, thereby losing the example. note: don't worry if you are not familiar with backgrounds and responsive web design yet; these are explained in other places. styling links as buttons the tools you've explored so far in this article can also be used in other ways. ...
How much does it cost to do something on the Web? - Learn web development
up photos, or produce audio and video files. you need to upload content to a remote server (see hosting below), so you need a modem. your isp can rent internet connectivity to you for a few dollars per month, though your budget might vary, depending on your location. isp access make sure that you have sufficient bandwidth: low-bandwidth access may be adequate to support a 'simple' website: reasonably-sized images, texts, some css and javascript. that will likely cost you a few dozen dollars, including the rent for the modem. on the other hand, you'll need a high-bandwidth connection, such as dsl, cable, or fiber access, if you want a more advanced website with hundreds of files, or if you want to deliver heavy video/audio files directly from your web server. it could cost the same as low...
...much bandwidth your website consumes. this depends on how many people, and web crawling robots, access your content during a given time, and how much server space your content takes up. this is why people usually store their videos on dedicated services such as youtube, dailymotion, and vimeo. for example, your provider may have a plan that includes up to several thousand visitors per day, for “reasonable” bandwidth usage. be careful, however as this is defined differently from one hosting provider to another. as a rule of thumb, recognize that reliable, paid, personal hosting can cost around ten to fifteen dollars per month. note that there is no such thing as “unlimited” bandwidth. if you consume a huge amount of bandwidth, expect to pay a huge amount of money. domain names your d...
Client-side form validation - Learn web development
itting data to the server, it is important to ensure all required form controls are filled out, in the correct format. this is called client-side form validation, and helps ensure data submitted matches the requirements set forth in the various form controls. this article leads you through basic concepts and examples of client-side form validation. prerequisites: computer literacy, a reasonable understanding of html, css, and javascript. objective: to understand what client-side form validation is, why it's important, and how to apply various techniques to implement it. client-side validation is an initial check and an important feature of good user experience; by catching invalid data on the client-side, the user can fix it straight away. if it gets to the server...
...rmation is correctly formatted, the application allows the data to be submitted to the server and (usually) saved in a database; if the information isn't correctly formatted, it gives the user an error message explaining what needs to be corrected, and lets them try again. we want to make filling out web forms as easy as possible. so why do we insist on validating our forms? there are three main reasons: we want to get the right data, in the right format. our applications won't work properly if our users' data is stored in the wrong format, is incorrect, or is omitted altogether. we want to protect our users' data. forcing our users to enter secure passwords makes it easier to protect their account information. we want to protect ourselves. there are many ways that malicious users can misu...
How to build custom form controls - Learn web development
asiest way to do this is to use a native control under the hood. such a control will keep track of the value with all the built-in controls provided by the browser, and the value will be sent as usual when a form is submitted. there's no point in reinventing the wheel when we can have all this done for us. as seen previously, we already use a native select control as a fallback for accessibility reasons; we can simply synchronize its value with that of our custom control: // this function updates the displayed value and synchronizes it with the native control. // it takes two parameters: // select : the dom node with the class `select` containing the value to update // index : the index of the value to be selected function updatevalue(select, index) { // we need to get the native control fo...
...get.selectedindex = index; value.innerhtml = optionlist[index].innerhtml; highlightoption(select, optionlist[index]); }; it might have seemed simpler to let a screen reader focus on the off-screen select and ignore our stylized one, but this is not an accessible solution. screen readers are not limited to blind people; people with low vision and even perfect vision use them as well. for this reason, you can not have the screen reader focus on an off-screen element. here is the final result of all these changes (you'll get a better feel for this by trying it with an assistive technology such as nvda or voiceover): live example check out the final source code if you want to move forward, the code in this example needs some improvement before it becomes...
JavaScript basics - Learn web development
ss. it applies the javascript to the page, so it can have an effect on the html (along with the css, and anything else on the page). add this code to the main.js file: const myheading = document.queryselector('h1'); myheading.textcontent = 'hello world!'; make sure the html and javascript files are saved. then load index.html in your browser. you should see something like this: note: the reason the instructions (above) place the <script> element near the bottom of the html file is that the browser reads code in the order it appears in the file. if the javascript loads first and it is supposed to affect the html that hasn't loaded yet, there could be problems. placing javascript near the bottom of an html page is one way to accommodate this dependency. to learn more about alternative ap...
...enter your user name, try pressing the cancel button. you should end up with a title that reads mozilla is cool, null. this happens because—when you cancel the prompt—the value is set as null. null is a special value in javascript that refers to the absence of a value. also, try clicking ok without entering a name. you should end up with a title that reads mozilla is cool, for fairly obvious reasons. to avoid these problems, you could check that the user hasn't entered a blank name. update your setusername() function to this: function setusername() { let myname = prompt('please enter your name.'); if(!myname) { setusername(); } else { localstorage.setitem('name', myname); myheading.innerhtml = 'mozilla is cool, ' + myname; } } in human language, this means: if myname ...
Tips for authoring fast-loading HTML pages - Learn web development
ng a specialized tool such as compress jpeg or tiny png,. specify sizes for images and tables if the browser can immediately determine the height and/or width of your images and tables, it will be able to display a web page without having to reflow the content. this not only speeds the display of the page but prevents annoying changes in a page's layout when the page completes loading. for this reason, height and width should be specified for images, whenever possible. tables should use the css selector: property combination: table-layout: fixed; and should specify widths of columns using the <col> and the <colgroup> elements. use lazy loading for images by default, imags are loaded eagerly; that is, the image is fetched and rendered as soon as it's processed in the html. all eagerly l...
...nly be loaded when it's needed. <img href="./images/footerlogo.jpg" loading="lazy"> note that lazily-loaded images may not be available when the load event is fired. you can determine if a given image is loaded by checking to see if the value of its boolean complete property is true. choose your user-agent requirements wisely to achieve the greatest improvements in page design, make sure that reasonable user-agent requirements are specified for projects. do not require your content to appear pixel-perfect in all browsers, especially not in down-version browsers. ideally, your basic minimum requirements should be based on the consideration of modern browsers that support the relevant standards. this can include recent versions of firefox, internet explorer, google chrome, opera, and safari. ...
Making asynchronous programming easier with async and await - Learn web development
pt 2017 javascript edition (see ecmascript next support in mozilla). these features basically act as syntactic sugar on top of promises, making asynchronous code easier to write and to read afterwards. they make async code look more like old-school synchronous code, so they're well worth learning. this article gives you what you need to know. prerequisites: basic computer literacy, a reasonable understanding of javascript fundamentals, an understanding of async code in general and promises. objective: to understand promises and how to use them. the basics of async/await there are two parts to using async/await in your code. the async keyword first of all we have the async keyword, which you put in front of a function declaration to turn it into an async functio...
...ew error(`http error! status: ${response.status}`); } else { return response.blob(); } }) .then(myblob => { let objecturl = url.createobjecturl(myblob); let image = document.createelement('img'); image.src = objecturl; document.body.appendchild(image); }) .catch(e => { console.log('there has been a problem with your fetch operation: ' + e.message); }); by now, you should have a reasonable understanding of promises and how they work, but let's convert this to use async/await to see how much simpler it makes things: async function myfetch() { let response = await fetch('coffee.jpg'); if (!response.ok) { throw new error(`http error! status: ${response.status}`); } else { let myblob = await response.blob(); let objecturl = url.createobjecturl(myblob); let ...
Manipulating documents - Learn web development
h the core dom apis, and the other apis commonly associated with dom and document manipulation the important parts of a web browser web browsers are very complicated pieces of software with a lot of moving parts, many of which can't be controlled or manipulated by a web developer using javascript. you might think that such limitations are a bad thing, but browsers are locked down for good reasons, mostly centering around security. imagine if a web site could get access to your stored passwords or other sensitive information, and log into websites as if it were you? despite the limitations, web apis still give us access to a lot of functionality that enable us to do a great many things with web pages. there are a few really obvious bits you'll reference regularly in your code — conside...
...adable by search engines). in the next couple of sections we will look at a couple of more practical uses of dom apis. note: you can find our finished version of the dom-example.html demo on github (see it live also). active learning: getting useful information from the window object so far we've only really looked at using node and document features to manipulate documents, but there is no reason why you can't get data from other sources and use it in your ui. you just have to make sure your data is in the right format; javascript makes it easier than many other languages, being weakly typed — for example numbers will convert to strings automatically when you want to print them to the screen. in this example we will solve a common problem — making sure your application is as big as t...
Third-party APIs - Learn web development
ing, etc. note: if you have trouble getting the example to work, check your code against our finished version — see expanded-example.html (also see it running live here). what about google maps? google maps is arguably the most popular maps api, so why didn't we use it for our maps example? we did create an example to show how to use it, but in the end we went with mapquest for a couple of reasons: it is much easier to get started with. for google apis in general, you need to create a google account and log into the google cloud platform console to create api keys, etc., and the process is fairly complex. for the google maps api in particular, you need to provide a credit card for billing purposes (although basic usage is free), which we didn't think was acceptable for a basic tutorial...
... can use as an approach for working with new apis. find the documentation when you want to use a third party api, it is essential to find out where the documentation is, so you can find out what features the api has, how you use them, etc. the new york times api documentation is at https://developer.nytimes.com/. get a developer key most apis require you to use some kind of developer key, for reasons of security and accountability. to sign up for an nytimes api key, following the instructions at https://developer.nytimes.com/get-started. let's request a key for the article search api — create a new app, selecting this as the api you want to use (fill in a name and description, toggle the switch under the "article search api" to the on position, and then click "create"). get the...
Video and Audio APIs - Learn web development
; box-shadow: 3px 3px 5px black; transition: 1s all; display: flex; } .player:hover .controls, player:focus .controls { opacity: 1; } we start off with the visibility of the custom controls set to hidden. in our javascript later on, we will set the controls to visible, and remove the controls attribute from the <video> element. this is so that, if the javascript doesn't load for some reason, users can still use the video with the native controls. we give the controls an opacity of 0.5 by default, so that they are less distracting when you are trying to watch the video. only when you are hovering/focusing over the player do the controls appear at full opacity. we lay out the buttons inside the control bar using flexbox (display: flex), to make things easier. next, let's look at o...
...the content property to set the content to be displayed in each case to be equal to the contents of the data-icon attribute. in the case of our play button, data-icon contains a capital "p". we apply the custom web font to our buttons using font-family. in this font, "p" is actually a "play" icon, so therefore the play button has a "play" icon displayed on it. icon fonts are very cool for many reasons — cutting down on http requests because you don't need to download those icons as image files, great scalability, and the fact that you can use text properties to style them — like color and text-shadow. last but not least, let's look at the css for the timer: .timer { line-height: 38px; font-size: 10px; font-family: monospace; text-shadow: 1px 1px 0px black; color: white; flex...
Aprender y obtener ayuda - Learn web development
rticles for more in-depth learning and reference material, and videos for quick explanations of concepts and new features, but it is really up to you what you prefer to learn from. there is no right and wrong answer here. interactive code playgrounds you might be the kind of person that prefers minimal instructions and would prefer to jump straight in and start playing with code. this is also a reasonable approach, and some learning sites tend to favor it. codecademy for example is a learning site where the tutorials mainly consist of interactive code editors where you have to directly write code and see if the desired result was achieved. many mdn web docs reference pages provide interactive examples too, where you can alter the code and see how the live result changes. and there is also not...
...ays what you want to achieve? the following have different scopes, but are all realistic and achievable: i want to become a professional web developer in two years' time. i want to learn enough to build a website for my local amateur tennis club. i want to learn html and css so i can expand my job role to take over updating the content on our company website. the following are not quite as reasonable: i want to go from a complete beginner to becoming a senior web developer in three months. i want to start my own company and build a social network that will out-perform facebook, in two years. what do you need to get there? once you've worked out your goal, it is a good idea to research what you'll need to achieve the goal. for example: materials i need: a computer internet acce...
Routing in Ember - Learn web development
eatures (such as classes, modules, etc), will be extremely beneficial, as ember makes heavy use of them. objective: to learn about implementing routing in ember. url-based filtering ember comes with a routing system that has a tight integration with the browser url. typically, when writing web applications, you want the page to be represented by the url so that if (for any reason), the page needs to refresh, the user isn't surprised by the state of the web app — they can link directly to significant views of the app. at the moment, we already have the "all" page, as we are currently not doing any filtering in the page that we've been working with, but we will need to reorganize it a bit to handle a different view for the "active" and "completed" todos. an ember applic...
... the available model, calling its activetodos() getter to make sure only the active (incomplete) todos are shown. in this file, change <todolist /> to <todolist @todos={{ @model.activetodos }}/> note that, in each of the route model hooks, we are returning an object with a getter instead of a static object, or more simply just the static list of todos (for example, this.todos.completed). the reason for this is that we want the template to have a dynamic reference to the todo list, and if we returned the list directly, the data would never re-compute, which would result in the navigations appearing to fail / not actually filter. by having a getter defined in the return object from the model data, the todos are re-looked-up so that our changes to the todo list are represented in the rendered ...
Getting started with React - Learn web development
terns. its biggest departure from javascript comes with the use of jsx syntax. jsx extends javascript's syntax so that html-like code can live alongside it. for example: const heading = <h1>mozilla developer network</h1>; this heading constant is known as a jsx expression. react can use it to render that <h1> tag in our app. suppose we wanted to wrap our heading in a <header> tag, for semantic reasons? the jsx approach allows us to nest our elements within each other, just like we do with html: const header = ( <header> <h1>mozilla developer network</h1> </header> ); note: the parentheses in the previous snippet aren't unique to jsx, and don’t have any effect on your application. they're a signal to you (and your computer) that the multiple lines of code inside are part of the sa...
.... on line 3, the opening <div> tag has a classname attribute. this is the same as the class attribute in html, but because jsx is javascript, we can't use the word class — it's reserved, meaning javascript already uses it for a specific purpose and it would cause problems here in our code. a few other html attributes are written differently in jsx than they are in html too, for the same kind of reason. we'll cover them as we encounter them. take a moment to change the <p> tag on line 6 so that it reads "hello, world!", then save your file. you'll notice that this change is immediately rendered in the development server running at http://localhost:3000 in your browser. now delete the <a> tag and save; the "learn react" link will be gone. your app component should now look like this: function...
Componentizing our Svelte app - Learn web development
.svelte file. components can be big or small, but they are usually clearly defined: the most effective components serve a single, obvious purpose. the benefits of defining components are comparable to the more general best practice of organizing your code into manageable pieces. it will help you understand how they relate to each other, it will promote reuse, and it will make your code easier to reason about, maintain, and extend. but how do you know what should be split into its own component? there are no hard rules for this. some people prefer an intuitive approach and start looking at the markup and drawing boxes around every component and subcomponent that seems to have its own logic. other people apply the same techniques used for deciding if you should create a new function or object.
...n, events-up" communication pattern. basically, this pattern relies on child components receiving data from their parents via props and parent components updating their state by handling events emitted from child components. so props flow down from parent to child and events bubble up from child to parent. this pattern establishes a two-way flow of information, which is predictable and easier to reason about. let's look at how to emit our own events to re-implement the missing delete button functionality. to create custom events we'll use the createeventdispatcher utility. this will return a dispatch() function that will allow us to emit custom events. when you dispatch an event you have to pass the name of the event and, optionally, an object with additional information that you want to pass...
Working with Svelte stores - Learn web development
n. we could move all the methods that modify the todo array (like addtodo(), removetodo(), etc) from our todos component to the store. if you have a central place where all the state modification is applied, components could just call those methods to modify the app's state and reactively display the info exposed by the store. having a unique place to handle state modifications makes it easier to reason about the state flow and spot issues. svelte won't force you to organize your state management in a specific way, it just provides the tools for you to choose how to handle it. implementing our custom todos store our to-do list app is not particularly complex, so we won't move all our modification methods into a central place. we'll just leave them as they are, and instead concentrate on persi...
...ls for you to choose how to handle it. implementing our custom todos store our to-do list app is not particularly complex, so we won't move all our modification methods into a central place. we'll just leave them as they are, and instead concentrate on persisting our todos. note: if you are following this guide working from the svelte repl you won't be able to complete this step. for security reasons the svelte repl works in a sandboxed environment which will not let you access web torage, and you will get a "the operation is insecure" error. in order to follow this section you'll have to clone the repo and go to the mdn-svelte-tutorial/06-stores folder or you can directly download the folder's content with npx degit opensas/mdn-svelte-tutorial/06-stores. so, to implement a custom store th...
Introduction to cross browser testing - Learn web development
ge of browsers and devices that the code definitely needs to work on with the site owner, but beyond that, you need to code defensively to give other browsers the best chance possible of being able to use your content. this is one of the great challenges of web development. note: we'll cover defensive coding later in the module too. why do cross browser issues occur? there are many different reasons why cross browser issues occur, and note that here we are talking about issues where things behave different across different browsers / devices / browsing preferences. before you even get to cross browser issues, you should have already fixed out bugs in your code (see debugging html, debugging css, and what went wrong? troubleshooting javascript from previous topics to refresh your memory if n...
...compiler where needed. some devices may have constraints that cause a web site to run slowly, or display badly. for example, if a site has been designed to look nice on a desktop pc, it will probably look tiny and be hard to read on a mobile device. if your site includes a load of big animations, it might be ok on a high spec tablet, but might be sluggish or jerky on a low end device. and more reasons besides. in later articles, we'll explore common cross browser problems, and look at solutions to those. workflows for cross browser testing all of this cross browser testing business may sound time consuming and scary, but it needn't be — you just need to plan carefully for it, and make sure you do enough testing in the right places to make sure you don't run into unexpected problems. if y...
Strategies for carrying out testing - Learn web development
to do this, you will probably use a combination of actual physical devices, and emulated environments (using either an emulator or a virtual machine). physical devices it is generally better to have a real device running the browser you want to test — this provides the greatest accuracy in terms of behaviour and overall user experience. you'll probably want something like the following, for a reasonable low-level device lab: a mac, with the browsers installed that you need to test — this can include firefox, chrome, opera, and safari. a windows pc, with the browsers installed that you need to test — this can include edge (or ie), chrome, firefox, and opera. a higher-spec android phone and tablet with browser installed that you need to test — this can include chrome, firefox, and o...
...re often than not though, you'll have to install some kind of emulator. the most common devices/browsers you'll want to test are as follows: the official android studio ide for developing android apps is a bit heavy weight for just testing websites on google chrome or the old stock android browser, but it does come with a robust emulator. if you want something a bit more lightweight, andy is a reasonable option that runs on both windows and mac. apple provides an app called simulator that runs on top of the xcode development environment, and emulates ipad/iphone/apple watch/apple tv. this includes the native ios safari browser. this unfortunately only runs on a mac. you can often find simulators for other mobile device environments too, for example: blackberry (emulator available for wi...
Setting up your own test automation environment - Learn web development
ceholders in the code with your actual user name and access key values): driver.sleep(2000).then(function() { driver.gettitle().then(function(title) { if(title === 'webdriver - google search') { console.log('test passed'); request({uri: "https://your-user-name:your-access-key@www.browserstack.com/automate/sessions/" + sessionid + ".json", method:"put", form:{"status":"passed","reason":"google results showed correct title"}}); } else { console.log('test failed'); request({uri: "https://your-user-name:your-access-key@www.browserstack.com/automate/sessions/" + sessionid + ".json", method:"put", form:{"status":"failed","reason":"google results showed wrong title"}}); } }); }); these are fairly intuitive — once the test completes, we send an api call to...
...log('test failed'); request({uri: "https://your-user-name:your-access-key@www.browserstack.com/automate/sessions/" + sessionid + ".json", method:"put", form:{"status":"failed","reason":"google results showed wrong title"}}); } }); }); these are fairly intuitive — once the test completes, we send an api call to browserstack to update the test with a passed or failed status, and a reason for the result. if you now go back to your browserstack automation dashboard page, you should see your test session available, as before, but with the updated data attached to it: sauce labs getting selenium tests to run remotely on sauce labs is also very simple, and very similar to browserstack albeit with a few syntactic differences. the code you need should follow the pattern seen below.
Client-side tooling overview - Learn web development
ow to find help with individual tools. prerequisites: familiarity with the core html, css, and javascript languages. objective: to understand what types of client-side tooling there are, and how to find tools and get help with them. overview of modern tooling writing software for the web has become more sophisticated through the ages. although it is still entirely reasonable to write html, css, and javascript "by hand" there is now a wealth of tools that developers can use to speed up the process of building a web site, or app. there are some extremely well-established tools that have become common "household names" amongst the development community, and new tools are being written and released every day to solve specific problems. you might even find yourself w...
...sed in isolation, so although there’s almost certainly help available it’s never in the same place or format. it can therefore be hard to find help with using a tool, or even to choose what tool to use. the knowledge about which are the best tools to use is a bit tribal, meaning that if you aren’t already in the web community, it is hard to find out exactly which ones to go for! this is one reason we wrote this series of articles, to hopefully provide that first step that is hard to find otherwise. you’ll probably need a combination of the following things: experienced teachers, mentors, fellow students, or colleagues that have some experience, have solved such problems before, and can give advice. a useful specific place to search. general web searches for front-end developer tools...
Mozilla accessibility architecture
if a child accessible of the document is asked for first, the doc accessible will be created first, because it is needed to cache any accessibles created within it. when the doc accessible is asked for, an event is fired which reaches the presshell, which then uses the accessibility service singleton (nsiaccessibilityservice) to create the doc accessible and return it back to the widget code. the reason that the doc accessible is not created directly in the widget code where it's needed is that the widget code has no knowledge what nsidomnode is associated with the current window's document object. there must be a document for the current widget (nswindow/nsiwidget) for the pres shell to create a doc accessible for it. one benefit of this approach is that accessibility.dll/libaccessibility.so do...
...s or stops, to avoid extra events being fired) nsdocaccessible::onstatechange(), :nsdocaccessible:onlocationchange() nsiwebprogresslistener callback event_state_change (msaa) event_reorder (atk) dom mutation events - multiple uses dom mutation events are a great thing. they are fired by gecko whenever nodes in the document are created, moved or changed. common reasons for these mutations are web page scripts, and user actions in the editor. we listen to dom mutation events for several resons: to broadcast document changes to the assistive technology client. however, on windows there are crash issues with the automatic windows-generated versions of event_create and event_destroy, so the msaa client cannot listen to them. we fire the safer event_reorder in t...
Gecko info for Windows accessibility vendors
currently support directional navigation via accnavigate() we do not currently support scroll bars as iaccessible objects, although we do support event_scrollingend and isimpledomnode::scrollto(), explained below. we do not currently support state_moveable, state_sizeable or state_marqueed. we do not currently support role_system_row, although internet explorer doesn't either, and the reason seems apparent. it is not obvious where the role_system_row should exist in the tree when the html rowspan attribute is used to combine to cells in different rows. there are currently two techniques for parsing tables: 1) use acclocation() to get the coordinates for each cell and feed that into an algorithm that builds up your own table data structure, or 2) use isimpledomnode and parse the table...
...> dhtml: role="wairole:label" or role="wairole:description" supports navrelation_label_for and navrelation_description_for via accnavigate(). the accname is an accumulation of the descendents' accnames, so may be considered redundant with them. the accname is also reflected in the accname of a form control that this labels, which is a good reason to check navrelation_label_for. role_text normal web text uses no tag or element, uses state_readonly for editable text, that state is cleared. xul: <textbox> html: <input type="text"> or <textarea> dhtml: role="wairole:textfield" or role="wairole:textarea" sets state_linked if within lin...
Accessible Toolkit Checklist
ee item supporting the most important basic iaccessible events get_accparent: get the parent of an iaccessible. get_accchildcount: get the number of children of an iaccessible. get_accchild: get the child of an iaccessible. get_accname: get the "name" of the iaccessible, for example the name of a button, checkbox or menu item. this is one reason why a label must be created together with each widget, rather than separately. get_accvalue: get the "value" of the iaccessible, for example a number in a slider, a url for a link, the text a user entered in a field. get_accrole: get an enumerated value representing what this iaccessible is used for, for example. is it a link, static text, editable text, a checkbox, or a table...
...ark border when link is focused) msaa support, including linked and traversed states, and accessible value that holds destination url text fields - single and multiple line it's probably best to use native widgets for these, otherwise accessibility support will be quite difficult tab should always focus the next item, not insert a tab, unless there's a really good reason and another way to navigate always use system selection color, otherwise screen reader won't read the text make sure the caret is never blinking when focus is not in text field handle standard editing keys, such as arrow keys, home, end, pageup, pagedown, ctrl+left/right, shifted keys for selection, delete, ctrl+delete, backspace, ctrl+backspace, ctrl+a, ctrl+b, ctrl+c, ctrl+i, ...
Creating reftest-based unit tests
./mach reftest path/to/reftest.txt 2>&1 | grep reftest reftest pass: file:///users/ray/mo/spaces1.html reftest pass: (!=) file:///users/ray/mo/spaces3.html $ fabulous! other comparisons note that it should also be possible to create a reftest that tests markup against an actual graphic image of the visual construct that should result. this is probably going to be a more fragile test, for the reasons described above. but it may be necessary. for example, say that certain markup should produce a certain sanskrit glyph. how does one test that? 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. more investigation into whether this will work is definitely warranted. experiments with this have...
... soon as the test finishes loading and moving on to the next test. next you need to add a listener for the 'mozreftestinvalidate' event, and only make the changes you want to test invalidation for after that event has fired. third, you need to remove 'reftest-wait' from the root element's 'class' attribute to tell the reftest framework that the test is now ready to have its rendering tested. the reason for using the 'mozreftestinvalidate' event is because a document's initial painting is not typically finished when the 'load' event fires. it would be possible to try and wait for the initial rendering to be done using a settimeout, but that would be unreliable, and just as bad, it can increase the time it takes to run a test many times over (which when you're running thousands of tests can reall...
Debugging Frame Reflow
when the frame's reflow is finished the following information is displayed : reflow metric (desired) width, height max. ...
...7b5f0 d=1500,390 text 02d7c130 r=0 a=8940,uc c=uc,uc cnt=885 text 02d7c130 d=0,0 block 02d7b210 d=8940,390 area 02d7afe4 d=9180,630 canvas 00b97c6c d=9180,4470 scroll 00b97ee0 d=9180,4470 scroll 00b97ee0 d=9180,4470 vp 00b97c30 d=9180,4470 the first line shows the reflow of the viewport (vp). this viewport has the address 00b97c30. it is the initial reflow: r=0. other reflow reasons are: incremental reflow resize reflow style change reflow dirty reflow the available width is 9180 twips. the available height is 4470 twips (a=9180,4470). the computed width is 9180 twips. the computed height is 4470 twips (c=9180,4470). the line count is 856 (cnt=856). below this is a line that reads: tblo 02d7b5f0 r=0 a=8940,uc c=0,0 cnt=870 here the uc shows that on initial reflow ...
mozbrowsercaretstatechanged
possible values are visibilitychange, updateposition, longpressonemptycontent, taponcaret, presscaret, and releasecaret. zoomfactor a number defining the current zoom factor in the browser <iframe>. collapsed a boolean indicating whether the current selection is collapsed (true) or not (false.) caretvisible a boolean indicati...
...n indicating whether the selectall command is available (true) or not (false.) cancut: a boolean indicating whether the cut command is available (true) or not (false.) cancopy: a boolean indicating whether the copy command is available (true) or not (false.) canpaste: a boolean indicating whether the paste command is available (true) or not (false.) reason a domstring that defines the reason for the state being changed. possible values are visibilitychange, updateposition, longpressonemptycontent, taponcaret, presscaret, and releasecaret. zoomfactor a number defining the current zoom factor in the browser <iframe>. collapsed a boolean indicating whether the current selection is collapsed (true) or not (false.) caretvisible a boolean indicating whether the caret is currently vis...
Gecko SDK
pt. note that in order to develop such components, you do not need the full sources of e.g. firefox, since you do not access parts of the front end from within a component. furthermore, since a component contains basic functionality, it is intended to run with every product of the mozilla platform. therefore it makes no sense to use a particular product to build general functionality. that's the reason why the gecko sdk was devised. do not confuse the gecko/xulrunner sdk with xulrunner itself. the gecko sdk is a collection of header files and tools used to develop general xpcom components which add functionality to the existing platform, whereas xulrunner is a framework which can be used to run standalone or embedded applications based on the mozilla framework. the gecko sdk contains all of t...
...dule on the web. unpack the sdk tarball to some suitable location. issues with the os x sdk if you need to use the xpidl utility to compile idl files on os x, it's likely that you will receive a strange error when running the tool that looks something along the lines of this: dyld: library not loaded: /opt/local/lib/libintl.3.dylib referenced from: /users/varmaa/xulrunner-sdk/bin/./xpidl reason: image not found trace/bpt trap unfortunately, this is caused by a problem with the sdk build process which cannot currently be resolved (see bugzilla bug #430274). to get around it, you'll need to first install macports as outlined in the mac os x build prerequisites and install libidl with it. on 64-bit versions of mac os x, you'll need to install libidl with the +universal flag. once that's...
Addon
l," which means that the optional methods or property may not exist on addon instances for some types of add-ons. api consumers should take care to verify the existence of these methods or properties before relying on them. ...
...ersion. void iscompatiblewith( in string appversion, in string platformversion ) parameters appversion an application version to test against platformversion a platform version to test against findupdates() starts an update check for this add-on. this will perform asynchronously and deliver results to the given listener. void findupdates( in updatelistener listener, in integer reason, in string appversion, in string platformversion ) parameters listener an updatelistener for the update process reason a reason code for performing the update appversion an application version to check for updates for platformversion a platform version to check for updates for optional methods uninstall() uninstalls this add-on. if possible the uninstall will happen immediately...
CustomizableUI.jsm
idget's node, acontainer is the area it was moved into (nb: it might already have been there and been moved to a different position!) onareareset(aarea, acontainer) fired after a reset to default placements is complete on an area's dom node. note that this is fired for each dom node. aarea is the area that was reset, acontainer the dom node that was reset. onareanodeunregistered(aarea, anode, areason) fired when an area's dom node is unregistered. aarea is the area for which a node was unregistered, anode the dom node which was unregistered, and areason indicates whether the area as a whole was unregistered (reason_area_unregistered), or whether a window closed (reason_window_closed). onareanoderegistered(aarea, anode) fired after an area node is first built when it is registered. this is ...
...ip toolbar. area_menubar string "toolbar-menubar", a constant reference to the id of the menubar's toolbar. area_bookmarks string "personaltoolbar", a constant reference to the id of the bookmarks toolbar. area_addonbar deprecated string "addon-bar", a constant reference to the id of the add-on toolbar shim. do not use, this will be removed as soon as reasonably possible. area_panel string "panelui-contents", a constant reference to the id of the menu panel. type_toolbar string "toolbar", a constant indicating the area is a toolbar. type_menu_panel string "menu-panel", a constant indicating the area is a menu panel. widget constants provider_xul string "xul", a constant indicating an...
Following the Android Toasts Tutorial from a JNI Perspective
le. we want to wrap this in a try-catch statement so if any errors occur we make sure to unload the classes and the java environment, this is good for performance. this is the template that will follow our object of signatures: var my_jenv = null; try { my_jenv = jni.getforthread(); // do the jni work here } finally { if (my_jenv) { jni.unloadclasses(my_jenv); } } the reason we choose my_jenv for a variable name, and not jenv, is because the global privileged window scope of firefox for android has a variable jenv already, and we don't want to mix. declare constructors, methods, and fields now that the sig's and java environment is ready, it is now possible to declare the constructors, methods, and fields. load the class the first step is to load the class. every...
... key-value pair, with the key being static_methods and methods and the value being an array. var toast = jni.loadclass(my_jenv, sig.toast.substr(1, sig.toast.length - 2), { static_methods: [ { name: 'maketext', sig: '()' } ], methods: [ { name: 'show', sig: '()' } ] }); the sig of methods is always in the format of "method format" from our types table above. the reason is that methods accept arguments and return something. we need to declare now the arguments and return type for each of the methods. the documentation says maketext takes three arguments, the types are context, int, and int and returns a toast. for example, let's declare this with strings: { name: 'maketext', sig: '(landroid/content/context;ii)landroid/widget/toast;' } we see there are no sepa...
PromiseWorker.jsm
t { 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.then( function(aval) { console.log('fullfilled - promise_domyfuncfalse - ', aval); }, function(areas...
...son); } ).catch( function(acaught) { console.error('caught - promise_domyfunctrue - ', acaught); } ); var promise_domyfuncfalse = myworker.post('resolvetest', [false]); promise_domyfuncfalse.then( function(aval) { console.log('fullfilled - promise_domyfuncfalse - ', aval); }, function(areason) { console.error('rejected - promise_domyfuncfalse - ', areason); } ).catch( function(acaught) { console.error('caught - promise_domyfuncfalse - ', acaught); } ); result running the code above will log the following information to the console: "fullfilled - promise_domyfunctrue - " "you sent to promiseworker argument of: `true`" bootstrap.js line 8 "rejected - promise...
Task.jsm
successfully, or is rejected if an exception occurs. you can use the yield operator inside the generator function to wait on a promise, spawn another task, or propagate a value: let resolutionvalue = yield (promise/generator/iterator/value); if you specify a promise, the yield operator returns its resolution value as soon as the promise is resolved. if the promise is rejected, its rejection reason is thrown as an exception. 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. this reduces the syntax overhead of calling task.spawn() explicitly when you want to recurse into other task functions. if you specify a function that is not a generator, it is called with n...
... any other unhandled exception that is thrown inside the task is reported by components.utils.reporterror. ...
Application Translation with Mercurial
time will pass between the moment in which you start the localization, finish it, test it, improve it, upload it for review and get review (maybe not approved on first try). other localizers will likely have done changes to the translation, either adding new texts, removing obsolete ones or improving the current texts. this can cause conflicts between the changes you created and theirs. for this reason, updating patches kann be necessary so mercurial is still able to find the lines in the files which it has to replace or where it has to add them. mercurial queues allow to revert changes and also pull changes and reapply your local changes. go back to the localization directory: cd /c/mozilla/de-mozilla-aurora initiate mercurial queues: hg qinit get to know the translation style for having...
... is defined in the .hgrc file (see above): hg qexport > ../firefox-29-aboutprivatebrowsing-v1.patch this creates a patch file called firefox-29-aboutprivatebrowsing-v1.patch containing the changes in the parent directory of de-mozilla-aurora (in this example: c:\mozilla\). proof-reading and altering the patch now proof-read the patch. this detects often more than 90 percent of the possible reasons for the reviewer to not accept the patch. if you find that changes have to be done, edit the real aboutprivatebrowsing.dtd file from the localization repository, save it and follow the steps from exporting the changes as patch (see above). validating the translation in the product this guide hasn't yet a section about the validation of the translation. please follow the instructions from the q...
Fonts for Mozilla 2.0's MathML engine
nofficial truetype conversion for stix fonts. the following fonts are not necessary when the above fonts are installed, but are worth noting because of their unicode support for many mathematical characters. dejavu serif and dejavu sans are freely available and installed with many linux distributions. they contain support for many mathematical characters, and mozilla will display some mathml reasonably on systems with these fonts installed, even without stix fonts. the font only contains glyphs for stretchy operators that have unicode assignments. cambria math is preinstalled on microsoft windows vista, and also comes with miscrosoft office 2007 or microsoft powerpoint viewer 2007. the font has good support for mathematical characters, and so, with any of these products installed, moz...
...d, even without stix fonts. the font only contains glyphs for stretchy operators that have unicode assignments. cambria math is preinstalled on microsoft windows vista, and also comes with miscrosoft office 2007 or microsoft powerpoint viewer 2007. the font has good support for mathematical characters, and so, with any of these products installed, mozilla will be able to display some mathml reasonably even without stix fonts. the font contains the necessary glyphs for stretchy operators but mozilla does not yet make use of all of these. the license allows you to "use this font as permitted by the eula for the product in which this font is included to display and print content", so consulting your lawyer is recommended if considering installing this on systems without the associated product...
Mozilla Port Blocking
quired access for that protocol. potential problems caused by port blocking port blocking can cause problems if a site or web application requires access to one of the ports which is blocked in mozilla. if a user attempts to access a uri on a blocked port, mozilla shows one of the following alerts to the user or in the error console. "access to the port number given has been disabled for security reasons." "establishing a connection to an unsafe or otherwise banned port was prohibited" "0x804b0013 (ns_error_port_access_not_allowed)" if your product or web site uses a port which is blocked by mozilla's default port blocking rules, you can either change the port of your service to a unblocked value (recommended if possible) or ask your mozilla users to enable the port. for details on which ports a...
... imap any port smtp any port finger 79 datetime 13 how to change mozilla port blocking permanently since each protocol can determine which ports are blocked, you should contact the protocol handler owner to request that a specific port be blocked or unblocked. if that fails, contact dougt@netscape.com and/or darin@netscape.com. you must have a good reason for the change, a deep understanding of the security risk involved and be able to justify it. things to do allow user preference to override default port blocking. currently you need to add preferences to either user.js or all.js. see bug 85601. per protocol port blocking/enabling preferences. better user interface allow the user to decide if the blocking is really required. some kin...
NSPR Contributor Guide
nspr wishes to document some guidelines for those who would contribute to nspr. ...
...nspr wishes to document some guidelines for those who would contribute to nspr. ...
NSS API Guidelines
underscores. for example: layer_upper_case_english_words() or der_convert_bit_string(). structure members for exposed data structures should have the form capitalizedenglishwords (the first letter uncapitalized). for example: pk11rsagenparamsstr.keysizeinbits for members of enums, our current api has no standard (typedefs for enums should follow the data types standard). there seem to be three reasonable options: enum members have the same standard as exposed data structure members. enum members have the same standard as data types. enum members have the same standard as public macros (minus the '()' of course). options 2 and 3 are the more preferred options. option 1, currently the most common used for enums, actually creates namespace pollution. callback functions, and fun...
...eybycert(), pk11_getbestslot(). these functions should all have the form layer_finddatatype[bydatatype](). the second kind of search, looks for all the objects that match a given criteria. these functions operate on a variety of levels. some return allocated arrays of data, some return linked lists of data, others use callbacks to return data elements one at a time. unfortunately, there are good reasons to maintain all these types. so here are some guidelines to make them more manageable: all callback operating search functions should be in the low level of the api, if exposed at all. developers dealing with ssl and pkcs #7 layers should not have to see any of these functions. these functions should have the form layer_traversestorageobjectorlist(). list and array returning functions should b...
nss tech note1
covered with the classic decoder. it can only decode der .† it does not handle streaming input, and requires that all input be present before beginning to decode. despite their differences, the two decoders have a lot in common. quickder was written to be as compatible as possible with the classic decoder, in order to ease migration to it in areas of critical performance bottlenecks. for this reason, i will first describe all the common functionality of the two decoders, before outlining their differences. the main non-streaming apis for these two decoders have an identical prototype : secstatus sec_asn1decodeitem(prarenapool *pool, void *dest, const sec_asn1template *t, secitem *item); secstatus sec_quickderdecodeitem(prarenapool* arena, void* dest, const sec_asn1template* template...
...1decodeitem and sec_quickderdecodeitem the arena argument is required to be non-null for sec_quickderdecodeitem . with sec_asn1decodeitem, it can be null, and if so, the decoder will allocate from the heap using pr_malloc . however, this usage is strongly discouraged and we recommend that you always use an arena pool even with sec_asn1decodeitem. see bug 175163 for more information about the reason for this recommendation. sec_asn1decodeitem will make a copy of the input data into the decoded target as needed, while sec_quickderdecodeitem will generate output with pointers into the input. this means that if you use sec_quickderdecodeitem, you must always be careful not to free the input as long as you intend to use the decoded structure. ideally, you should allocate the input data out of...
nss tech note6
ing libfreebl_32fpu_3.chk libfreebl_32int_3.sl for other pa-risc cpus, with a corresponding libfreebl_32int_3.chk on the 64-bit hp-ux pa-risc architecture, there is only one freebl library, called libfreebl3.sl, with a corresponding libfreebl3.chk applications should always use nss binaries that are the output of the regular nss build process. 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 . the softoken and freebl binaries won't match any nss binaries that may have been submitted to nist for validation, and thus may not be verified as being the actual fips 140 validated cryptographic module . the only way to meet thi...
... as being the actual fips 140 validated cryptographic module . the only way to meet this requirement is for your application never to modify the nss binaries. any offer of binary support that may have been previously made to you by nss developers is null and void. if your build process modifies nss libraries in any way (for example, to strip the symbols), it should consider not doing so for the reasons cited above. if you still decide to make unsupported changes, you can allow the softoken to come up in fips 140 mode of operation by regenerating the .chk files yourself. the tool to do that is called shlibsign. it is released as part of the nss binary distributions. if your build process does not modify nss shared libraries, you can just use the .chk files in the nss binary distributions. ...
NSS functions
6 and later cert_encodepolicyconstraintsextension mxr 3.12 and later cert_encodepolicymappingextension mxr 3.12 and later cert_encodesubjectkeyid mxr 3.12 and later cert_encodeusernotice mxr 3.12 and later cert_extractpublickey mxr 3.2 and later cert_findcertbyname mxr 3.2 and later cert_findcrlentryreasonexten mxr 3.12 and later cert_findcrlnumberexten mxr 3.12 and later cert_findnameconstraintsexten mxr 3.12 and later cert_filtercertlistbycanames mxr 3.4 and later cert_filtercertlistbyusage mxr 3.4 and later cert_filtercertlistforusercerts mxr 3.6 and later cert_findcertbydercert mxr 3.2 and later ...
...mxr 3.2 and later pk11_getblocksize mxr 3.2 and later pk11_getcertfromprivatekey mxr 3.9.3 and later pk11_getcurrentwrapindex mxr 3.2 and later pk11_getdefaultarray mxr 3.8 and later pk11_getdefaultflags mxr 3.8 and later pk11_getdisabledreason mxr 3.8 and later pk11_getfirstsafe mxr 3.2 and later pk11_getinternalkeyslot mxr 3.2 and later pk11_getinternalslot mxr 3.2 and later pk11_getkeygen mxr 3.4 and later pk11_getkeylength mxr 3.2 and later pk11_getkeystrength m...
Scripting Java
ge and access class java.io.file using just the name file: js> importpackage(java.io) js> file [javaclass java.io.file] here importpackage(java.io) makes all the classes in the java.io package (such as file) available at the top level. it's equivalent in effect to the java declaration import java.io.*;. it's important to note that java imports java.lang.* implicitly, while rhino does not. the reason is that javascript has its own top-level objects boolean, math, number, object, and string that are different from the classes by those names defined in the java.lang package. because of this conflict, it's a good idea not to use importpackage on the java.lang package. one thing to be careful of is rhino's handling of errors in specifying java package or class names. if java.myclass is accessed,...
...le omitting a required method is bad practice for programming in the large, it's useful for small scripts and for exploratory programming. the javaadapter constructor in the previous section we created java adapters using the new operator with java interfaces. this approach has its limitations: it's not possible to implement multiple interfaces, nor can we extend non-abstract classes. for these reasons there is a javaadapter constructor. the syntax of the javaadapter constructor is: new javaadapter(javaintforclass, [javaintf, ..., javaintf,] javascriptobject) here javaintforclass is an interface to implement or a class to extend and javaintf are aditional interfaces to implement. the javascriptobject is the javascript object containing the methods that will be called from the java adapter.
GCIntegration - SpiderMonkey Redirect 1
s--as if someone did a js_dumpheap() at the beginning of the incremental gc. these objects, as well as any that were allocated since the gc started, are guaranteed to be marked. the write barrier guarantees the snapshot-at-the-beginning (satb) invariant in a simple way. 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. in the diagram above, c will be marked when the pointer from a to c is nulled out. this barrier is conservative—it assumes that any destroyed pointer was pointing to an object that was part of the initial snapshot. consequently, more objects may be marked than necessary, but those objects will be collected in the next gc if they're unreachable. spidermonkey implements t...
...uently, more objects may be marked than necessary, but those objects will be collected in the next gc if they're unreachable. spidermonkey implements the write barrier internally. any time a property is updated in the vm or the jit, a write barrier is invoked. the troublesome spots are the pointers in gecko that spidermonkey doesn't know about. 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. initializing a pointer never requires a write barrier because there was nothing being destroyed that might have part of the initial snapshot. if a pointer is not traced via js_call_tracer or any similar mechanism, then there's no need for a w...
GC Rooting Guide
/ make a scope to force the destructor to run before obj is unwrapped. eventlogger(cx); ...code... } return obj; } autorooters gc thing pointers that appear as part of a stack-allocated aggregates (array, structure, class, union) should use js::rooted<t> when possible. there are some situations when using js::rooted<t> is not possible, or is undesirable for performance reasons. to cover these cases, there are various autorooter classes that can be used. here are the main autorooters defined: type autorooter class js::value[] autoarrayrooter js::vector<js::value> autovaluevector js::vector<jsid> autoidvector js::vector<jsobject*> autoobjectvector js::vector<jsscript*> autoscriptvector ...
... aggregates, otherwise use an autorooter. ...
Exact Stack Rooting
not traced as part of the gc. instead, every pointer on the cstack should be considered part of the rootset. to that end, we have a special "rooting" mechanism for stack pointers that is very efficiently able to add and remove gcpointers to the rootedset. the downside of this efficiency is that gcpointers must be added to and removed from this rootedset tracking structure in lifo order. for this reason it is highly recommended that this rooting mechanism only be used on the cstack. js::rooted<t> typedef js::rooted<t> rootedt; -> rootedobject, rootedstring, rootedscript, etc. because of the lifo restriction, using this interface manually is extremely cumbersome. instead, spidermonkey has a convenient suite of c++ raii classes to do this for you, called js::rootedt: rootedstring str1(cx, js_...
...et, you can construct and pass a new nullptr instance. you are free to use these as temporaries. rootedobject obj(cx, js_newobject(cx, clasp, nullptr(), nullptr()); common pitfalls the c++ type system allows us to eliminate the possibility of most common errors; however, there are still a few things that you can get wrong that the compiler cannot help you with. there is basically never a good reason to do any of these. if you think you do need to do one of these, ask on one of spidermonkey's support forums: maybe we've already solved your problem using a different mechanism. storing a js::rootedt on the heap. it would be very easy to violate the lifo constraint if you did this. use a different rooting mechanism if you store a gcpointer on the heap. there are moz_stack_class annotations th...
Statistics API
time that this gc consumed. note: this is the sum of all the slice durations, not end time - start time. compartments_collected: integer - the number of compartments that were collected by the gc. compartment_count: integer - the number of compartments that were present in the system at the end of the gc. max_pause: number (milliseconds) - longest duration pause during the gc. nonincremental_reason: string - a string representing the reason that an incremental gc was aborted or forced to finish in a single slice. if the incremental gc completed normally, this will be "none". allocated: integer (mb) - size of the javascript heap in mib at the start of the gc. slices: array of objects - a list of objects describing each slice in detail. times: object - a map from phase names to the total t...
...er browser code is allowed to run. the slices array describes how long each slice took and what work was done during the slice. each element of the slices array is an object with these fields: slice: integer - the slice index, starting at 0. pause: number (milliseconds) - the slice duration. when: number (milliseconds) - the time this slice started, relative to the first slice's start time. reason: string - a string describing the api that initiated this gc slice. page_faults: integer - number of page faults incurred during the processing of this slice. start_timestamp: integer (microseconds) - time of slice start from epoch. end_timestamp: integer (microseconds) - time of slice end from epoch. times: object - a map from phase names to the total time taken by that phase during this sli...
JSAPI User Guide
ate the object embedding. in either case, if you create an object and then want it to persist in the run time where it can be used by other scripts, you must root the object by calling js_add*root or js_addnamed*root. using these functions ensures that the js engine will keep track of the objects and clean them up during garbage collection, if appropriate. creating an object from a script one reason to create a custom js object from a script is when you only need an object to exist as long as the script that uses it is executing. to create objects that persist across script calls, you can embed the object code in your application instead of using a script. note: you can also use scripts to create persistent objects, too. to create a custom object using a script: define and spec the obje...
... getobjectfromothersandbox() function. your application just needs to take care not to expose any such function to scripts. in short, never pass one user's data and objects to another user's code, and you'll have no access control issues. spidermonkey won't do it if you don't. trade-offs. object-capabilities security is security without run-time security checks. it is easy to implement, easy to reason about, and fast. but in fairness there are some drawbacks. first, the failure mode is pretty severe. if you do accidentally leak an object from one sandbox into another, the genie is out of the bottle. once a malicious script gets a reference to a single object in a sandbox, it can use that object to get a reference to the sandbox's global object, and from there, almost any other object or functi...
History Service Design
atements approach is used in other dependant services and in autocomplete. another step to improve performance is mainly dedicated to not locking ui. since places is actually not thread-safe and doing most of the work in the main-thread, adding visits (the most common action usually executed on user interaction) could end up locking the ui till the database i/o to save data is complete. for this reason visits and favicons are added lazily on a timer. in future this will probably change in favour of storage asynchronous statements, so that the inserts will be queued-up by mozstorage itself in a separate thread. sql queries are built with performance in mind, and constantly tested against large databases. database indexes are quite important, and a good query can make the difference between minu...
...ry, bookmarks or both, also with values coming from other services like tags, annotations. result nodes can be simple uri nodes with page attributes or complete visit attributes, or can be containers (folders, other queries, dynamic containers and so on). see querying places for deeper knowledge on the actual implementation. expiration expiration is an important part of data management for two reasons: privacy: expiring data based on user interaction is important, nothing must be left behind on a page removal database maintenance: having cleaner and smaller tables helps queries performances expiration is done at certain moments, but in future will most likely be moved to async queries, to be executed on a separate thread. actually pages and visits are expired: on page added (lazily) ...
Using XPCOM Utilities to Make Things Easier
ike raw pointers, that can be compared and tested, and so on. when you pass them to a getter, you must do something special, however: you must wrap the variable with the function getter_addrefs, as in the example above. you cannot call the nsisupports addref or release methods on a nscomptr. but this restriction is desirable, since the nscomptr is handling reference counting for you. if for some reason you need to adjust the reference count, you must assign the nscomptr to a new variable and addref that. this is a common pattern when you have a local nscomptr in a function and you must pass back a reference to it, as in the following: someclass::get(nsisupports** aresult) { if (!aresult) return ns_error_null_pointer; nscomptr<nsisupports> value; object->method(getter_addrefs(value))...
...ces: someclass::dosomething(nsifile* afile) { if (!afile) return ns_error_null_pointer; nsresult rv; nscomptr<nsilocalfile> localfile = do_queryinterface(afile, &rv); // ... } if the queryinterface is successful, localfile will be non-null, and rv will be set to ns_ok. if queryinterface fails, localfile will be null, and rv will be set to a specific error code corresponding to the reason for the failure. in this construct, the result code rv is an optional parameter. if you don't care what the error code is, you can simply drop it from the function call. from this point on, we'll be using nscomptrs as much as possible in weblock. for a complete listing of smart pointer functionality, see mozilla.org's nscomptr documentationxxx this should be in devmo. note: other-parts this s...
mozIVisitInfoCallback
placeinfo aplaceinfo); void handleresult(in moziplaceinfo aplaceinfo); void oncomplete(in nsresult aresultcode, in moziplaceinfo aplaceinfo);obsolete since gecko 8.0 methods handleerror() called when a moziplaceinfo couldn't be processed. void handleerror( in nsresult aresultcode, in moziplaceinfo aplaceinfo ); parameters aresultcode nsresult indicating the reason why the change failed. aplaceinfo the information that was unable to be processed. handleresult() called for each visit added, title change, or guid change when passed to moziasynchistory.updateplaces(). if more than one operation is done for a given visit, this method is only called once (for all changes at once). void handleresult( in moziplaceinfo aplaceinfo ); parameters apl...
...nto the database. oncomplete() obsolete since gecko 8.0 (firefox 8.0 / thunderbird 8.0 / seamonkey 2.5) called for each visit added, title change, or guid change when passed to moziasynchistory.updateplaces(). void oncomplete( in nsresult aresultcode, in moziplaceinfo aplaceinfo ); parameters aresultcode nsresult of the change indicating success or failure reason. aplaceinfo the information that was being entered into the database. notes this method was replaced by the separate handleresult() and handleerror() methods in gecko 8.0 (firefox 8.0 / thunderbird 8.0 / seamonkey 2.5). see also mozivisitinfo moziasynchistory ...
nsIAsyncOutputStream
non-blocking streams, it is not necessary that nsioutputstream.isnonblocking() return true. nor is it necessary that a non-blocking nsioutputstream implementation also implement nsiasyncoutputstream. method overview void asyncwait(in nsioutputstreamcallback acallback, in unsigned long aflags, in unsigned long arequestedcount, in nsieventtarget aeventtarget); void closewithstatus(in nsresult reason); constants constant value description wait_closure_only (1<<0) if passed to asyncwait(), this flag overrides the default behavior, causing the onoutputstreamready notification to be suppressed until the stream becomes closed (either as a result of closewithstatus()/close being called on the stream or possibly due to some error in the underlying stream). methods asyncwait() asynchronou...
...pes, which have both an input end and an output end. if the output end of a pipe is closed, then reads from the input end of the pipe will fail. the error code returned when an attempt is made to read to a "closed" pipe corresponds to the status code passed in when the output end of the pipe was closed, which greatly simplifies working with pipes in some cases. void closewithstatus( in nsresult reason ); parameters reason the error that will be reported if this stream is accessed after it has been closed. ...
nsIAuthPromptProvider
netwerk/base/public/nsiauthpromptprovider.idlscriptable this interface requests a prompt interface for the given prompt reason. inherits from: nsisupports last changed in gecko 1.9 (firefox 3) method overview void getauthprompt(in pruint32 apromptreason, in nsiidref iid, [iid_is(iid),retval] out nsqiresult result); constants constant value description prompt_normal 0 normal (non-proxy) prompt request. prompt_proxy 1 proxy authentication request. methods getauthprompt() this method requests a prompt interface for the given prompt reason. 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. iid the desired ...
...rompt( 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. iid the desired interface, for example, ns_get_iid(nsiauthprompt2). result a nsiauthprompt2 interface. exceptions thrown ns_error_not_available if no prompt is allowed or available for the given reason. ...
nsIComponentManager
th the addbootstrappedmanifestlocation() method. see addbootstrappedmanifestlocation() for details. void removebootstrappedmanifestlocation( in interface nsilocalfile alocation ); parameters examples using addbootstrappedmanifestlocation in a bootstrapped extension for firefox 8 and 9: alocation the directory or xpi to stop reading the chrome.manifest from. ...
...ameters examples using addbootstrappedmanifestlocation in a bootstrapped extension for firefox 8 and 9: alocation the directory or xpi to stop reading the chrome.manifest from. ...
nsIContentPrefCallback2
dom/interfaces/base/nsicontentprefservice2.idlscriptable callback used by nsicontentprefservice2 methods 1.0 66 introduced gecko 20.0 inherits from: nsisupports last changed in gecko 20.0 (firefox 20.0 / thunderbird 20.0 / seamonkey 2.17) method overview void handlecompletion(in unsigned short reason); void handleerror(in nsresult error); void handleresult(in nsicontentpref pref); constants constant value description complete_ok 0 complete_error 1 methods handlecompletion() called when the method finishes. this will be called exactly once for each method invocation, and afterward no other callback methods will be called. void handlecompletion( in unsigned short reason ); p...
...n nsicontentpref pref); constants constant value description complete_ok 0 complete_error 1 methods handlecompletion() called when the method finishes. this will be called exactly once for each method invocation, and afterward no other callback methods will be called. void handlecompletion( in unsigned short reason ); parameters reason one of the complete_* values indicating the manner in which the method completed. handleerror() called when an error occurs. this may be called multiple times before handlecompletion is called. void handleerror( in nsresult error ); parameters error a number in components.results describing the error. handleresult() for the retrieval methods, this is called once for each retriev...
nsILocalFile
ription delete_on_close 0x80000000 optional parameter used by opennsprfiledesc(). methods native code only! appendrelativenativepath appends a relative, native character encoding, path to the current path of the nsilocalfile object. void appendrelativenativepath( in acstring relativefilepath ); parameters relativefilepath a native relative path. for security reasons, this cannot contain '..' or cannot start with a directory separator '/'. must be in the native file system character set. exceptions thrown ns_error_file_unrecognized_path indicates that relativefilepath incorrectly begins with a path separator character or otherwise contains invalid characters. appendrelativepath() appends a relative native path to the current path of the nsilocalfile...
...hrown ns_error_file_unrecognized_path indicates that relativefilepath incorrectly begins with a path separator character or otherwise contains invalid characters. appendrelativepath() appends a relative native path to the current path of the nsilocalfile object. void appendrelativepath( in astring relativefilepath ); parameters relativefilepath a native relative path. for security reasons, this cannot contain '..' or cannot start with a directory separator '/' . exceptions thrown ns_error_file_unrecognized_path indicates that relativefilepath incorrectly begins with a path separator character or otherwise contains invalid characters. getrelativedescriptor() returns a relative file path in an opaque, cross platform format. it is therefore not a native path. acstring getr...
nsIRequest
constant value description load_bypass_cache 1 << 9 force an end-to-end download of content data from the origin server. this flag is used for a shift-reload. load_from_cache 1 << 10 load from the cache, bypassing protocol specific validation logic. this flag is used when browsing via history. it is not recommended for normal browsing as it may likely violate reasonable assumptions made by the server and confuse users. the following flags control the frequency of cached content validation when neither load_bypass_cache or load_from_cache are set. by default, cached content is automatically validated if necessary before reuse. note: these flags are intended for normal browsing, and they should therefore not apply to content that must be validated befo...
...ppen asynchronously. requests that use nsistreamlistener must not call ondataavailable anymore after cancel has been called. note: most nsirequest implementations expect astatus to be a failure code; however, some implementations may allow astatus to be a success code such as ns_ok. in general, astatus should be a failure code. void cancel( in nsresult astatus ); parameters astatus the reason for canceling this request. ispending() indicates whether the request is pending. ispending is true when there is an outstanding asynchronous event that will make the request no longer be pending. requests do not necessarily start out pending; in some cases, requests have to be explicitly initiated (for example nsichannel implementations are only pending once asyncopen returns successfully). ...
nsITransport
g transfered in some fashion via the streams exposed by this interface). a transport can have an event sink associated with it. the event sink receives transport-specific events as the transfer is occurring. for a socket transport, these events can include status about the connection. see nsisockettransport for more info about socket transport specifics. method overview void close(in nsresult areason); nsiinputstream openinputstream(in unsigned long aflags, in unsigned long asegmentsize, in unsigned long asegmentcount); nsioutputstream openoutputstream(in unsigned long aflags, in unsigned long asegmentsize, in unsigned long asegmentcount); void seteventsink(in nsitransporteventsink asink, in nsieventtarget aeventtarget); constants open flags. constant value description open_bloc...
... flags. open_unbuffered 1<<1 generic nsitransporteventsink status codes. nsitransport implementations may override these status codes with their own more specific status codes (for example, see nsisockettransport). constant value description status_reading 0x804b0008 status_writing 0x804b0009 methods close() close the transport and any open streams. void close( in nsresult areason ); parameters areason the reason for closing the stream. openinputstream() open an input stream on this transport. nsiinputstream openinputstream( in unsigned long aflags, in unsigned long asegmentsize, in unsigned long asegmentcount ); parameters aflags optional transport specific flags. flags have the following meaning: open_blocking if specified, then the resulting stream will have ...
nsIWebSocketChannel
. to create an instance, use: var websocketchannel = components.classes["@mozilla.org/????????????????????????????"] .createinstance(components.interfaces.nsiwebsocketchannel); method overview void asyncopen(in nsiuri auri, in acstring aorigin, in nsiwebsocketlistener alistener, in nsisupports acontext); void close(in unsigned short acode, in autf8string areason); void sendbinarymsg(in acstring amsg); void sendmsg(in autf8string amsg); attributes attribute type description extensions acstring sec-websocket-extensions response header value. read only. loadgroup nsiloadgroup the load group of the websockets code. notificationcallbacks nsiinterfacerequestor the notification ...
... in nsiwebsocketlistener alistener, in nsisupports acontext ); parameters auri the uri of the websocket protocol; this may be redirected. aorigin the uri of the originating resource. alistener the nsiwebsocketlistener implementation. acontext an opaque parameter forwarded to alistener's methods. close() void close( in unsigned short acode, in autf8string areason ); parameters acode the status of the connection when closed; see status codes for possible values. areason a human-readable string describing the reason the connection closed. sendbinarymsg() sends a binary message to the websocket peer. void sendbinarymsg( in acstring amsg ); parameters amsg the data to send. sendmsg() sends a text message to the websocket peer. ...
Troubleshooting XPCOM components registration
you can be certain that a component has failed to register by going to the error console and evaluating components.classes["contract-id"].name where contract-id is your contract id. ...
...\path\to\logfile "c:\program files\mozilla firefox\firefox.exe" examining this log for warning and errors may provide valuable clues why the component failed to load. if using firefox 4 / xulrunner 2.0, make sure that your extension is unpacked and you declared the binary component in your chrome.manifest. see xpcom changes in gecko 2.0 parsing errors in javascript components the most common reason for components written in javascript to fail is that there are parsing errors. these parsing errors should show up in the error console if chrome errors are enabled. to learn more about enabling chrome errors, see "how can i see errors in my code" in the extension faqs. registration failure if the module is loading correctly but doesn't register its components, try adding calls to components.ut...
Weak reference
interface you were hoping for. why can't i just directly call my interfaces methods on the weak reference? you really want this weak reference scheme to give you a pointer that implements the interface you actually care about, e.g., // note: _not_ the implementation we have... nsweakptr<nsifoo> weakfooptr = fooptr; // ... if ( weakfooptr ) status = weakfooptr->somefoomethod(...); this is a reasonable thing to want. it's expensive to implement automatically, however. neither inheritance, nor templates, nor macros can help automatically forward all the method calls to the real object. xpidl could write an implementation for you (if we modified it), or you could write one by hand as i discuss below. there are other, mostly negligible, costs: it's an extra indirection per call, and the easy i...
...could write one by hand as i discuss below. there are other, mostly negligible, costs: it's an extra indirection per call, and the easy implementation requires adding an extra pointer per interface to the target implementation. why can't i just queryinterface between the pair? it really feels like the nsiweakreference that you are holding is just another interface on the target object. it seems reasonable to want to simply queryinterface between the two. why these extra calls: getweakreference and queryreferent? this would be possible if the weak reference was actually aggregated to the target object. the problem here is queryinterface. queryinterface must satisfy many requirements to allow com to work. among these requirements is that every call to queryinterface against the same (aggragate)...
Index
the icon will show is on disk at: <profile home>/nim/<value of pref aim.session.screenname>/picture/<screenname for card>.gif if aim.session.screenname is not set, the icon will not appear. if there is no card matching the email, the icon will not appear. if there is a card, but no screenname, the icon will not appear. and finally, if there is no icon, the icon will not appear. the reason this file name scheme was chosen was is this is how netscape 7.0 im stores buddy icons on disk. so if you use nim, and you use buddy icons, this will just work for free. notes: 16 cached compose window faq seth spitzer (sspitzer@mozilla.org) what is the "cached" compose window? instead of destroying the mail compose window on send (or close) just to create a new one t...
... directory). 44 main windows thunderbird the base chrome directory of thunderbird can sometimes appear confusing when you're just beginning to look at it. as such, i've always thought it would be nice to have a list of what xul, js, or other files are that are here, what they do, and where they overlay at different points within the client. things appear confusing for several reasons: 45 message interfaces interfaces, interfaces:scriptable, needscontent, xpcom api reference, thunderbird nsimsghdr - this interface describes headers for all mail messages. it can be used to retrieve address, subject and related header information for a mail message. 46 message examples thunderbird no summary! 47 message list examples thun...
Working with data
onvert strings when using them as input parameters to c functions. they get converted automatically for you. just pass in the javascript string object. however, when c functions return, they still return a char.ptr or jschar.ptr (that is, a pointer to an 8-bit or 16-bit array of characters). you'll have to convert those yourself, as covered above. making non-null terminated strings if for some reason non-null terminated strings are needed, this can also be accomplished. 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...
...ry.declare("somecfunction", ctypes.default_abi, ctypes.void_t, mystruct.ptr); somecfunction(myarray); this shows how to pass a buffer containing 5 elements of mystruct, the elements in myarray are not pointers. 64-bit integers while most numeric types in js-ctypes are represented by standard javascript number objects, 64-bit integers cannot all be represented accurately by this type. for that reason, 64-bit and pointer-sized c values of numeric types don't get automatically converted to javascript numbers. instead, they're converted to javascript objects that you can manipulate using the methods provided by the int64 and uint64 objects. note: these 64-bit integer types are intentionally low on features, so that when javascript adds a "big number" type, we can easily upgrade to support that ...
ctypes.open
ata/roaming/mozilla/firefox/profiles/aecgxse.unnamed%20profile%201/extensions/youraddon@jetpack.xpi!/mysubfolder/mycfunctionsforunix.so" if your add-on is a bootstrap add-on, then you don't need to use this method to convert a chrome:// path; instead, on startup procedure of the bootstrap add-on obtain the file and/or jar path from installpath from the adata parameter. ...
...startup procedure of the bootstrap add-on obtain the file and/or jar path from installpath from the adata parameter. function startup(adata, areason) { var nsifile_folder = adata.installpath; // if addon is unpacked, this will be the addon folder. ...
Streams - Plugins
tream itself by calling npn_destroystream. you should delete any private data allocated in the plug-in's stream->pdata field when you destroy a stream. the plug-in can store private data associated with the stream in stream->pdata. the browser stores private data in stream->ndata; this value should not be changed by the plug-in. nperror npp_destroystream(npp instance, npstream *stream, nperror reason); the instance parameter is the current plug-in instance; the stream parameter specifies the stream to be deleted. the reason parameter specifies why the stream was destroyed. it can have one of these values: npres_done (most common): normal completion; all data was sent to the instance. npres_user_break: the user canceled the stream directly by clicking the stop button or indirectly by so...
...trates using this function with npn_newstream and npn_destroystream, see "example of sending a stream." deleting the stream when the stream is complete, the plug-in calls npn_destroystream to close and delete it. this applies to streams the plug-in creates with npn_newstream or streams created by the browser with npp_newstream. nperror npn_destroystream(npp instance, npstream* stream, nperror reason); the instance parameter is the current plug-in; the stream parameter specifies the stream, created by either the browser or the plug-in. the reason parameter represents the reason the stream was stopped, as follows: npres_done (most common): the stream completed normally; the plug-in sent all data to the browser. npres_user_break: the plug-in terminated the stream because of a user request...
URLs - Plugins
st a stream and receive notification of the result in all cases, use npn_geturlnotify. for http urls, the browser resolves npn_geturl as the http server method get, which requests url objects. note that npn_geturl is typically asynchronous: it returns immediately and only later handles the request, such as displaying the url or creating the stream for the instance and writing the data. for this reason as well, calling npn_geturlnotify may be more useful than npn_geturl; the plug-in is notified upon either successful or unsuccessful completion of the request. nperror npn_geturl(npp instance, const char *url, const char *target); the instance parameter represents the current plug-in instance. the url parameter is the url of the request, which can be of any type, including http, ftp, news, or m...
...er it has finished loading the url. if the target is null, it calls npp_urlnotify after calling npp_destroystream to close the stream. both the npn_geturlnotify and npn_posturlnotify functions call the npp_urlnotify method to notify the plug-in of the result of a request. both functions pass the notifydata value to npp_urlnotify, which tells the plug-in that the url request was completed and the reason for completion. void npp_urlnotify(npp instance, const char* url, npreason reason, void* notifydata); the instance and url parameters have the same definitions as those of npn_geturl. the notifydata parameter contains the private plug-in data passed to the corresponding call to npn_geturlnotify and npn_posturlnotify. warning: in gecko 2.0 (firefox 4 / thunderbird 3.3 / seam...
AbstractRange - Web APIs
the span, and then the range is used to copy the contents of the range. ranges and the hierarchy of the dom in order to define a range of characters within a document in a way that is able to span across zero or more node boundaries, and which is as resilient as possible to changes to the dom, you can't simply specify the offset to the first and last characters in the html. there are a few good reasons for that. first, after your page is loaded, the browser simply isn't thinking in terms of html. once it's been loaded, the page is a tree of dom node objects, so you need to specify the beginning and ending locations of a range in terms of nodes and positions within nodes. second, in order to support the mutability of the dom tree as much as possible, you need a way to represent positions rela...
...pport the mutability of the dom tree as much as possible, you need a way to represent positions relative to nodes in the tree, rather than simply global positions within the entire document. by defining points within the document as offsets within a given node, those positions remain consistent with the content even as nodes are added to, removed from, or moved around within the dom tree—within reason. there are fairly obvious limitations (such as if a node is moved to be after the endpoint of a range, or if the content of a node is heavily altered), but it's far better than nothing. third, using node-relative positions to define the start and end positions will generally be easier to make perform well. rather than having to negotiate the dom figuring out what your global offset refers to, th...
CloseEvent.initCloseEvent() - Web APIs
t the event before it is dispatched, using eventtarget.dispatchevent(). once dispatched, it doesn't do anything anymore. do not use this method anymore as it is deprecated. instead use specific event constructors, like closeevent(). the page on creating and triggering events gives more information about the way to use these. syntax event.initmouseevent(type, canbubble, cancelable, wasclean, reasoncode, reason); parameters type the string to set the event's type to. possible types for mouse events include: click, mousedown, mouseup, mouseover, mousemove, mouseout. canbubble whether or not the event can bubble. sets the value of event.bubbles. cancelable whether or not the event's default action can be prevented. sets the value of event.cancelable. wasclean whether or not the conn...
... type the string to set the event's type to. possible types for mouse events include: click, mousedown, mouseup, mouseover, mousemove, mouseout. canbubble whether or not the event can bubble. sets the value of event.bubbles. cancelable whether or not the event's default action can be prevented. sets the value of event.cancelable. wasclean whether or not the connection was cleanly closed. reasoncode the reason of the close. reason a domstring describing the reason of the close in shuman-readable way. specifications this is no part of any specifications, though it was in some early drafts. ...
CrashReportBody - Web APIs
the crashreportbody interface of the reporting api represents the body of a crash report (the return value of its report.body property). a crash report is generated when a document becomes unusable due to the browser (or one of its processes) crashing. for security reasons, no details of the crash are communicated in the body except for a general crash reason. properties reason a string representing the reason for the crash. current possible reasons are: oom: the browser ran out of memory. unresponsive: the page was killed due to being unresponsive. examples crash reports are generally only retrievable via endpoints set up using the report-to header. it is difficult to retrieve a crash report via a reportingobserver, as by that point the page would have crashed! so...
...erally only retrievable via endpoints set up using the report-to header. it is difficult to retrieve a crash report via a reportingobserver, as by that point the page would have crashed! some sample json might look like this: { "type": "crash", "age": 42, "url": "https://example.com/", "user_agent": "mozilla/5.0 (x11; linux x86_64; rv:60.0) gecko/20100101 firefox/60.0", "body": { "reason": "oom" } } note: crash reports are always delivered to the endpoint group named default; there is currently no way to override this. if you want to receive other kinds of reports, but not crash reports, make sure to use a different name for the endpoint group that you choose for those reports. specifications specification status comment reporting apithe definition...
Element.classList - Web APIs
Web › API › Element › classList
ndard methods and properties of element.prototype.classlist for ie10-ie11 browsers plus nearly compliant behavior for ie 6-9. check it out: // 1. ...
...rties of element.prototype.classlist for ie10-ie11 browsers plus nearly compliant behavior for ie 6-9. check it out: // 1. ...
Comparison of Event Targets - Web APIs
event) event.currenttarget dom event interface the eventtarget whose eventlisteners are currently being processed. as the event capturing and bubbling occurs, this value changes. event.relatedtarget dom mouseevent interface identifies a secondary target for the event. event.explicitoriginaltarget event.webidl if the event was retargeted for some reason other than an anonymous boundary crossing, this will be set to the target before the retargeting occurs. for example, mouse events are retargeted to their parent node when they happen over text nodes (bug 185889), and in that case .target will show the parent and .explicitoriginaltarget will show the text node. unlike .originaltarget, .explicitoriginaltarget will never contain anonymous conte...
...nal target dispatching the event <small>event.target</small></td> <td class="standard">target who's event listener is being processed <small>event.currenttarget</small></td> <td class="standard">identify other element (if any) involved in the event <small>event.relatedtarget</small></td> <td class="non-standard">if there was a retargetting of the event for some reason <small> event.explicitoriginaltarget</small> contains the target before retargetting (never contains anonymous targets)</td> <td class="non-standard">if there was a retargetting of the event for some reason <small> event.originaltarget</small> contains the target before retargetting (may contain anonymous targets)</td> </tr> </thead> <tr> <td id="target"></td> ...
FileEntrySync - Web APIs
tes a new filewriter associated with the file that the fileentry represents. void createwriter ( ) raises (fileexception); parameter none. returns filewritersync exceptions this method can raise a fileexception with the following codes: exception description not_found_err the file does not exist. invalid_state_err the file is no longer valid for some reason other than it having been deleted. file() returns a file that represents the current state of the file that this fileentry represents. void file ( ) raises (fileexception); parameter none. returns file exceptions this method can raise a fileexception with the following codes: exception description not_found_err the file does not exist. inval...
... returns a file that represents the current state of the file that this fileentry represents. void file ( ) raises (fileexception); parameter none. returns file exceptions this method can raise a fileexception with the following codes: exception description not_found_err the file does not exist. invalid_state_err the file is no longer valid for some reason other than it having been deleted. browser compatibility the compatibility table on this page is generated from structured data. if you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. desktopmobilechromeedgefirefoxinternet exploreroperasafariandroid webviewchrome for androidfirefox for androidopera for androids...
FileError - Web APIs
Web › API › FileError
curred. best practices most people don't read the page on errors and exceptions unless they're stumped. so the following are a few tips that could help you avoid some pitfalls. error callbacks are not optional for your sanity although error callbacks are optional, you should include them in the arguments of the methods for the sake of the sanity of your users. a web app could fail for various reasons, so you don't want to spend the rest of your day guessing what's going on and going through maddening troubleshooting. don't run your app from file:// for security reasons, browsers do not allow you to run your app from file://. in fact, many of the powerful storage apis (such as file system, blobbuilder, and filereader) throw errors if you run the app locally from file://. when you're just te...
...rr 12 the file or directory with the same path already exists. quota_exceeded_err 10 either there's not enough remaining storage space or the storage quota was reached and the user declined to give more space to the database. to ask for more storage, see managing html5 offline storage. security_err 2 access to the files were denied for one of the following reasons: the files might be unsafe for access within a web application. too many calls are being made on file resources. other unspecified security error code or situations. type_mismatch_err 11 the app looked up an entry, but the entry found is of the wrong type. for example, the app is asking for a directory, when the entry is really a file. ...
FileSystemDirectoryEntry.getDirectory() - Web APIs
ory subtree rooted at the directory on which it's called. syntax filesystemdirectoryentry.getdirectory([path][, options][, successcallback][, errorcallback]); parameters path optional a usvstring representing an absolute path or a path relative to the directory on which the method is called, describing which directory entry to return. absolute paths may not be able to be used, for security reasons. options optional an object based on the filesystemflags dictionary, which allows you to specify whether or not to create the entry if it's missing and if it's an error if the file already exists. these options are currently not useful in web contexts. successcallback optional a method to be called once the filesystemdirectoryentry has been created. the method receives a single parameter: th...
...or.not_found_err the create option was not specified (or was specified as false), and the directory doesn't exist. fileerror.path_exists_err the create and exclusive options were both true, indicating that the directory should be created but must not already exist, but the directory does in fact already exist. fileerror.security_err the request to access the directory was denied for security reasons. fileerror.type_mismatch_err the path specified is not a directory; it's probably a file, but might be an unsupported file descriptor such as a pipe; this depends on the user agent to some extent. filesystemflags the options parameter is an object which is based on the filesystemflags dictionary; it provides flags which make it possible to adjust the behavior of the getdirectory() method. ...
FileSystemFlags.create - Web APIs
this option has no effect.ie no support noopera no support nosafari no support nowebview android full support yesprefixed full support ...
...this option has no effect.opera android no support nosafari ios no support nosamsung internet android full support yesprefixed full support yesprefixed prefixed implemented wi...
FileSystemFlags.exclusive - Web APIs
this option has no effect.ie no support noopera no support nosafari no support nowebview android full support yesprefixed full support ...
...this option has no effect.opera android no support nosafari ios no support nosamsung internet android full support yesprefixed full support yesprefixed prefixed implemented wi...
GlobalEventHandlers.onerror - Web APIs
ing interface event is fired at the element that initiated the load, and the onerror() handler on the element is invoked. these error events do not bubble up to window, but (at least in firefox) can be handled with a window.addeventlistener configured with usecapture set to true. installing a global error event handler is useful for automated collection of error reports. syntax for historical reasons, different arguments are passed to window.onerror and element.onerror handlers (as well as on error-type window.addeventlistener handlers). window.onerror window.onerror = function(message, source, lineno, colno, error) { ... }; function parameters: message: error message (string). available as event (sic!) in html onerror="" handler. source: url of the script where the error was raised ...
...n(event) { ... }) event of type errorevent contains all the information about the event and the error. element.onerror element.onerror = function(event) { ... } element.onerror accepts a function with a single argument of type event. a good example for this is when you are using an image tag, and need to specify a backup image in case the one you need is not available on the server for any reason. <img src="imagenotfound.gif" onerror="this.onerror=null;this.src='imagefound.gif';" /> the reason we have the this.onerror=null in the function is that the browser will be stuck in an endless loop if the onerror image itself generates an error. notes when an error occurs in a script, loaded from a different origin, the details of the error are not reported to prevent leaking information (se...
HTMLImageElement.alt - Web APIs
the htmlimageelement property alt provides fallback (alternate) text to display when the image specified by the <img> element is not loaded. this may be the case because of an error, because the user has disabled the loading of images, or because the image simply hasn't finished loading yet. perhaps the most important reason to use the alt tag is to support accessibility, as the alt text may be used by screen readers and other assistive technologies to help differently-abled users make full use of your content. it will be read aloud or sent to the touch device, for example, to support visually impaired users. think of it like this: when choosing alt strings for your images, imagine what you would say when reading the page to someone over the phone without mentioning that there's an image on ...
...alt; value a domstring which contains the alternate text to display when the image is not loaded or for use by assistive devices. the alt attribute is officially mandatory; it's meant to always be specified. if the image doesn't require a fallback (such as for an image which is simply decorative or an advisory icon of minimal importance), you may specify an empty string (""). for compatibility reasons, browsers generally will accept an image without an alt attribute, but you should try to get into the habit of using it. usage notes the fundamental guideline for the alt attribute is that every image's alternate text should be able to replace the image without altering the meaning of the page. you should never use alt for text that could be construed as a caption or title. there are separate ...
HTMLMediaElement.play() - Web APIs
note: older browsers may not return a value from play(). ...
... note: older browsers may not return a value from play(). ...
Headers.delete() - Web APIs
Web › API › Headers › delete
these headers include the forbidden header names and forbidden response header names. syntax myheaders.delete(name); parameters name the name of the http header you want to delete from the headers object. returns void. ...
...these headers include the forbidden header names and forbidden response header names. syntax myheaders.delete(name); parameters name the name of the http header you want to delete from the headers object. returns void. ...
IDBTransaction - Web APIs
foo", "readwrite"); var trans2 = db.transaction("foo", "readwrite"); var objectstore2 = trans2.objectstore("foo") var objectstore1 = trans1.objectstore("foo") objectstore2.put("2", "key"); objectstore1.put("1", "key"); after the code is executed the object store should contain the value "2", since trans2 should run after trans1. transaction failures transactions can fail for a fixed number of reasons, all of which (except the user agent crash) will trigger an abort callback: abort due to bad requests, e.g. trying to add() the same key twice, or put() with the same index key with a uniqueness constraint. this causes an error on the request, which can bubble up to an error on the transaction, which aborts the transaction. this can be prevented by using preventdefault() on the error event on...
...ually been flushed to disk. the complete event may thus be delivered quicker than before, however, there exists a small chance that the entire transaction will be lost if the os crashes or there is a loss of system power before the data is flushed to disk. since such catastrophic events are rare, most consumers should not need to concern themselves further. if you must ensure durability for some reason (e.g. you're storing critical data that cannot be recomputed later) you can force a transaction to flush to disk before delivering the complete event by creating a transaction using the experimental (non-standard) readwriteflush mode (see idbdatabase.transaction. properties idbtransaction.db read only the database connection with which this transaction is associated. idbtransaction.error r...
KeyboardEvent - Web APIs
examples include alphanumeric keys on the standard pc 101 us keyboard, the numlock key, and the space bar. dom_key_location_left 0x01 the key is one which may exist in multiple locations on the keyboard and, in this instance, is on the left side of the keyboard. examples include the left control key, the left command key ...
...the event behavior depends on the specific platform. it will either behave like windows or mac depending on what the native event model does. note: manually firing an event does not generate the default action associated with that event. for example, manually firing a key event does not cause that letter to appear in a focused text input. in the case of ui events, this is important for security reasons, as it prevents scripts from simulating user actions that interact with the browser itself. example <!doctype html> <html> <head> <script> 'use strict'; document.addeventlistener('keydown', (event) => { const keyname = event.key; if (keyname === 'control') { // do not alert when only control key is pressed. return; } if (event.ctrlkey) { // even though event.key is not '...
MediaTrackSettings - Web APIs
false. latency a double-precision floating point value indicating the current value of the latency property, specifying the audio latency, in seconds. latency is the amount of time which elapses between the start of processing the audio and the data being available to the next stop in the audio utilization process. this value is a target value; actual latency may vary to some extent for various reasons. noisesuppression a boolean which indicates the current value of the noisesupression property, which is true if noise suppression is enabled and is false otherwise. samplerate a long integer value indicating the current value of the samplerate property, specifying the sample rate in samples per second of the audio data. standard cd-quality audio, for example, has a sample rate of 41,000 s...
...device, used for general photography. "left" a camera facing toward the environment to the user's left. "right" a camera facing toward the environment to the user's right. framerate a double-precision floating point value indicating the current value of the framerate property, specifying how many frames of video per second the track includes. if the value can't be determined for any reason, the value will match the vertical sync rate of the device the user agent is running on. height a long integer value indicating the current value of the height property, specifying the height of the track's video data in pixels. width a long integer value indicating the current value of the width property, specifying the width of the track's video data in pixels. resizemode a domstring indi...
PaymentRequest.show() - Web APIs
it may only be called while handling events that represent user interactions, such as click, keyup, or the like. only one payment request can be in the process of being handled at once, across all documents. ...
...uest (its state is interactive because it is being shown already). notsupportederror the promise rejects with a notsupportederror if the user agent does not support the payment methods specified when the paymentrequest constructor was called. securityerror the promise rejects with a securityerror if the call to show() was not in response to a user action, such as a click or keyup event. other reasons a securityerror may be thrown are at the discretion of the user agent, and may include situations such as too many calls to show() being made in a short time or show() being called while payment requests are blocked by parental controls. 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 an...
PromiseRejectionEvent.promise - Web APIs
the promiserejectionevent interface's promise read-only property indicates the javascript promise which was rejected. you can examine the event's promiserejectionevent.reason property to learn why the promise was rejected. syntax promise = promiserejectionevent.promise value the javascript promise which was rejected, and whose rejection went unhandled. examples this example listens for unhandled promises and, if the reason is an object with a code field containing the text "module not ready", it sets up an idle callback that will retry the task that failed to execute correctly. ...
...ction went unhandled. examples this example listens for unhandled promises and, if the reason is an object with a code field containing the text "module not ready", it sets up an idle callback that will retry the task that failed to execute correctly. event.preventdefault() is called to indicate that the promise has now been handled. 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. living stan...
PromiseRejectionEvent - Web APIs
v> a:hover text { fill: #0095dd; pointer-events: all;} constructor promiserejectionevent() creates a promiserejectionevent event, given the type of event (unhandledrejection or rejectionhandled) and other details. properties also inherits properties from its parent event. promiserejectionevent.promise read only the javascript promise that was rejected. promiserejectionevent.reason read only a value or object indicating why the promise was rejected, as passed to promise.reject(). methods this interface has no unique methods; inherits methods from its parent event. events rejectionhandled fired when a javascript promise is rejected, and after the rejection is handled by the promise's rejection handling code. unhandledrejection fired when a javascript promise is r...
...script promise is rejected, and after the rejection is handled by the promise's rejection handling code. unhandledrejection fired when a javascript promise is rejected but there is no rejection handler to deal with the rejection. examples this simple example catches unhandled promise rejections and logs them for debugging purposes. window.onunhandledrejection = function(e) { console.log(e.reason); } specifications specification status comment html living standardthe definition of 'promiserejectionevent' in that specification. living standard initial definition. ...
RTCPeerConnection.addIceCandidate() - Web APIs
rned by this method is rejected, returning one of the errors below as the name attribute in the specified domexception object passed to the rejection handler. typeerror the specified candidate's sdpmid and sdpmlineindex are both null. invalidstateerror the rtcpeerconnection currently has no remote peer established (remotedescription is null). operationerror this can happen for a number of reasons: the value specified for sdpmid is non-null and doesn't match the media description id of any media description included within the remotedescription. the specified value of sdpmlineindex is greater than or equal to the number of media descriptions included in the remote description. the specified ufrag doesn't match the ufrag field in any of the remote descriptions being considered. o...
... the remotedescription. the specified value of sdpmlineindex is greater than or equal to the number of media descriptions included in the remote description. the specified ufrag doesn't match the ufrag field in any of the remote descriptions being considered. one or more of the values in the candidate string are invalid or could not be parsed. attempting to add the candidate fails for any reason. examples this code snippet shows how to signal ice candidates across an arbitrary signaling channel. // this example assumes that the other peer is using a signaling channel as follows: // // pc.onicecandidate = event => { // if (event.candidate) { // signalingchannel.send(json.stringify({ice: event.candidate})); // "ice" is arbitrary // } else { // // all ice candidates hav...
RTCPeerConnection.createOffer() - Web APIs
the rtcpeerconnection is closed. notreadableerror no certificate or set of certificates was provided for securing the connection, and createoffer() was unable to create a new one. since all webrtc connections are required to be secured, that results in an error. operationerror examining the state of the system to determine resource availability in order to generate the offer failed for some reason. example here we see a handler for the negotiationneeded event which creates the offer and sends it to the remote system over a signaling channel. note: keep in mind that this is part of the signaling process, the transport layer for which is an implementation detail that's entirely up to you. in this case, a websocket connection is used to send a json message with a type field with the valu...
...everything else in the promise fulfillment handler, depend entirely on your design. 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 successful, the local end of the rtcpeerconnection is configured to match by passing the offer (which is represented using an object conforming to rtcsessiondescriptioninit) into setlocaldescription(). once that's done, the offer is sent to the remote system over the signaling channel...
ReadableStreamDefaultReader.cancel() - Web APIs
the cancel() method of the readablestreamdefaultreader interface cancels the stream, signaling a loss of interest in the stream by a consumer. the supplied reason argument will be given to the underlying source, which may or may not use it. cancel is used when you've completely finished with the stream and don't need any more data from it, even if there are chunks enqueued waiting to be read. that data is lost after cancel is called, and the stream is not readable any more. to read those chunks still and not completely get rid of the stream, you'd use readablestreamdefaultcontroller.close(). ...
...be read. that data is lost after cancel is called, and the stream is not readable any more. to read those chunks still and not completely get rid of the stream, you'd use readablestreamdefaultcontroller.close(). note: if the reader is active, the cancel() method behaves the same as that for the associated stream (readablestream.cancel()). syntax var promise = readablestreamdefaultreader.cancel(reason); parameters reason optional a domstring providing a human-readable reason for the cancellation. return value a promise, which fulfills with the value given in the reason parameter. exceptions typeerror the source object is not a readablestreamdefaultreader, or the stream has no owner. examples in the following simple example, a previously-created custom readablestream is read usi...
Using the Screen Capture API - Web APIs
s in part or completely obscured, either by being overlapped by another object to some extent, or by being entirely hidden or offscreen. how these are handled by the screen capture api varies. generally, the browser will provide an image which obscures the hidden portion of the logical display surface in some way, such as by blurring or replacing with a color or pattern. this is done for security reasons, as the content that cannot be seen by the user may contain data which they do not want to share. a user agent might allow the capture of the entire content of an obscured window after gaining permission from the user to do so. in this case, the user agent may include the obscured content, either by getting the current contents of the hidden portion of the window or by presenting the most-recen...
...urces available for capture by the screen sharing api. this ensures that web applications can't force the user to share specific content by restricting the source list until only one item is left. while display capture is in effect, the machine which is sharing screen contents will display some form of indicator so the user is aware that sharing is taking place. note: for privacy and security reasons, screen sharing sources are not enumerable using enumeratedevices(). related to this, the devicechange event is never sent when there are changes to the sources available for getdisplaymedia(). capturing shared audio getdisplaymedia() is most commonly used to capture video of a user's screen (or parts thereof). however, user agents may allow the capture of audio along with the video content. ...
Storage API - Web APIs
ser agent to decide to make the site's storage unit persistent due to usage characteristics or other metrics. the "persistent-storage" feature's permission-related flags, algorithms, and types are all set to the standard defaults for a permission, except that the permission state must be the same across the entire origin, and that if the permission state isn't "granted" (meaning that for whatever reason, access to the persistent storage feature was denied), the origin's site storage unit's box mode is always "best-effort". note: see using the permissions api for further details about obtaining and managing permissions. when clearing site storage units, an origin's box is treated as a single entity; if the user agent needs to clear it and the user approves, the entire data store is cleared ra...
...he user will be asked specifically for permission to remove persistent site storage units. quotas and usage estimates the user agent determines, using whatever mechanism it chooses, the maximum amount of storage a given site can use. this maximum is the origin's quota. the amount of this space which is in use by the site is called its usage. both of these values are estimates; there are several reasons why they're not precise: user agents are encouraged to obscure the exact size of the data used by a given origin, to prevent these values from being used for fingerprinting purposes. de-duplication, compression, and other methods to reduce the physical size of the stored data may be used. quotas are conservative estimates of the space available for the origin's use, and should be less than ...
Using writable streams - Web APIs
t how the writable stream functionality in our demo works. constructing a writable stream to create a writable stream, we use the writablestream() constructor; the syntax looks complex at first, but actually isn’t too bad. the syntax skeleton looks like this: const stream = new writablestream({ start(controller) { }, write(chunk,controller) { }, close(controller) { }, abort(reason) { } }, { highwatermark, size() }); the constructor takes two objects as parameters. the first object is required, and creates a model in javascript of the underlying sink the data is being written to. the second object is optional, and allows you to specify a custom queueing strategy to use for your stream, which takes the form of an instance of bytelengthqueuingstrategy or countqueuings...
...k. write(chunk,controller) — a method that is called repeatedly every time a new chunk is ready to be written to the underlying sink (specified in the chunk parameter). close(controller) — a method that is called if the app signals that it has finished writing chunks to the stream. it should do whatever is necessary to finalize writes to the underlying sink, and release access to it. abort(reason) — a method that will be called if the app signals that it wishes to abruptly close the stream and put it in an errored state. the constructor call in our example looks like this: const decoder = new textdecoder("utf-8"); const queuingstrategy = new countqueuingstrategy({ highwatermark: 1 }); let result = ""; const writablestream = new writablestream({ // implement the sink write(chunk) ...
SubtleCrypto.encrypt() - Web APIs
s with an arraybuffer containing the "ciphertext". exceptions the promise is rejected when the following exceptions are encountered: invalidaccesserror raised when the requested operation is not valid for the provided key (e.g. invalid encryption algorithm, or invalid key for the specified encryption algorithm). operationerror raised when the operation failed for an operation-specific reason (e.g. algorithm parameters of invalid sizes, or aes-gcm plaintext longer than 2³⁹−256 bytes). supported algorithms the web crypto api provides four algorithms that support the encrypt() and decrypt() operations. one of these algorithms — rsa-oaep — is a public-key cryptosystem. the other three encryption algorithms here are all symmetric algorithms, and they're all based on the same...
...st 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. gcm does provide built-in authentication, and for this reason it's often recommended over the other two aes modes. rsa-oaep the rsa-oaep public-key encryption system is specified in rfc 3447. aes-ctr this represents aes in counter mode, as specified in nist sp800-38a. aes-cbc this represents aes in cipher block chaining mode, as specified in nist sp800-38a. aes-gcm this represents aes in galois/counter mode, as specified in nist sp800-38d. one majo...
WebGL model view projection - Web APIs
th behind it check out some of the following links: opengl projection matrix perspective projection trying to understand the math behind the perspective projection matrix in webgl one important thing to note about the perspective projection matrix used below is that it flips the z axis. in clip space the z+ goes away from the viewer, while with this matrix it comes towards the viewer. the reason to flip the z axis is that the clip space coordinate system is a left-handed coordinate system (wherein the z-axis points away from the viewer and into the screen), while the convention in mathematics, physics and 3d modeling, as well as for the view/eye coordinate system in opengl, is to use a right-handed coordinate system (z-axis points out of the screen towards the viewer) . more on that in t...
...a positive number indicating the distance into the screen to a plane which is perpendicular to the floor, nearer than which everything gets clipped away. this is mapped to -1 in clip space, and should not be set to 0. farclippingplanedistance a positive number indicating the distance to the plane beyond which geometry is clipped away. this is mapped to 1 in clip space. this value should be kept reasonably close to the distance of the geometry in order to avoid precision errors creeping in while rendering. in the latest version of the box demo, the computesimpleprojectionmatrix() method has been replaced with the computeperspectivematrix() method. cubedemo.prototype.computeperspectivematrix = function() { var fieldofviewinradians = math.pi * 0.5; var aspectratio = window.innerwidth / win...
Writing WebSocket client applications - Web APIs
cure link for all websocket connections unless they're on the same device or possibly on the same network). 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. the browser may also output to its console a more descriptive error message as well as a closing code as defined in rfc 6455, section 7.4 through the closeevent. examples this simple example creates a new websocket, connecting to the server at wss://www.example.com/socketserver. a custom protocol of "protocolone" is named in the request for the socket in this exam...
... websocket object will be successful. we can at least be sure that attempting to send data only takes place once a connection is established by defining an onopen event handler to do the work: examplesocket.onopen = function (event) { examplesocket.send("here's some text that the server is urgently awaiting!"); }; using json to transmit objects one handy thing you can do is use json to send reasonably complex data to the server. for example, a chat program can interact with a server using a protocol implemented using packets of json-encapsulated data: // send text to all users through the server function sendtext() { // construct a msg object containing the data the server needs to process the message from the chat client. var msg = { type: "message", text: document.getelement...
Writing WebSocket servers - Web APIs
rver. note: read the latest official websockets specification, rfc 6455. sections 1 and 4-7 are especially interesting to server implementors. section 10 discusses security and you should definitely peruse it before exposing your server. a websocket server is explained on a very low level here. websocket servers are often separate and specialized servers (for load-balancing or other practical reasons), so you will often use a reverse proxy (such as a regular http server) to detect websocket handshakes, pre-process them, and send those clients to a real websocket server. this means that you don't have to bloat your server code with cookie and authentication handlers (for example). the websocket handshake first, the server must listen for incoming socket connections using a standard tcp sock...
...tomatically allowing or denying, etc.) and send a 403 forbidden if you don't like what you see. however, be warned that non-browser agents can send a faked origin. most applications reject requests without this header. if any header is not understood or has an incorrect value, the server should send a 400 ("bad request")} response and immediately close the socket. as usual, it may also give the reason why the handshake failed in the http response body, but the message may never be displayed (browsers do not display it). if the server doesn't understand that version of websockets, it should send a sec-websocket-version header back that contains the version(s) it does understand. in the example above, it indicates version 13 of the websocket protocol. the most interesting header here is sec-we...
Spaces and reference spaces: Spatial tracking in WebXR - Web APIs
0.5, y: 0.5, z: 0.5, w: 1.0 }); arefspace = arefspace.getoffsetreferencespace(halfmetertransform); this replaces the existing reference space arefspace with one whose coordinates and orientation have had the transform halfmetertransform applied. with no orientation data included in the transform, the orientation of arefspace is unaffected. converting between webxr session types another common reason you may need to convert positional information from one reference space to another is when it's necessary to change the session type from inline to immersive-vr or back. this commonly happens when your user interface provides a way to preview the scene inline within the context of a web page, with a button or other control to switch to immersive mode. since most users would prefer that you maint...
...ve to the user's environment. a reset may occur because the xr hardware lost connectivity for a time, resulting in the user's movements not being properly tracked for a while. upon recovery of tracking, a reset means tracking has been restored and the new position information represents the actual position information provided by the xr hardware, rather than cached or "best-guess" data. another reason reset may be sent is because the user has exited the bounds of a reference space and entered another reference space, or because the user has been transitioned programmatically from one reference space to another. any time the bounds geometry of the user's space changes, a reset is sent. reset is only used for signficant jumps or transitions; minor things will just be absorbed automatically. the...
Starting up and shutting down a WebXR session - Web APIs
the world around the user with the images you present. immersive-ar an augmented reality session in which images are added to the real world using a headset or similar apparatus. this option is not yet widely supported, as the ar specification is in flux. inline an on-screen presentation of the xr imagery within the context of the document window. if the session couldn't be created for some reason—such as feature policy disallowing its use or the user declining to grant permission to use the headset—the promise gets rejected. so a more complete function that starts up and returns a webxr session could look like this: async function createimmersivesession(xr) { try { session = await xr.requestsession("immersive-vr"); return session; } catch(error) { throw error; } } ...
... ...
Migrating from webkitAudioContext - Web APIs
how to update your code to use the modern web audio api. the web audio standard was first implemented in webkit, and the implementation was built in parallel with the work on the specification of the api. as the specification evolved and changes were made to the spec, some of the old implementation pieces were not removed from the webkit (and blink) implementations due to backwards compatibility reasons. new engines implementing the web audio spec (such as gecko) will only implement the official, final version of the specification, which means that code using webkitaudiocontext or old naming conventions in the web audio specification may not immediately work out of the box in a compliant web audio implementation. this article attempts to summarize the areas where developers are likely to enco...
... and 1, respectively. note that these bounds are not enforced by the engine, and are merely used for informational purposes. as an example, it's perfectly valid to set a gain value to 2, or even -1. in order to find out these nominal values, you can consult the specification. the units attribute as implemented in webkitaudiocontext implementations is unused, and always returns 0. there is no reason why you should need this attribute. removal of mediaelementaudiosourcenode.mediaelement the mediaelement attribute of mediaelementaudiosourcenode has been removed. you can keep a reference to the media element used to create this node if you need to access it later. removal of mediastreamaudiosourcenode.mediastream the mediastream attribute of mediastreamaudiosourcenode has been removed. y...
WindowOrWorkerGlobalScope.setInterval() - Web APIs
unction[, delay]); var intervalid = scope.setinterval(code, [delay]); parameters func a function to be executed every delay milliseconds. the function is not passed any arguments, and no return value is expected. code an optional syntax allows you to include a string instead of a function, which is compiled and executed every delay milliseconds. this syntax is not recommended for the same reasons that make using eval() a security risk. delayoptional the time, in milliseconds (thousandths of a second), the timer should delay in between executions of the specified function or code. see delay restrictions below for details on the permitted range of delay values. arg1, ..., argn optional additional arguments which are passed through to the function specified by func once the timer expire...
...minimum value for the interval. attempts to specify a value less than 4 ms in deeply-nested calls to setinterval() will be pinned to 4 ms. browsers may enforce even more stringent minimum values for the interval under some circumstances, although these should not be common. note also that the actual amount of time that elapses between calls to the callback may be longer than the given delay; see reasons for delays longer than specified in windoworworkerglobalscope.settimeout() for examples. ensure that execution duration is shorter than interval frequency if there is a possibility that your logic could take longer to execute than the interval time, it is recommended that you recursively call a named function using settimeout(). for example, if using setinterval() to poll a remote server every...
WritableStream.WritableStream() - Web APIs
is necessary to finalize writes to the underlying sink, and release access to it. if this process is asynchronous, it can return a promise to signal success or failure. this method will be called only after all queued-up writes have succeeded. the controller parameter passed to this method is a writablestreamdefaultcontroller, which can be used to control the stream at the end of writing. abort(reason) optional this method, also defined by the developer, will be called if the app signals that it wishes to abruptly close the stream and put it in an errored state. it can clean up any held resources, much like close(), but abort() will be called even if writes are queued up — those chunks will be thrown away. if this process is asynchronous, it can return a promise to signal success or failur...
...nal this method, also defined by the developer, will be called if the app signals that it wishes to abruptly close the stream and put it in an errored state. it can clean up any held resources, much like close(), but abort() will be called even if writes are queued up — those chunks will be thrown away. if this process is asynchronous, it can return a promise to signal success or failure. the reason parameter contains a domstring describing why the stream was aborted. queuingstrategy optional an object that optionally defines a queuing strategy for the stream. this takes two parameters: highwatermark a non-negative integer — this defines the total number of chunks that can be contained in the internal queue before backpressure is applied. size(chunk) a method containing a p...
WritableStreamDefaultWriter.abort() - Web APIs
borts the stream, signaling that the producer can no longer successfully write to the stream and it is to be immediately moved to an error state, with any queued writes discarded. if the writer is active, the abort() method behaves the same as that for the associated stream (writablestream.abort()). if not, it returns a rejected promise. syntax var promise = writablestreamdefaultwriter.abort(reason); parameters reason optional a domstring representing a human-readable reason for the abort. return value a promise, which fulfills with the value given in the reason parameter. exceptions typeerror the stream you are trying to abort is not a writablestream, or it is locked. examples const writablestream = new writablestream({ write(chunk) { ... }, close() { ... },...
...given in the reason parameter. exceptions typeerror the stream you are trying to abort is not a writablestream, or it is locked. examples const writablestream = new writablestream({ write(chunk) { ... }, close() { ... }, abort(err) { ... } }, queuingstrategy); ... const writer = writablestream.getwriter(); ... // abort the stream when desired writer.abort.then((reason) => { console.log(reason); }) specifications specification status comment streamsthe definition of 'abort()' in that specification. living standard initial definition. ...
Using XMLHttpRequest - Web APIs
d to the url: ?foo=bar&baz=the%20first%20line.%0athe%20second%20line. a little vanilla framework all these effects are done automatically by the web browser whenever you submit a <form>. if you want to perform the same effects using javascript you have to instruct the interpreter about everything. therefore, how to send forms in pure ajax is too complex to be explained here in detail. ...
... echo "\n\n:: data received as \"raw\" (text/plain encoding) ::\n\n"; if (isset($http_raw_post_data)) { echo $http_raw_post_data; } echo "\n\n:: files received ::\n\n"; print_r($_files); the syntax to activate this script is simply: ajaxsubmit(myform); note: this framework uses the filereader api to transmit file uploads. this is a recent api and is not implemented in ie9 or below. for this reason, the ajax-only upload is considered an experimental technique. if you do not need to upload binary files, this framework works fine in most browsers. note: the best way to send binary content is via arraybuffers or blobs in conjuncton with the send() method and possibly the readasarraybuffer() method of the filereader api. but, since the aim of this script is to work with a stringifiable raw dat...
XRSystem: requestSession() - Web APIs
tly active or in the process of being set up. there can only be one immersive vr session at a time. notsupportederror there is no webxr-compatible device available, or the device does not support the specified sessionmode; this can also be thrown if any of the required options are unsupported. securityerror permission to enter the specified xr mode is denied. this can happen for a number of reasons, which are covered in more detail in permissions and security in webxr device api. examples creating an immersive vr session the following example calls requestsession() requesting an "immersive-vr" session. if the promise resolves, it sets up a session and initiates the animation loop. navigator.xr.requestsession("immersive-vr") .then((xrsession) => { xrsession.addeventlistener('end', ...
... onsessionstarted(xrsession); }); } else { // button is a toggle button. xrsession.end().then(() => xrsession = null); } } specifications specification status comment webxr device apithe definition of 'requestsession()' in that specification. working draft initial definition. ...
Accessibility and Spacial Patterns - Accessibility
tern are the guidelines contravened? if so, reduce brightness. text and padding wcag standards for contrast perception do not take into account the effect of padding. for example, blue text on a gray background is easier to perceive if it is surrounded "locally" by black than by white. there is such a thing as "local" adaptation to colors. the bottom line: padding matters. math spatial reasoning affects math learning; consequently, spatial relationships in how math is presented affects cognition. the web developer can do something about this in the manner in which he displays math. animation figures strongly in this arena. for example, "how" an object looks when it is rotated, from different angles, how they look sliced, and how they relate to each other in space all make a differ...
...ee also mdn accessibiltity: what users can do to browse more safely web accessibiltity for seizures and physical reactions web accessibility: understanding colors and luminance braille part 3: a step-by-step guide to typesetting ada braille correctly in adobe illustrator spatial math in brailleblaster (4 of 5) government literature nasa: designing with blue math spatial reasoning: why math talk is about more than numbers scientific literature colour constancy in context: roles for local adaptation and levels of reference gamma oscillations and photosensitive epilepsy characterizing the patterned images that precipitate seizures and optimizing guidelines to prevent them arnold wilkins, john emmett, and graham harding contributers: heartfelt thanks to jim alla...
Implementing a Microsoft Active Accessibility (MSAA) Server - Accessibility
vents are being generated by a given piece of software. the accessible explorer and inspect object tools show the tree of data nodes the accessible object is exposing through com, and what the screen boundaries of each object are. in addition, msdn has improved their msaa documentation. when to use msaa, and when not to it's a common mistake to say that msaa is not worth using, for a number of reasons. myths for not using msaa myth: msaa doesn't really work reality: msaa works really well for dialogs and ui. true, it's not great for documents, but it's the only existing widely-used standard for exposing accessibility. myth: msaa is too slow reality: assistive technology vendors have found ways around most of the performance problems related to out-of-process com method calls. just make s...
...technology company. be as easy to work with as you possibly can -- this includes being extremely responsive to their bug reports with new test builds, as well as being very communicative about what you have changed and when. do as much work as you possibly can without their help. see if your organization can offer something they can't get for themselves. be patient, and set your expectations to a reasonable level. realize that it's about both pride and revenue for these companies, and that they need to sell a lot of copies of their software to make up the work they put in to support your app. remember that no matter how small they are, you need them more than they need you, unless your application's accessibility is being demanded by end-users. example: how gecko and mozilla implement msaa the...
Aligning Items in a Flex Container - CSS: Cascading Style Sheets
it enabled proper vertical alignment, so we can at last easily center a box. in this guide, we will take a thorough look at how the alignment and justification properties work in flexbox. to center our box we use the align-items property to align our item on the cross axis, which in this case is the block axis running vertically. we use justify-content to align the item on the main axis, which in this case the inline axis running horizontally. you can take a look at the code of this example below. change the size of the container or nested element and the nested element always remains centered. ...
...ent in the most simple flex example. if we add display: flex to a container, the child items all become flex items arranged in a row. they will all stretch to be as tall as the tallest item, as that item is defining the height of the items on the cross axis. 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. the reason the items become the same height is that the initial value of align-items, the property that controls alignment on the cross axis, is set to stretch. we can use other values to control how the items align: align-items: flex-start align-items: flex-end align-items: center align-items: stretch align-items: baseline in the live example below, the value of align-items is stretch. try the ot...
WebKit CSS extensions - CSS: Cascading Style Sheets
-webkit-transform-origin -webkit-transition -webkit-transition-delay -webkit-transition-duration -webkit-transition-property -webkit-transition-timing-function u -webkit-user-select *supported with -moz- and -webkit- prefix in firefox, but not supported without a prefix. microsoft edge and ie mobile support this property with the -webkit- prefix, rather than -ms- for interopability reasons as well. ** these values are supported even though they are not standard and are not on track to becoming standard. *** use flex-box properties instead. deprecated -webkit- properties the following properties were once supported with the -webkit- prefix but are no longer supported in evergreen browsers, with or without the -webkit- prefix. -webkit-alt* -webkit-color-correction -webkit-...
... :-webkit-autofill :-webkit-autofill-strong-password :-webkit-drag :-webkit-full-page-media :-webkit-full-screen* :-webkit-full-screen-ancestor :-webkit-full-screen-document :-webkit-full-screen-controls-hidden * now standard. note: if there is an invalid pseudo-class within in a chain or group of selectors, the whole selector list is invalid. pseudo-elements for web-compatibility reasons, blink, webkit, and gecko browsers treat all pseudo-elements starting with ::-webkit- as valid. ::-webkit-file-upload-button ::-webkit-inner-spin-button ::-webkit-input-placeholder ::-webkit-media-controls ::-webkit-media-controls-current-time-display ::-webkit-media-controls-enclosure ::-webkit-media-controls-fullscreen-button ::-webkit-media-controls-mute-button ::-webkit-media-con...
color-adjust - CSS: Cascading Style Sheets
ered by the browser might actually make things worse rather than better. the appearance of the content should not be changed except by the user's request. for example, a page might include a list of information with rows whose background colors alternate between white and a light grey. removing the background color would decrease the legibility of the content. usage notes there are a number of reasons a browser might wish to deviate from the specified appearance, such as: the content uses text and background colors that will be too similar on the output device for legibility purposes. if the output device is a printer, and to save ink, dark or extremely dense background images might be removed. when printing a page, the browser might want to replace light-colored text on a dark backgroun...
...ion. formal definition initial valueeconomyapplies toall elementsinheritedyescomputed valueas specifiedanimation typediscrete formal syntax economy | exact examples preserving low contrast in this example, a box is shown which uses a background-image and a translucent linear-gradient() function atop a black background color to have a dark blue gradient behind medium red text. for whatever reason, this is the desired appearance in any rendering environment, including on paper, so we also use color-adjust: exact to tell the browser not to make color or style adjustments to the box when rendering it. css .my-box { background-color: black; background-image: linear-gradient(rgba(0, 0, 180, 0.5), rgba(70, 140, 220, 0.5)); color: #900; width: 15rem; height: 6rem; text-align: cente...
Adapting to the new two-value syntax of display - CSS: Cascading Style Sheets
it also details the in-built backwards compatibility for the display property. what happens when we change the value of the display property? one of the first things we learn about css is that some elements are block-level and some are inline-level. for example, an <h1> or a <p> are block-level by default, and a <span> is inline-level. using the display property we can switch between block and inline. ...
...e syntax for display: flow-root being display: block flow-root therefore makes a lot of sense. you are creating a block formatting context, with a block-level box and children participating in normal flow. what about the matched pair display: inline flow-root? this is the new way of describing display: inline-block. the value display: inline-block has been around since the early days of css. the reason we tend to use it is to allow padding to push inline items away from an element, when creating navigation items for example, or when wanting to add a background with padding to an inline element as in the example below. an element with display: inline-block however, will also contain floats. it contains everything inside the inline-level box. therefore display: inline-block does exactly what d...
Video player styling basics - Developer guides
element has the following basic style set up: .controls progress { display:block; width:100%; height:81%; margin-top:0.125rem; border:none; color:#0095dd; -moz-border-radius:2px; -webkit-border-radius:2px; border-radius:2px; } like the <button> elements, <progress> also has a default border, which is removed here. it is also given a slight rounded corner for aesthetic reasons. the color property is also defined here as internet explorer uses this defined colour for styling the progress bar's background colour as it increases. as mentioned in the previous article, there is a fallback provided for browsers that do not support the <progress> element; this also needs to be styled appropriately: .controls progress[data-state="fake"] { background:#e6e6e6; height:...
... progress.value = 0; // update the play/pause button's 'data-state' which allows the correct button image to be set via css changebuttonstate('playpause'); }); mute.addeventlistener('click', function(e) { video.muted = !video.muted; changebuttonstate('mute'); }); you might have noticed that there are new handlers where the play and pause events are reacted to on the video. there is a reason for this! even though the browser's default video control set has been turned off, many browsers make them accessible by right clicking on the html5 video. 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. if a user uses the default controls, the defined media api events — such as play and pause — are ra...
<i>: The Idiomatic Text element - HTML: Hypertext Markup Language
Web › HTML › Element › i
historically, these have been presented using italicized type, which is the original source of the <i> naming of this element. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. content categories flow content, phrasing content, palpable content. permitted content phrasing content. ...
... and ending tag are mandatory. permitted parents any element that accepts phrasing content. implicit aria role no corresponding role permitted aria roles any dom interface htmlelement attributes this element only includes the global attributes. usage notes use the <i> element for text that is set off from the normal prose for readability reasons. this would be a range of text with different semantic meaning than the surrounding text. among the use cases for the <i> element are spans of text representing a different quality or mode of text, such as: alternative voice or mood taxonomic designations (such as the genus and species "homo sapiens") idiomatic terms from another language (such as "et cetera"); these should include ...
<input>: The Input (Form Input) element - HTML: Hypertext Markup Language
Web › HTML › Element › input
he input's value is not submitted with the form! (disabled controls, unchecked radio buttons, unchecked checkboxes, and reset buttons are also not sent.) there are two special cases: _charset_ : if used as the name of an <input> element of type hidden, the input's value is automatically set by the user agent to the character encoding being used to submit the form. isindex: for historical reasons, the name isindex is not allowed. name and radio buttons the name attribute creates a unique behavior for radio buttons. only one radio button in a same-named group of radio buttons can be checked at a time. selecting any radio button in that group automatically deselects any currently-selected radio button in the same group. the value of that one checked radio button is sent along with ...
... if there is an error, supporting browsers will both alert the user and prevent the form from being submitted. a word of caution: if a custom error is set to a truthy value (anything other than the empty string or null), the form will be be prevented from being...
<sub>: The Subscript element - HTML: Hypertext Markup Language
Web › HTML › Element › sub
subscripts are typically rendered with a lowered baseline using smaller text. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. content categories flow content, phrasing content, palpable content. permitted content phrasing content. tag omission none, both the starting and ending tag are mandatory. ...
...on none, both the starting and ending tag are mandatory. permitted parents any element that accepts phrasing content. implicit aria role no corresponding role permitted aria roles any dom interface htmlelement attributes this element only includes the global attributes. usage notes the <sub> element should be used only for typographical reasons—that is, to change the position of the text to comply with typographical conventions or standards, rather than solely for presentation or appearance purposes. for example, using <sub> to style the name of a company which uses altered baselines in their wordmark would not be appropriate; instead, css should be used (likely the vertical-align property, such as vertical-align: sub or, to more pr...
<sup>: The Superscript element - HTML: Hypertext Markup Language
Web › HTML › Element › sup
superscripts are usually rendered with a raised baseline using smaller text. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. content categories flow content, phrasing content, palpable content. permitted content phrasing content. tag omission none, both the starting and ending tag are mandatory. ...
...on none, both the starting and ending tag are mandatory. permitted parents any element that accepts phrasing content. implicit aria role no corresponding role permitted aria roles any dom interface htmlelement attributes this element only includes the global attributes. usage notes the <sup> element should only be used for typographical reasons—that is, to change the position of the text to comply with typographical conventions or standards, rather than solely for presentation or appearance purposes. for example, to style the wordmark of a business or product which uses a raised baseline should be done using css (most likely vertical-align) rather than <sup>. this would be done using, for example, vertical-align: super or, to shift ...
HTML elements reference - HTML: Hypertext Markup Language
Web › HTML › Element
ed to indicate the term being defined within the context of a definition phrase or sentence. <em> the html <em> element marks text that has stress emphasis. the <em> element can be nested, with each level of nesting indicating a greater degree of emphasis. <i> the html idiomatic text element (<i>) represents a range of text that is set off from the normal text for some reason, such as idiomatic text, technical terms, taxonomical designations, among others. <kbd> the html keyboard input element (<kbd>) represents a span of inline text denoting textual user input from a keyboard, voice input, or any other text entry device. <mark> the html mark text element (<mark>) represents text which is marked or highlighted for reference or notation purp...
...tes), or because they share attribute values, such as lang. <strong> the html strong importance element (<strong>) indicates that its contents have strong importance, seriousness, or urgency. browsers typically render the contents in bold type. <sub> the html subscript element (<sub>) specifies inline text which should be displayed as subscript for solely typographical reasons. <sup> the html superscript element (<sup>) specifies inline text which is to be displayed as superscript for solely typographical reasons. <time> the html <time> element represents a specific period in time. <u> the html unarticulated annotation element (<u>) represents a span of inline text which should be rendered in a way that indicates that it has a...
Identifying resources on the Web - HTTP
arget of an http request is called a "resource", whose nature isn't defined further; it can be a document, a photo, or anything else. each resource is identified by a uniform resource identifier (uri) used throughout http for identifying resources. the identity and the location of resources on the web are mostly given by a single url (uniform resource locator, a kind of uri). there are sometimes reasons identity and location are not given by the same uri: http uses a specific http header, alt-svc when the resource requested wants the client to access it at another location. urls and urns urls the most common form of uri is the uniform resource locator (url), which is known as the web address. https://developer.mozilla.org https://developer.mozilla.org/docs/learn/ https://developer.mozilla.o...
..., is never sent to the server with the request. usage notes when using urls in html content, you should generally only use a few of these url schemes. when referring to subresources — that is, files that are being loaded as part of a larger document — you should only use the http and https schemes. increasingly, browsers are removing support for using ftp to load subresources, for security reasons. ftp is still acceptable at the top level (such as typed directly into the browser's url bar, or the target of a link), although some browsers may delegate loading ftp content to another application. examples https://developer.mozilla.org/docs/learn tel:+1-816-555-1212 git@github.com:mdn/browser-compat-data.git ftp://example.org/resource.txt urn:isbn:9780141036144 mailto:help@supercyberhelpde...
MIME types (IANA media types) - HTTP
or application/xhtml+xml if you want xml’s strict parsing rules, <![cdata[…]]> sections, or elements that aren't from html/svg/mathml namespaces. text/javascript per the html specification, javascript files should always be served using the mime type text/javascript. no other values are considered valid, and using any of those may result in scripts that do not load or run. ...
...t/html; charset=utf-8" /> <meta name="vieport" content --3d6b6a416f9b5 content-type: text/html content-range: bytes 300-400/1270 -color: #f0f0f2; margin: 0; padding: 0; font-family: "open sans", "helvetica --3d6b6a416f9b5-- importance of setting the correct mime type most web servers send unrecognized resources as the application/octet-stream mime type. for security reasons, most browsers do not allow setting a custom default action for such resources, forcing the user to save it to disk to use it. some common incorrect server configurations: rar-compressed files. in this case, the ideal would be the true type of the original files; this is often impossible as .rar files can hold several resources of different types. in this case, configure the server to sen...
Cross-Origin Resource Sharing (CORS) - HTTP
Web › HTTP › CORS
n, access to selected resources from a different origin. a web application executes a cross-origin http request when it requests a resource that has a different origin (domain, protocol, or port) from its own. an example of a cross-origin request: the front-end javascript code served from https://domain-a.com uses xmlhttprequest to make a request for https://domain-b.com/data.json. for security reasons, browsers restrict cross-origin http requests initiated from scripts. for example, xmlhttprequest and the fetch api follow the same-origin policy. this means that a web application using those apis can only request resources from the same origin the application was loaded from unless the response from other origins includes the right cors headers. the cors mechanism supports secure cross-orig...
...s), 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. cors failures result in errors, but for security reasons, specifics about the error are not available to javascript. all the code knows is that an error occurred. the only way to determine what specifically went wrong is to look at the browser's console for details. subsequent sections discuss scenarios, as well as provide a breakdown of the http headers used. examples of access control scenarios we present three scenarios that demonstrate how cros...
Link prefetching FAQ - HTTP
estriction for link prefetching. limiting prefetching to only urls from the the same server would not offer any increased browser security. do prefetched requests contain a referer: header? yes, prefetched requests include a http referer: header indicating the document from which the prefetching hint was extracted. this may impact referrer tracking that is commonly used on many sites. for this reason, link prefetching may not be appropriate for all content. however, it is possible to instruct mozilla to validate a prefetched document when the user follows a href to the prefetched document by specifying the cache-control: must-revalidate http response header. this header enables caching, but requires an if-modified-since or if-none-match validation request before the serving the document out o...
...prefetching instead of trying to roll-in silent downloading using various js/dom hacks. the <link> tag gives the browser the ability to know what sites are up to, and we can use this information to better prioritize document prefetching. the user preference to disable <link> tag prefetching may simply encourage websites to stick with js/dom hacks, and that would not be good for users. this is one reason why prefetching is enabled by default. which browsers support link prefetching? browsers based on mozilla 1.2 (or later) as well as browsers based on mozilla 1.0.2 (or later) support prefetching. this includes firefox and netscape 7.01+. camino builds as of march 2003 are based on mozilla 1.0.1, and therefore do not support prefetching. test your browser to see if it supports link prefetching. ...
Network Error Logging - HTTP
st.com/" } } the type of the network error may be one of the following pre-defined values from the specification, but browsers can add and send their own error types: dns.unreachable the user's dns server is unreachable dns.name_not_resolved the user's dns server responded but was unable to resolve an ip address for the requested uri. dns.failed request to the dns server failed due to reasons not covered by previous errors (e.g. servfail) dns.address_changed for security reasons, if the server ip address that delivered the original report is different to the current server ip address at time of error generation, the report data will be downgraded to only include information about this problem and the type set to dns.address_changed. tcp.timed_out tcp connection to the server time...
...med_out tcp connection to the server timed out tcp.closed the tcp connection was closed by the server tcp.reset the tcp connection was reset tcp.refused the tcp connection was refused by the server tcp.aborted the tcp connection was aborted tcp.address_invalid the ip address is invalid tcp.address_unreachable the ip address is unreachable tcp.failed the tcp connection failed due to reasons not covered by previous errors http.error the user agent successfully received a response, but it had a 4xx or 5xx status code http.protocol.error the connection was aborted due to an http protocol error http.response.invalid response is empty, has a content-length mismatch, has improper encoding, and/or other conditions that prevent user agent from processing the response http.response.r...
Redirections in HTTP - HTTP
ts and other crawlers don't memorize the new, temporary url. temporary redirections are also used when creating, updating, or deleting resources, to show temporary progress pages. code text method handling typical use case 302 found get methods unchanged. others may or may not be changed to get.[2] the web page is temporarily unavailable for unforeseen reasons. 303 see other get methods unchanged. others changed to get (body lost). used to redirect after a put or a post, so that refreshing the result page doesn't re-trigger the operation. 307 temporary redirect method and body not changed the web page is temporarily unavailable for unforeseen reasons. better than 302 when non-get operations are available on the ...
...rects but forgets to change the html redirects, the redirects will no longer be identical, which could cause an infinite loop or other nightmares. use cases there are numerous use cases for redirects, but as performance is impacted with every redirect, their use should be kept to a minimum. domain aliasing ideally, there is one location, and therefore one url, for each resource. but there are reasons for alternative names for a resource: expanding the reach of your site a common case is when a site resides at www.example.com, but accessing it from example.com should also work. redirections for example.com to www.example.com are thus set up. you might also redirect from common synonyms or frequent typos of your domains. moving to a new domain for example, your company was renamed, but y...
Concurrency model and the event loop - JavaScript
me because of how it's usually implemented, which usually resembles: while (queue.waitformessage()) { queue.processnextmessage() } queue.waitformessage() waits synchronously for a message to arrive (if one is not already available and waiting to be handled). "run-to-completion" each message is processed completely before any other message is processed. this offers some nice properties when reasoning about your program, including the fact that whenever a function runs, it cannot be pre-empted and will run entirely before any other code runs (and can modify data the function manipulates). this differs from c, for instance, where if a function runs in a thread, it may be stopped at any point by the runtime system to run some other code in another thread. a downside of this model is that if ...
...o the queue, and a time value (optional; defaults to 0). the time value represents the (minimum) delay after which the message will actually be pushed into the queue. if there is no other message in the queue, and the stack is empty, the message is processed right after the delay. however, if there are messages, the settimeout message will have to wait for other messages to be processed. for this reason, the second argument indicates a minimum time—not a guaranteed time. here is an example that demonstrates this concept (settimeout does not run immediately after its timer expires): const s = new date().getseconds(); settimeout(function() { // prints out "2", meaning that the callback is not called immediately after 500 milliseconds. console.log("ran after " + (new date().getseconds() ...
Using Promises - JavaScript
d interface). the two events are: rejectionhandled sent when a promise is rejected, after that rejection has been handled by the executor's reject function. unhandledrejection sent when a promise is rejected but there is no rejection handler available. in both cases, the event (of type promiserejectionevent) has as members a promise property indicating the promise that was rejected, and a reason property that provides the reason given for the promise to be rejected. these make it possible to offer fallback error handling for promises, as well as to help debug issues with your promise management. these handlers are global per context, so all errors will go to the same event handlers, regardless of source. one case of special usefulness: when writing code for node.js, it's common that mo...
...these get logged to the console by the node runtime. you can capture these for analysis and handling by your code—or just to avoid having them cluttering up your output—by adding a handler for the unhandledrejection event, like this: window.addeventlistener("unhandledrejection", event => { /* you might start here by adding code to examine the promise specified by event.promise and the reason in event.reason */ event.preventdefault(); }, false); by calling the event's preventdefault() method, you tell the javascript runtime not to do its default action when rejected promises go unhandled. that default action usually involves logging the error to console, and this is indeed the case for node. ideally, of course, you should examine the rejected promises to make sure none of t...
Promise.all() - JavaScript
with value "555", so it gets rejected var p3 = promise.all([1,2,3, promise.reject(555)]); // using settimeout we can execute code after the stack is empty settimeout(function() { console.log(p); console.log(p2); console.log(p3); }); // logs // promise { <state>: "fulfilled", <value>: array[3] } // promise { <state>: "fulfilled", <value>: array[4] } // promise { <state>: "rejected", <reason>: 555 } asynchronicity or synchronicity of promise.all this following example demonstrates the asynchronicity (or synchronicity, if the iterable passed is empty) of promise.all: // we are passing as argument an array of promises that are already resolved, // to trigger promise.all as soon as possible var resolvedpromisesarray = [promise.resolve(33), promise.resolve(44)]; var p = promise.all(r...
...lfilled", <value>: array[2] } the same thing happens if promise.all rejects: var mixedpromisesarray = [promise.resolve(33), promise.reject(44)]; var p = promise.all(mixedpromisesarray); console.log(p); settimeout(function() { console.log('the stack is now empty'); console.log(p); }); // logs // promise { <state>: "pending" } // the stack is now empty // promise { <state>: "rejected", <reason>: 44 } but, promise.all resolves synchronously if and only if the iterable passed is empty: var p = promise.all([]); // will be immediately resolved var p2 = promise.all([1337, "hi"]); // non-promise values will be ignored, but the evaluation will be done asynchronously console.log(p); console.log(p2) settimeout(function() { console.log('the stack is now empty'); console.log(p2); }); ...
Promise.allSettled() - JavaScript
sed as input an array containing the outcome of each promise in the original set of promises. however, if and only if an empty iterable is passed as an argument, promise.allsettled() returns a promise object that has already been resolved as an empty array. for each outcome object, a status string is present. if the status is fulfilled, then a value is present. if the status is rejected, then a reason is present. the value (or reason) reflects what value each promise was fulfilled (or rejected) with. 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"...
...d (or rejected) with. 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. ...
Promise.prototype.catch() - JavaScript
provide an onrejected function even if you want to fall back to an undefined result value - for example obj.catch(() => {}). the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax p.catch(onrejected); p.catch(function(reason) { // rejection }); parameters onrejected a function called when the promise is rejected. this function has one argument: reason the rejection reason. the promise returned by catch() is rejected if onrejected throws an error or returns a promise which is itself rejected; otherwise, it is resolved. return value internally calls promise.prototype.then on the object upon which i...
...is never called }); // errors thrown after resolve is called will be silenced var p3 = new promise(function(resolve, reject) { resolve(); throw new error('silenced exception!'); }); p3.catch(function(e) { console.error(e); // this is never called }); if it is resolved //create a promise which would not call onreject var p1 = promise.resolve("calling next"); var p2 = p1.catch(function (reason) { //this is never called console.error("catch p1!"); console.error(reason); }); p2.then(function (value) { console.log("next promise's onfulfilled"); /* next promise's onfulfilled */ console.log(value); /* calling next */ }, function (reason) { console.log("next promise's onrejected"); console.log(reason); }); specifications specification ecma...
Promise.prototype.finally() - JavaScript
nally) 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. this use case is for precisely when you do not care about the rejection reason, or the fulfillment value, and so there's no need to provide it. so for example: unlike promise.resolve(2).then(() => {}, () => {}) (which will be resolved with undefined), promise.resolve(2).finally(() => {}) will be resolved with 2. similarly, unlike promise.reject(3).then(() => {}, () => {}) (which will be fulfilled with undefined), promise.reject(3).finally(() => {}) will be rejected...
...}) (which will be resolved with undefined), promise.resolve(2).finally(() => {}) will be resolved with 2. similarly, unlike promise.reject(3).then(() => {}, () => {}) (which will be fulfilled with undefined), promise.reject(3).finally(() => {}) will be rejected with 3. note: a throw (or returning a rejected promise) in the finally callback will reject the new promise with the rejection reason specified when calling throw. examples using finally let isloading = true; fetch(myrequest).then(function(response) { var contenttype = response.headers.get("content-type"); if(contenttype && contenttype.includes("application/json")) { return response.json(); } throw new typeerror("oops, we haven't got json!"); }) .then(function(json) { /* process your json further ...
Promise.race() - JavaScript
the source for this interactive demo is stored in a github repository. if you'd like to contribute to the interactive demo project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax promise.race(iterable); parameters iterable an iterable object, such as an array. see iterable. return value a pending promise that asynchronously yields the value of the first promise in the given iterable to fulfill or reject. ...
...nsole.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 it 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 }); specifica...
The "codecs" parameter in common media types - Web media technologies
media file using a simple mime type, such as video/mp4 or audio/mpeg. however, many media types—especially those that support video tracks—can benefit from the ability to more precisely describe the format of the data within them. for instance, just describing a video in an mpeg-4 file with the mime type video/mp4 doesn't say anything about what format the actual media within takes. for that reason, the codecs parameter can be added to the mime type describing media content. with it, container-specific information can be provided. this information may include things like the profile of the video codec, the type used for the audio tracks, and so forth. this guide briefly examines the syntax of the media type codecs parameter and how it's used with the mime type string to provide details abo...
...the mpeg-4 file type. video/quicktime a video file in apple's quicktime format. as noted elsewhere, this format was once commonly used on the web but no longer is, since it required a plugin to use. however, each of these mime types is vague. all of these file types support a variety of codecs, and those codecs may have any number of profiles, levels, and other configuration factors. for this reason, you can add the codecs parameter to the media type. to do so, append a semicolon (;) followed by codecs= and then the string describing the format of the contents of the file. some media types only let you specify the names of the codecs to use, while others allow you to specify various constraints on those codecs as well. you can specify multiple codecs by separating them with commas. audio...
Performance fundamentals - Web Performance
y adding and removing classes on parent elements. if you want to create animations on the fly or modify them in javascript, james long has written a simple library for that called css-animations.js. use css transforms instead of tweaking absolute positioning and fiddling with all that math yourself, use the transform css property to adjust the position, scale, and so forth of your content. the reason is, once again, hardware acceleration. the browser can do these tasks on your gpu, letting the cpu handle other things. in addition, transforms give you capabilities you might not otherwise have. not only can you translate elements in 2d space, but you can transform in three dimensions, skew and rotate, and so forth. paul irish has an in-depth analysis of the benefits of translate() from a perfo...
... on the screen (such as if it's in the background and some other task is operating). this will save battery life and prevent users from cursing your name into the night sky. make events immediate as old-school, accessibility-aware web developers we love click events since they also support keyboard input. on mobile devices, these are too slow. you should use touchstart and touchend instead. the reason is that these don’t have a delay that makes the interaction with the app appear sluggish. if you test for touch support first, you don’t sacrifice accessibility, either. for example, the financial times uses a library called fastclick for that purpose, which is available for you to use. keep your interface simple one big performance issue we found in html5 apps was that moving lots of dom e...
Populating the page: how browsers work - Web Performance
ount of data transmitted until the network's maximum bandwidth can be determined. in tcp slow start, after receipt of the initial packet, the server doubles the size of the next packet to around 28kb. subsequent packets increase in size until a predetermined threshold is reached, or congestion is experienced. if you’ve ever heard of the 14kb rule for initial page load, tcp slow start is the reason why the initial response is 14kb, and why web performance optimization calls for focusing optimizations with this initial 14kb response in mind. tcp slow start gradually builds up transmission speeds appropriate for the network's capabilities to avoid congestion. congestion control as the server sends data in tcp packets, the user's client confirms delivery by returning acknowledgements, or ack...
...roves paint and repaint performance. there are specific properties and elements that instantiate a layer, including <video> and <canvas>, and any element which has the css properties of opacity, a 3d transform, will-change, and a few others. these nodes will be painted onto their own layer, along with their descendants, unless a descendant necessitates its own layer for one (or more) of the above reasons. layers do improve performance, but are expensive when it comes to memory management, so should not be overused as part of web performance optimization strategies. compositing when sections of the document are drawn in different layers, overlapping each other, compositing is necessary to ensure they are drawn to the screen in the right order and the content is rendered correctly. as the page...
<set> - SVG: Scalable Vector Graphics
Web › SVG › Element › set
note: the <set> element is non-additive. the additive and accumulate attributes are not allowed, and will be ignored if specified. ...
... note: the <set> element is non-additive. the additive and accumulate attributes are not allowed, and will be ignored if specified. ...
SVG documentation index - SVG: Scalable Vector Graphics
Web › SVG › Index
r an external css file. most svg you'll find around the web use inline css, but there are advantages and disadvantages associated with each type. 275 filter effects advanced, needscontent, svg, svg:tutorial there are situations, where basic shapes do not provide the flexibility you need to achieve a certain effect. drop shadows, to provide a popular example, cannot be created reasonably with a combination of gradients. filters are svg's mechanism to create sophisticated effects. 276 getting started beginner, needsbeginnerupdate, svg, svg:tutorial let us dive straight in with a simple example. take a look at the following code. 277 gradients in svg intermediate, svg, svg:tutorial perhaps more exciting than just fills and strokes is th...
...tion svg see http://wiki.svg.org/server_configuration 381 sizing svg this page was auto-generated because a user created a sub-page to this page. 382 specification deviations svg there are a few places where we have consciously decided to make gecko deviate from or extend the svg specification. this page lists those deviations/extensions and our reasoning for them. 383 mimetypes.rdf corruption svg this page explains a problem that can cause svg to stop working in mozilla due to the way mozilla maps filename extensions to media types. ...
How to turn off form autocompletion - Web security
additionally, the browser enables the user to choose a master password that the browser will use to encrypt stored login details. even without a master password, in-browser password management is generally seen as a net gain for security. since users do not have to remember passwords that the browser stores for them, they are able to choose stronger passwords than they would otherwise. 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 passwor...
...-password" if you are defining a user management page where a user can specify a new password for another person, and therefore you want to prevent autofilling of password fields, you can use autocomplete="new-password". this is a hint, which browsers are not required to comply with. however modern browsers have stopped autofilling <input> elements with autocomplete="new-password" for this very reason. for example, firefox version 67 (see bug 1119063) stopped autofilling in this case; however, firefox 70 (see bug 1565407) can suggest securely-generated passwords, but does not autofill a saved password. see the autocomplete compat table for more details. ...
2015 MDN Fellowship Program - Archive of obsolete content
onducted at your normal workspace. the fine print mozilla will provide coaching, direction and training on teaching best practices. subject to mozilla’s travel reimbursement policies, mozilla will cover fellows travel, room, per diem food costs and visa costs up to $3,000 to attend the orientation. fellows are responsible for obtaining their own visas if any are required (mozilla will provide reasonable supporting documentation). the fellows will meet the stated deliverables of their projects and meet weekly with their mentor, the program lead and their other fellows. the fellow will also share the results of their projects at 1-2 events agreed upon by the fellow and the program director, as well as on their personal channels (blog, social media, etc). the fellow is responsible for any rela...
Communicating using "postMessage" - Archive of obsolete content
suppose the content script wants to send mouseout events as well as mouseover. now we have to embed the event type in the message payload, and implement a switch function in the receiver to dispatch the message: var pagemodscript = "window.
Content Processes - Archive of obsolete content
e the fact that work on implementing this in firefox has currently been suspended. since both add-on modules and content scripts are currently loaded in sandboxes rather than separate processes, and sandboxes can communicate with each other directly (using imports/exports), you might be wondering why we have to go through all the trouble of passing messages between add-on and content scripts. the reason for this extra complexity is that the code for add-on modules and content scripts have different privileges. every add-on module can get chrome privileges simply by asking for them, whereas content scripts have the same privileges as the page it is running on. when two sandboxes have the same privileges, a wrapper in one sandbox provides transparent access to an object in the other sandbox. when...
Modules - Archive of obsolete content
...
SDK API Lifecycle - Archive of obsolete content
de.js: experimental the module is not yet stabilized. you can try it out and provide feedback, but we may change or remove it in future versions without having to pass through a formal deprecation process. unstable the api is in the process of settling, but has not yet had sufficient real-world testing to be considered stable. backwards-compatibility will be maintained if reasonable. if we do have to make backwards-incompatible changes, we will not guarantee the module will go through the formal deprecation process. stable the module is a fully-supported part of the sdk. we will avoid breaking backwards compatibility unless absolutely necessary. if we do have to make backwards-incompatible changes, we will go through the formal deprecation process. d...
XUL Migration Guide - Archive of obsolete content
ts, which can access web pages, but do not have access to the sdk's apis content scripts and add-on scripts communicate by sending each other json messages: in fact, the ability to communicate with the add-on scripts is the only extra privilege a content script is granted over a normal remote web page script. a xul-based add-on will need to be reorganized to respect this distinction. the main reason for this design is security: it reduces the risk that a malicious web page will be able to access privileged apis. there's much more information on content scripts in the working with content scripts guide. using the supported apis the sdk provides a set of high level apis providing some basic user interface components and functionality commonly required by add-ons. because we expect to keep t...
passwords - Archive of obsolete content
r the credential. usernamefield string the value of the name attribute for the user name input field in a form. passwordfield string the value of the name attribute for the password input field in a form. onerror function the callback function that is called if the function failed. the callback is passed an error containing a reason of a failure: this is an nsiexception object. store(options) this function is used to store a credential in the password manager. it takes an options object as an argument: this contains all the properties for the new credential. as different sorts of credentials contain different properties, the appropriate options differ depending on the sort of credential being stored. to store ...
self - Archive of obsolete content
n be used by internal api code to index local storage and other resources that are associated with a particular add-on. name this property contains the add-on's short name. it comes from the name property in the main package's package.json file. version this property contains the add-on's version string. it comes from the version property set in the package.json file in the main package. loadreason this property contains of the following strings describing the reason your add-on was loaded: install enable startup upgrade downgrade isprivatebrowsingsupported this property indicates whether or not the add-on supports private browsing. it comes from the private-browsing key in the add-on's package.json file. data the data object is used to access data that was bundled with the add-on. t...
ui/button/action - Archive of obsolete content
abel); // access the second tab's label -> "tab-specific label" console.log(button.state(tabs[1]).label); // reset the tab-specific state button.state(tab, null); // access the second tab's label -> "window-specific label" console.log(button.state(tabs[1]).label); } finally, you can pass the button itself into state(). this is an alternative way to set or get the global state. ...
ui/button/toggle - Archive of obsolete content
abel); // access the second tab's label -> "tab-specific label" console.log(button.state(tabs[1]).label); // reset the tab-specific state button.state(tab, null); // access the second tab's label -> "window-specific label" console.log(button.state(tabs[1]).label); } finally, you can pass the button itself into state(). this is an alternative way to set or get the global state. ...
File I/O - Archive of obsolete content
use of os.file is preferred over the examples in this article. only use these legacy interfaces if os.file is not available to you. this article describes local file input/output in chrome javascript. you access the file system using mozilla xpcom components. note: file objects are nsifile. for legacy reasons, there is also an nsilocalfile interface. creating an nsifile object components.utils.import("resource://gre/modules/fileutils.jsm"); var file = new fileutils.file("/home"); or the same without using fileutils.jsm: var file = components.classes["@mozilla.org/file/local;1"]. createinstance(components.interfaces.nsilocalfile); file.initwithpath("/home"); note: the path should be in the "native" form (for example"c:\\windows"). if you need to use file:// ...
Examples and demos from articles - Archive of obsolete content
en appropriate through the cleartimeout() function. a possible approach to solve this problem is to nest all the informations needed by each animation to start, stop, etc. etc. in different objects and then to create a constructor for such class of objects in order to standardize and simplify the instantiation of them. here is a possible and minimalist example of such abstraction, which for this reason we named minidaemon. [article] image preview before upload [html] the filereader.prototype.readasdataurl() method is useful, for example, to get a preview of an image before uploading it. [article] note: the filereader() constructor was not supported by internet explorer for versions before 10. for a full compatibility code, see also our crossbrowser possible solution for image preview. det...
Miscellaneous - Archive of obsolete content
yourmodule(data.installpath.path); // some code ... } ...
Preferences - Archive of obsolete content
at dots in a special way. for example this code will also read the value of accessibility.typeaheadfind.enablesound preference: var prefs = components.classes["@mozilla.org/preferences-service;1"] .getservice(components.interfaces.nsiprefservice); var branch = prefs.getbranch("acce"); var enablesound = branch.getboolpref("ssibility.typeaheadfind.enablesound"); this is the reason why you should usually pass strings ending with a dot to getbranch(), like prefs.getbranch("accessibility."). another caveat you should be aware of is that nsiprefbranch.getchildlist("",{}) returns an array of preference names that start with that branch's root, for example var branch = prefs.getbranch("accessibility."); var children = branch.getchildlist("", {}); will return these items (for...
StringView - Archive of obsolete content
stringview has been proposed as strawman for es2015 on ecmascript bugs. everyone can participate in the discussion at bug 1557 or at esdiscuss. ...
Communication between HTML and your extension - Archive of obsolete content
from the ajax request wasn't fully updated into the html page. what that meant is that everytime the extension went looking for the element, it wasn't there yet. as a last ditch effort i tried setting a timeout using settimeout when i got the event in the extension to wait a few milliseconds before looking for the desired element. this was non-optimal and the timeout wasn't very reliable for some reason. sometimes i would get the timeout, sometimes i would'nt. what i ended up with some helpful information on the irc channel led me to believe that a custom event might help. i started to research custom events on google but everything that i found was far too complicated for what i wanted to achieve. eventually i put the creation of the custom event into the statechanged function that was handling...
Creating custom Firefox extensions with the Mozilla build system - Archive of obsolete content
there is a wealth of material on creating extensions for firefox. all of these documents currently assume, however, that you are developing your extension using xul and javascript only. for complex extensions, it may be necessary to create components in c++ that provide additional functionality. reasons why you might want to include c++ components in your extension include: need for high-performance beyond what can be delivered by javascript code. use of third-party libraries written in c or c++. use of mozilla interfaces that are not exposed via xpcom (e.g. nspr). note: with the modern jit javascript engine in gecko and js-ctypes more extension code can be written only in javascript than ever before. please consider all of your options car...
Enhanced Extension Installation - Archive of obsolete content
graded by xpinstall or dropped into a directory-based install location), the install manifest supplied by the item is expanded into a temporary location and read. the guid and version supplied are validated, and then compatibility is checked for by the new _getinstalldata function. this function returns the guid, version, and type of the item, and also an error code listing either success, or the reason for a failure, such as invalid guid, version, or incompatible item. depending on the failure, the install function may take several steps. if the item is found incompatible, a version update check is performed as before. if updated compatibility information is found this is written into the in-memory representation of the the temporary install manifest and the install function is called recursiv...
Install Manifests - Archive of obsolete content
dates on amo, using the id of the extension. note: it is strongly recommended that the updateurl be an https (secure) link. non-secure update urls can be hijacked by a malicious update.rdf file, enabling malware to infiltrate the user's computer. alternatively, you could host your extension on amo and leave out the updateurl completely. this provides secure updates automatically. for security reasons, gecko 1.9 applications require that if you specify an updateurl, it must be an https url, or you must include an updatekey. your server must send this file as text/rdf, text/xml or application/rdf+xml or the update checker may not work. the add-on manager will substitute the following values into this url in case you wish to generate the response rdf dynamically, such as using php or cgi: ...
Installing Extensions and Themes From Web Pages - Archive of obsolete content
on content handling to invoke the confirmation ui, many sites are (incorrectly) doing so for theme jar files too and wondering why they aren't auto-detected and installed. well, xpi is a mozilla-specific extension and so we can have special handling for it, but jar is not - not all .jar files are firefox themes, so if you click on a .jar link you'll be shown the save as decision dialog. for this reason you should always use the installtrigger api to install themes. a note on updateenabled() installtrigger exposes a function called updateenabled that some of you may be calling before you call installtrigger.install. this is not necessary as install calls updateenabled itself internally. furthermore, calling updateenabled may lead to problems if your distribution site is not in the user's white...
Listening to events in Firefox extensions - Archive of obsolete content
ndlers the pageshoweventhandlers() function is called by the pageshow event and is used to populate the character set menu and update the ui elements associated with any detected feeds or opensearch plugins for the website. xulbrowserwindow xulbrowserwindow is an nsiwebprogresslistener used to get progress events for the currently visible browser. ...
Migrating raw components to add-ons - Archive of obsolete content
components as a by product of their own software installs, though. if you would like to install firefox add-ons in an automated, programmatic way, we have documented a set of best practices. javascript c-types some add-on authors create binary components not because they want to interact with firefox at the c++ level, but strictly so that they can make use of third party dlls. if this is the only reason you are using a binary component instead of javascript, take a look at the new javascript c-types support introduced in firefox 3.6. it allows javascript code to load functions from dlls on windows, and should allow you to eliminate your dependence on binary components entirely. this leads to a better compatibility path as new versions of firefox are released. ...
Appendix: What you should know about open-source software licenses - Archive of obsolete content
by taking advantage of this fact. red hat enterprise linux (rhel) cannot be copied or distributed with the redhat trademark in place. a number of rhel clones have appeared, such as centos, where the trademarked parts have been scrubbed away by a community effort. the firefox web browser, developed by the mozilla foundation, does not permit modifications of its name or trademarked icon. for this reason, the debian project, which distributes free software as a volunteer effort, has a browser based on firefox, but with a different name and logo. document licenses as open-source software grows in popularity, people have begun thinking about applying its principles to content other than software, to allow anyone to duplicate, distribute, and modify it freely. because oss licenses aren’t direct...
Adding Events and Commands - Archive of obsolete content
event) { /* do stuff*/ }, false); be careful when doing this! you should at least validate the url of the page that is generating the custom event, so that you know that it's coming from the right place. you should also avoid this kind of events to trigger actions that could be destructive to the user's data, because a malicious site could try to trigger these events and cause damage. there's a reason for the division between remote content and local chrome, so make sure you respect it. there's a section further ahead on intercepting page loads which complements this section very well. this should give you a solid foundation to handle interaction between web content and xul. additional information on custom events and how they can be used to effect communication between web content and xul c...
Appendix B: Install and Uninstall Scripts - Archive of obsolete content
ithout prior user consent. remember that the user can revert this decision. so, you should listen to other events, like canceling the operation, to make sure that you know what is going on. set a boolean flag that indicates if your add-on is set to be uninstalled or not, and reset it when necessary. the second stage is knowing when the application is actually going to be closed. then you'll have reasonable certainty that the add-on will be removed and you can perform any cleanup operations safely. for this, you need to add an observer for the quit-application topic. this is when you'll know the application will close. then you can check the flag you set up on the first stage and perform any necessary deletions. you shouldn't perform very time-consuming operations here, at least not without tell...
Appendix F: Monitoring DOM changes - Archive of obsolete content
dom mutation events were introduced to html several years ago in order to allow web applications to monitor changes to the dom by other scripts. unfortunately, adding listeners for any of these events to a document has a highly deleterious effect on performance, an effect which is not mitigated in the slightest by later removing those listeners. for this reason, it is best to avoid using mutation listeners at all costs, especially from extensions. this document lays out some alternatives which do not have such severe performance impacts. mutation observers mutation observers are the more efficient, w3c speced replacement for the highly inefficient mutation events. their major advantage is in their performance and their ease of use, especially when combined with simple libraries. their main di...
Appendix E: DOM Building and Insertion (HTML & XUL) - Archive of obsolete content
failure to do so can lead to execution or remote scripts, and in the worst cases to privilege escalation which can leave a user's pc open to remote attack. building dom trees in most cases, dom trees should be built exclusively with dom creation methods. the following methods will all safely create a dom tree without risk of remote execution. ...
Local Storage - Archive of obsolete content
ral you should use logging freely in order to have as much information as possible to fix bugs and know what is going on. don't log inside functions that are called too often, such as mouseover event handlers, or certain http activity listeners. this impacts performance and fills the log with useless messages. we normally add a comment that indicates that logging is not done there for performance reasons. sqlite sqlite storage was introduced in firefox 2, and it's the preferred storage mechanism in firefox. it is the storage system used for the places api that manages bookmarks and history. it's also used for storing cookies, form inputs, and others. sqlite is a lightweight sql based storage system. it is ideal for embedding in other programs, and is currently in use in several popular applic...
Security best practices in extensions - Archive of obsolete content
ing your content there. give the element a type="content" attribute, which essentially sandboxes the code there and blocks callback rights into chrome. using eval() in an extension using the built-in javascript eval function is frowned upon in the context of extensions. while there are some legitimate use-cases, most of the time there are safer alternatives. this blog post offers some excellent reasons not to use eval(). sandboxed http connections the main purpose of sandboxed http connections is to interact with a web service, without interfering with the cookies set in the browser by that service/site. for example, if you are loading pictures or other data from a photo sharing site, you can sandbox your connections to that site so that the normal browsing of that site by the user in the ma...
Underscores in class and ID Names - Archive of obsolete content
ring_length, and a variable representing the number of people who voted republican might be voted_republican. given this fact, authors who write css often attempt to employ the underscore in a similar fashion when creating class and id names. this should not be done. although underscores are, as of this writing, technically permitted in class and id names, there are many historical and practical reasons why they should be avoided. the css1 specification, published in its final form in 1996, did not allow for the use of underscores in class and id names unless they were "escaped." an escaped underscore would look something like this: p.urgent\_note {color: maroon;} this was not well supported by browsers at the time, however, and the practice has never caught on. css2, published in 1998, also...
JXON - Archive of obsolete content
a name like this isn't a good choice, since the text content of a node can be parsed into a non-string value by our algorithms during the conversion). in the algorithms proposed here, you can easily change this name, depending on your needs. ...
Images, Tables, and Mysterious Gaps - Archive of obsolete content
e of these problems, because the best solution for a given document will greatly depend on its structure. if your document uses transitional markup, make sure your doctype reflects that fact and does not trigger "standards" mode. this will prevent browsers from using standards-based rendering, and thus all the image-layout problems are avoided. 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. any image in a table cell with other images should be vertically aligned with the bottom of the line box. any image in a table cell with other images and text should have its vertical alignment changed as necessary, if at all. with ...
No Proxy For configuration - Archive of obsolete content
of sites or domains that was within the intranet, and should not be accessed via the proxy server. due to various limitations, this feature should be used for only the most simple blacklist scenarios. in almost all cases, pac gives better control and flexibility. user interface "no proxy for" is an optional field, part of "manual proxy configuration". the field is relatively short, but can hold reasonably long (2k+ characters) entries. new profiles contain the values "localhost, 127.0.0.1", by default. entry points: preferences | advanced | proxies control-click menu for off line-online icon (network plug) configuration the no proxy list is composed of either domain elements or ipv4 address elements. the elements are separated by either a space (" ") or a comma (","). note for forme...
Kill the XUL.mfl file for good - Archive of obsolete content
e, because each user has his own... loading these files from the server, and storing them back slows down the network, thus it may actually be faster without than with xul.mfl occasionnally gets corrupted, needing a manual intervention to wipe it out, before mozilla again works correctly. with quicklauncer (see above), mozilla's speed is actually quite adequate, even without xul.mfl for these reasons, it is desirable to disable the xul.mfl functionality. unfortunately, there appears to be no "clean" way of doing so (javascript command in prefs.js or registry setting). but creating a subdirectory named xul.mfl in mozilla's profile directory seems to help (mozilla is not smart enough to remove the directory before creating the file, thus the presence of the directory effectively disables this ...
Structure of an installable bundle - Archive of obsolete content
cation-specific /searchplugins/*.src sherlock search plugins firefox 1.5 and greater. /searchplugins/*.xml mozsearch and opensearch plugins firefox 2 and greater /dictionaries/*.{aff|dic} myspell dictionaries firefox 2 and greater of course, an extension need not (and normally won't) have all of these directories. themes are limited for security reasons, and can normally only provide a chrome.manifest which registers the theme and a jar file. platform-specific files gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) removed support for platform-specific subdirectories, described below. instead, you need to use manifest flags, such as the os and abi flags, in your chrome manifest to specify components that should be loaded for specific pl...
Getting Started - Archive of obsolete content
setup download the latest version of mozilla, install it (install the dom inspector as well), and select the classic skin. you can use the same version as the one you use to browse the web, but if you mess it up, it is possible that you will be unable to access your browser without uninstalling and reinstalling mozilla. for this reason we suggest that you install a second copy into a second directory (make sure that you use a different profile as stated in the release notes) extract the chrome the chrome is stored in \mozilla\chrome and the individual modules are stored in jar files. jar files are zip files with a different extension. you can open them up in your zip program the same way you open up zip files. mozilla currently comes with two skins, classic and modern. looking in the directory ...
Repackaging Firefox - Archive of obsolete content
here. and that's all you need! take a moment and browse through the files, and don't forget to check mdc for reference material. locales there is a difference between the locales you plan to distribute installers for (and will therefore need to repack), and the locales supported by your dex. if possible, we recommend you have your dex support the full set of locales that firefox supports. the reason is that if you create and ship a dex that supports 2 locales (for example), and later decide to ship on a 3rd locale, you will need to re-create the dex to support it. that means that you will need to change the version of the dex, and that will cause any users with the earlier version to get unnecessarily upgraded. on the other hand, if you create a dex which supports all locales, you can only ...
Gecko Coding Help Wanted - Archive of obsolete content
ion: decomtamination convert weird, ugly and inefficient method signatures to more natural c++ method signatures. it's really improved code readability, reduced code size, and sped up performance. it's kind of tedious but it's extremely valuable and will help you learn the way around the codebase. we've done a lot, but there's a lot more to do. roc is willing to work closely with anyone with reasonable c++ experience to get them started on this. just send him mail. not up for coding yet? join the gecko bugathon and help save gecko engineers from imminent doom! original document information author(s): fantasai last updated date: may 4, 2004 copyright information: portions of this content are © 1998–2007 by individual mozilla.org contributors; content available under a ...
Creating a Help Content Pack - Archive of obsolete content
entries describe other entries. you can refer to an entry by giving the entry a unique rdf:id attribute. then, to describe that entry, you set an rdf:about attribute to the value of the entry's rdf:id, prefixed by a #. nesting as described above works exactly the same no matter how deeply or shallowly nested your entry is. nesting theoretically can work to any number of levels, but for practical reasons nesting is limited to roughly 20 levels. if you're coming anywhere close to this limit, however, you probably should be considering exactly why you need so much nesting. the table of contents file the table of contents file is the most important data source you'll create. the help viewer will display the table of contents when you start the viewer. in some versions of the viewer, it will be th...
Hidden prefs - Archive of obsolete content
there is ui for the "mail.collect_email_address_outgoing" pref. see "edit | preferences.. | mail & newsgroups | addressing" "other compose header" pref from mailnews.js: // you can specify a comma delimited list of optional headers // this will show up in the address picker in the compose window // examples: "x-face"...
Java in Firefox Extensions - Archive of obsolete content
java.util.linkedlist(); if you want to load your own jars, then you can create your own java class loader. the following technique only works in javascript code linked from or contained in xul files. if you wish to call java code from within javascript code that implements some xpcom components, at this time, you need a different technique (refer to the complete java firefox extension). a good reason for calling java from within an xpcom component rather than from xul is to maintain a singleton (some singular java object) across all firefox windows. if you call java from xul, then each firefox window will have its own class loader and hence its own "singleton". the following approach is taken from the extension xquseme (note you must use the latest version, currently still in the sandbox, as...
Menu - Archive of obsolete content
Archive › Mozilla › Jetpack › UI › Menu
on bar's context menus, but it does on the bookmark toolbar's context menu. to work around this limitation, try using beforeshow and examining the node that the user clicked. for example, to add an item to the tabs' context menu, try: jetpack.menu.context.browser.beforeshow = function (menu, context) { menu.reset(); if (context.node.localname === "tab") menu.add("hey, a tab!"); }; (the reason this problem exists is because document.queryselectorall() does not match anonymous content in xul. many parts of firefox's interface are actually anonymous content. a future version of jetpack will hopefully provide a better solution.) jetpack.menu.context.page the content context menu. this is the context menu that appears when right-clicking on a web page. a contextmenuset object. context ob...
Mozilla Crypto FAQ - Archive of obsolete content
les, mozilla.org cannot guarantee that the format of the key and certificate database will remain unchanged over time; in particular, changes may be introduced at some point that break compatibility with existing applications. also, changing the database directly from an application risks causing database corruption and subsequent problems in psm and applications like mozilla using psm. for these reasons we strongly recommend that mozilla developers and others access the key and certificate database only through public apis provided by the nss library. for more information see the documentation for the cert7.db certificate database. also see the documents "into the black box: a case study in obtaining visibility into commercial software", "netscape certificate database information", and "netsca...
How to Write and Land Nanojit Patches - Archive of obsolete content
ing the development of (firefox 11 / thunderbird 11 / seamonkey 2.8), so this information is relevant to earlier versions of the codebase. adobe and mozilla share a copy of nanojit. this means that landing nanojit patches is a bit complicated, but experience has taught us that this is much better than having separate versions of nanojit. (note: this document is called nanojitmerge for historical reasons -- adobe and mozilla used to have separate copies of nanojit, but this was a maintenance headache so they were merged. the first version of this document was written just after that merge occurred.) resources nanojit development now takes place on a single shared repository nanojit-central. repository: http://hg.mozilla.org/projects/nanojit-central (or clone ssh://hg.mozilla.org/projects/nanoji...
Plug-n-Hack Phase1 - Archive of obsolete content
it is suggested that browsers wishing to support pnh restrict handling of customevents such that they’re ignored where the event happens outside of user initiated actions. 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 addon). configuresectoolfailed - this notifies the document that configuration has failed for some reason. the user should be notified that configuration has failed. configuresectoolsucceed...
RDF Datasource How-To - Archive of obsolete content
p datasource and address book datasource, above, we'd be able to identify the sender of "message 126" as an "important friend". deciding on a vocabulary the vocabulary is the set of properties that you will use to express relationships between elements (resources and literals) in your data model. the first question that you must answer is "should i use an existing vocabulary, or invent my own?" a reasonable answer is, "use an existing vocabulary unless you absolutely must invent your own." this will allow your datasource to be integrated with other datasources with a minimum of effort. there are several existing vocabularies of note, including: the rdf schema specification. this vocabulary is a "meta vocabulary" that is used to specify other vocabularies. the dublin core. this vocabulary is use...
Remote debugging - Archive of obsolete content
per's computer, a last-resort strategy is to debug it on the community member's computer. the crash victim should at least know how to run a debugger, if not how to use it, and should have a debug build of firefox handy. this requires quite a bit of trust, in both directions. the developer trusts that his time is not being wasted: the crash is a real bug in firefox. (that is, there's a legitimate reason it happens only on some computers, but that reason just hasn't been discovered.) the crash victim, in turn, trusts the developer with full access to his computer. a good place to start is a detailed stack (in gdb, use bt followed by bt full). there give more information about the stack than a breakpad crash report: not only the names of the functions on the stack, but also the values they were p...
Running Tamarin acceptance tests - Archive of obsolete content
/tamarin-redux/generated/shell_toplevel.abc $ export avm=/users/build/hg/tamarin-redux/objdir-release/shell/avmshell $ python runtests.py tamarin tests started: 2010-09-28 10:37:06.410676 current configuration: x64-mac-tvm-release avm version: 5260:6d1899261bac executing 2532 tests against vm: /users/build/hg/builds/5260-6d1899261bac/mac/avmshell_64 2532 running abcasm/abs_helper.as skipping... reason: 2531 running abcasm/adhoc.abs skipping... reason: inconsistencies in different debug output, need to implement regex matching of diffs 2527 running abcasm/branchtocommon.abs 2530 running abcasm/arithmetic.abs 2529 running abcasm/bkpt.abs 2528 running abcasm/bkptline.abs 2526 running abcasm/bug_476556.abs 2524 running abcasm/bug_491056.abs ... test run passed! tests complete at 2010-09-28 ...
Tamarin build documentation - Archive of obsolete content
uild system for mozilla developers. the cross-platform build system is used for daily automated build testing so it is the most reliable system. the tamarin codebase has the ability to build additional code which supports debugging hooks. in the xcode project, this is the debug_debugger and release_debugger configurations. the flash player builds tamarin with the debugging hooks off for codesize reasons, but the mozilla client will build tamarin with the debugging hooks on. cross-platform build (general instructions - non-android) prerequisites: you need python 2.5 or later and gnu make 3.81 or later. (gnu make 3.80 does not work. nor does any other brand of make.) with the right prerequisites, use these commands to build tamarin: $ hg clone http://hg.mozilla.org/tamarin-redux/ $ cd tamar...
TraceVis - Archive of obsolete content
is: dist/bin/js -j -t /tmp/tracevis.log myprogram.js the tracevis log file is a binary file consisting of a sequence of 8-byte records. there are two scripts for postprocessing the log files in js/src/tracevis. text summary python binlog.py /tmp/tracevis.log this prints a summary of the log. the first part lists the time tracemonkey spent in each major tracing activity. the second part lists the reasons tracemonkey transitioned to the interpreter, and the amount of interpreter time charged to each reason. visualization python vis.py /tmp/tracevis.log /tmp/tracevis.png this creates a png format visualization of tracemonkey activities. there is a color for each activity. time goes forward down each column of pixels, then to the column on the right. the blog post linked above has examples of this ...
Tuning Pageload - Archive of obsolete content
parser interruption and less responsiveness but lower overall load time. content.notify.* controls the information flow from content sink to rendering model. 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. the reason for this is that nscssframeconstructor is most efficient when doing a bunch of stuff at once instead of constructing rendering objects for one dom node at a time. specifically - content.notify.ontimer controls whether the frame constructor is notified off a timer at all content.notify.backoffcount controls how many times that happens for a given page (the default is arbitrarily many times). once ...
URIs and URLs - Archive of obsolete content
ry and ref. the filename consists of filebasename and fileextension. if the spec is completly broken down, it consists of: scheme, username, password, host, port, directory, filebasename, fileextension, param, query and ref. together these segments form the url spec with the following syntax: scheme://username:password@host:port/directory/filebasename.fileextension;param?query#ref for performance reasons the complete spec is stored in escaped form in the nsstandardurl object with pointers (position and length) to each basic segment and for the more global segments like path and prehost for example. necko provides pre written urlparsers for schemes based on hierachical naming systems. escaping to be able to parse an url safely it is sometimes necessary to "escape" certain characters, to hide the...
XBL 1.0 Reference - Archive of obsolete content
anonymous content and css selectors and scopes binding stylesheets binding implementations introduction methods properties inheritance of implementations event handlers example - sticky notes updated and adjusted for the current firefox implementation. this example is targeted to demonstrate the xbl usage rather than to be a practically useful application. for this reason it contains many comments and some blocks could be avoided in a more compact solution yet used here for demonstration purposes. notes.html notes.xml notes.css view this example download all files (.zip archive) need to ask to adjust the server - it gives "access denied" for zip files (?) references initial xbl 1.0 proposal submitted as a note to w3c (does not reflect mozilla implem...
XML in Mozilla - Archive of obsolete content
we treat xhtml documents differently depending on the mime type (or file suffix if files are loaded from local discs). files that go through the html code path are not checked for well-formedness. you will also notice not all xhtml features are supported when you exercise the html code path. mime type file suffix code path ...
panel.level - Archive of obsolete content
hether the panel appears on top of all windows, or just on top of the window the panel is in. if this attribute is not set, the popup window level depends on the platform. on linux, the default value is top, otherwise, the default value is parent. if a panel has one or more text fields, this attribute should not be set, otherwise ime or on-screen keyboard popups will appear incorrectly. for these reasons, you should avoid setting the level if not needed. top the panel is shown in front of all other normal windows, including those of other applications. parent the panel is shown just above the window the panel is in, but behind other windows above it. if anchored, the child window maintains its relative position to its parent window. floating the panel floats above the window the ...
Moving, Copying and Deleting Files - Archive of obsolete content
ment to modify the filename while moving. this would be used when renaming a file within the same directory. when moving a file within the same directory, the destination argument may be null. for instance, the following example renames a file within the same directory: file.moveto(null, "hello.txt"); if the destination file already exists, nsifile.moveto() replaces the existing file. for this reason, you may wish to check if the file exists using nsifile.exists() before moving the file. deleting a file to delete a file, use nsifile.remove(). this method takes one boolean argument which indicates whether to delete recursively or not. if true and the file object refers to a directory, the directory will be removed as well all files and subdirectories within it. if false, a directory will onl...
Index - Archive of obsolete content
Archive › Mozilla › XUL › Index
any of the most common accessibility mistakes will be found and reported. 1084 xul and rdf this page was auto-generated because a user created a sub-page to this page. 1085 the implementation of the application object model outdated_articles purpose - the purpose of this document is two-fold. the first section of the document describes the motivation and reasoning behind using rdf as the foundation of xul. this section makes a technical argument both for having xul in the first place and for using rdf as the underlying implementation of xul's content model. the second section describes the xul/rdf architecture itself and outlines enhancements to the xul language in order to allow the markup language to reference local data and to indicate how and when i...
OpenClose - Archive of obsolete content
ment with the right mouse button. on macintosh systems with only one mouse button, a context menu may be opened by either holding down the mouse button or by pressing the control key and clicking the mouse button. on windows, the context menu can also be opened by pressing the menu key on the keyboard (the key on many keyboards next to control with a menu image) or by pressing shift+f10. for this reason, you should not assume that a user has used the mouse to open the context menu. the openpopup method regardless of the type of popup, you may wish to open the popup programatically. to do this, use the popup's openpopup method. this method may be used for any type of popup, either a menupopup, a panel, or a tooltip, including ones that can be opened via other means, for instance, a popup attach...
PopupEvents - Archive of obsolete content
pup that they cannot close. you also cannot cancel the hiding of a menupopup when a user has made a selection from a menu, as it is already too late to do so. in this situation the command event has already been sent to the selected menuitem and the operation already carried out. this is one special case in which the popuphiding event is fired after the popup has been removed from the screen. the reason for this is if, as is quite common, the menu item's action is to open a modal dialog. here, the menu would need to be removed first, before the dialog can be opened. otherwise, the user would have a menu for a parent window that is no longer active. so instead, the popup is removed first. note that this means that the popuphiding event doesn't fire until after the modal dialog has been closed. th...
SeaMonkey - making custom toolbar (SM ver. 1.x) - Archive of obsolete content
...
Adding Event Handlers - Archive of obsolete content
l documents. in fact, both html and xul share the same event mechanism. one important difference is that while the 'click' event (or the onclick attribute) is used in html to respond to buttons, in xul the command event should be used instead. xul does have a click event, but it only responds to mouse clicks, not to keyboard usage. thus, the click event should be avoided in xul, unless you have a reason to have an element that can only be handled with a mouse. in addition, whereas the command event will not be sent if an element is disabled, the click event will be sent regardless of whether the element is disabled or not. our find files example a command handler can be placed on the find and cancel buttons in the find files dialog. pressing the find button should start the search. because we...
Adding Event Handlers to XBL-defined Elements - Archive of obsolete content
me"> <handlers> <handler event="event-name" action="script"/> </handlers> </binding> place all of your handlers within the handlers element. each handler element defines the action taken for a particular event specified by its event attribute. valid event types are those supported by xul and javascript, such as click and focus. use the event name without the 'on' in front of it. a common reason to set handlers is to modify the custom properties when an event occurs. for example, a custom checkbox might have a checked property which needs to be changed when the user clicks the checkbox: <handlers> <handler event="mouseup" action="this.checked=!this.checked"/> </handlers> when the user clicks and releases the mouse button over the check box, the mouseup event is sent to it, and the han...
Adding Style Sheets - Archive of obsolete content
elements look more suitable. changing the styles however, there will be times when the default look of elements will not give the look that is desired. for this, we will need to add a style sheet of our own. so far, we have been applying styles using the style attribute on elements. although this works, it is not really the best thing to do. it is much better to create a separate style sheet. the reason is so that different looks, or skins, can be applied easily. there may be certain cases where the style attribute is acceptable. an example would be when a script changes the style, or where a difference in layout might change the meaning of the element. however you should avoid this as much as possible. for installed files, you'll have to create or modify a manifest file and install the skin. ou...
Additional Install Features - Archive of obsolete content
call the file.copy function which copies the source file to the destination. functions also exist to move(), rename() and execute() files. thus, you can move files that might conflict with your package out of the way. handling errors you will likely want to handle errors gracefully. this will occur if a file or directory cannot be found, there is insufficient disk space or for a number of other reasons. you can use the getlasterror() function to determine whether an error occured. if it returns success, no error occured. otherwise, the number will be an error code which indicates the type of error that occured. you can call this function at any point during the installation script to determine whether an error occured during the last operation. if an error occurs, you will likely want to abort...
Broadcasters and Observers - Archive of obsolete content
which has the id isoffline, which is the one defined earlier. if the value of the label attribute on the broadcaster changes, the observers will update the values of their label attributes also. we could continue with additional elements. as many elements as you want can observe a single broadcaster. you can also have only one if you wanted to but that would accomplish very little since the main reason for using broadcasters is to have attributes forwarded to multiple places. you should only use broadcasters when you need multiple elements that observe an attribute. below, some additional observers are defined: <broadcaster id="offline_command" label="offline" accesskey="f"/> <keyset> <key id="goonline_key" observes="offline_command" modifiers="accel" key="o"/> </keyset> <menuitem id="offli...
Creating a Skin - Archive of obsolete content
to-diagnose bugs. use at your own risk! this section describes how to create a simple skin. for simplicity, we'll only apply it to the find files dialog. a simple skin the image below shows the current find files dialog. let's create a skin that we can apply to it. normally, a skin would apply to the entire application, but we'll focus on just the find files dialog to make it easier. for this reason, we'll modify only the file findfile.css rather than the global.css file. this section assumes that you are starting with the classic skin. you may wish to make a copy of the files used by the find files dialog before editing. you need to create a file 'findfile.css' in a custom skin. or, you can temporarily place it in the content directory and refer to it using a stylesheet directive. you ca...
Document Object Model - Archive of obsolete content
hown below. an oncommand handler will also be added to the find button. <script src="findfile.js"/> . . . <button id="find-button" label="find" oncommand="dofind();"/> now, create another file called findfile.js in the same directory as findfile.xul. we'll add the dofind() function is this file. the script tag does allow code to be contained directly inside of it. however, for various reasons, including better performance, you should always put scripts in separate files, except for short fragments which can be put directly in the event handler. function dofind(){ var meter = document.getelementbyid('progmeter'); meter.hidden = false; } this function first gets a reference to the progress meter using its id, progmeter. the second line of the function body changes the hidden sta...
Install Scripts - Archive of obsolete content
note: for firefox extensions, install.js are no longer used. you should create a install.rdf instead. you will usually want some form of control over your install process. for example, you may wish to check versions of files and only install updated files, or perhaps you wish to apply patches to existing files. the install script is even flexible enough to allow you to uninstall files. for this reason, installers include an install script to handle the installation process. the installer script must be called install.js and must be placed at the top level of the installer archive. the script will contain javascript code which calls a number of install functions. in an html document, or a xul document, the window object is the root global object. that means that you can call the methods of the ...
Manifest Files - Archive of obsolete content
m any site, other sites are not configured to allow installations by default. it is also possible to use a install script written in javascript to install files. this allows you to copy files to any location and perform other file management tasks. however, applications installed with a script will not be listed in the extension manager and there is no automated method to uninstall them. for this reason, the install scripts are not used often. for standalone applications, they can be packaged up using xulrunner. this allows a separate executable file, and the application may be distributed independently of a browser. for more information about creating extensions, see extensions. for more information about xulrunner, see xulrunner. older applications if you are creating applications for older ve...
Manipulating Lists - Archive of obsolete content
he items that are selected, while the selectedcount property holds the number of items selected. typically, you will use these properties to iterate over the list and perform some operation for each item. be careful when iterating over the selected items; if you modify the items in the list while iterating, the list will change and the selection properties may return different values. this is one reason why it is useful to manipulate the list by the item rather than by index. deleting selected items the following example shows a method of deleting the selected items properly: example 4 : source view <script> function deleteselection(){ var list = document.getelementbyid('thelist'); var count = list.selectedcount; while (count--){ var item = list.selecteditems[0]; list.removeite...
Skinning XUL Files by Hand - Archive of obsolete content
n the global skin of an application, since these are the styles that give an application a certain overall look, or skin. note that for any one class of element, there may be several pseudo-classes andattribute selector styles defined. when you declare a button in your xul to be of a particular class, you take advantage of all of the styles defined for the various states of that button. for this reason, it can be very efficient to use button classes that appear in the global skin and to make new classes only when necessary. browse through the global skin to familiarize yourself with what's there. in the next few sections, you will be importing this style information into a custom stylesheet and extending it with new style rules for your xul. loading stylesheets in xul for your custom skin, l...
Templates - Archive of obsolete content
bookmarks datasource so it can be used to get the data. this example will only get the top-level bookmarks (or bookmark folders) as we're going to create buttons. for child bookmarks, we would need to use an element that displays a hierarchy such as a tree or menu. this example and any others that reference internal rdf datasources will only work if you load them from a chrome url. for security reasons, mozilla doesn't allow access to them from other sources. to view this example, you will need to create a chrome package and load the file from there (you can do this easily, see manifest files). you can then enter the chrome url into the browser url field. example 1 : source <vbox datasources="rdf:bookmarks" ref="nc:bookmarksroot" flex="1"> <template> <button uri="rdf:*" label="rdf:ht...
Updating Commands - Archive of obsolete content
then be reused for all commands. in fact, this is common enough that mozilla includes a library which does just that. if you include the script 'chrome://global/content/globaloverlay.js' in a xul file, you can call the godocommand method which executes the command passed as the argument. the code for this function is only a few lines long so you could include it directly in your code if for some reason you didn't want to include the library. <script src="chrome://global/content/globaloverlay.js"/> <command id="cmd_paste" oncommand="godocommand('cmd_paste');"/> <button label="paste" command="cmd_paste"/> the example above will implement a paste button. it is attached to the command which will invoke the command on the necessary controller when called. the code above is all you need to implemen...
Using Spacers - Archive of obsolete content
nd button grow in size but some space has appeared between the main label and the button. of course, this is the spacer that we put in earlier. it has resized itself also. if you look closely enough, you should notice that the change in size has been divided up equally between the spacer and the button. the spacer has received half of the free space and the button has received the other half. the reason we're seeing this effect is that both the spacer and the find button have a flex attribute. because both are flexible, both the button and the spacer resize equally. what if you want to set one element to grow twice as large an another? you can use a higher number as the value of the flex attribute. the values of the flex element are a ratio. if one element has a flex of 1 and the next one has a ...
XPCOM Interfaces - Archive of obsolete content
se the interface nsisupports is implemented by all components, the function queryinterface() function is available in every component. several components may implement the same interface. typically, they might be subclasses of the original but not necessarily. any component may implement the functionality of nsilocalfile. in addition, a component may implement several interfaces. it is for these reasons that two steps are involved in getting an interface to call functions through. however, there is a shortcut we can use because we'll often use both of these lines together: var alocalfile = components.classes["@mozilla.org/file/local;1"].createinstance(components.interfaces.nsilocalfile); this will do the same thing as the two lines but in one line of code. it eliminates the need to create t...
XUL Structure - Archive of obsolete content
such as overlays. since xul and html are handled in the same way, you can load both from either your local file system, from a web page, or from an extension or standalone xulrunner application. content from remote sources (e.g. http://localhost/~username/ ), regardless of whether they are html or xul or another document type, are limited in the type of operations they can perform, for security reasons. for this reason, mozilla provides a method of installing content locally and registering the installed files as part of its chrome system. this allows a special url form, called a chrome:// url, to be used. by accessing a file using a chrome url, the files receive elevated privileges to access local files, access preferences and bookmarks and perform other privileged operations. obviously, web ...
Using Remote XUL - Archive of obsolete content
t" element in html. the url we use, chrome://global/skin/, is a reference to the default application stylesheet (a.k.a. skin). if we were to switch the browser to a different skin, the style of our menus would also change. if we want our site to have the same look no matter what skin the user is using, we would need to write our own stylesheet to style the elements. in case you're wondering, the reason the buttons and menu items had style before we added the stylesheet reference is that some xul elements are defined in mozilla using another xml-based language called xbl which provides building blocks for creating ui widgets. xbl files sometimes contain references to the default application stylesheet, and when they do their widgets inherit that style even if we don't specify a stylesheet. you c...
XUL Questions and Answers - Archive of obsolete content
a scheme is in development to allow servers to open up their site for cross-site access, but that's not yet done. hidechrome="true" doesn’t work on a mac? unfortunately, no simple solution to this was posted. a workaround is to open the content in a new window using "window.open"...
XUL and RDF - Archive of obsolete content
this section makes a technical argument both for having xul in the first place and for using rdf as the underlying implementation of xul's content model. ...
XUL Coding Style Guidelines - Archive of obsolete content
erred to our notes as "localization note". files not to be localized? some files live in the tree but aren't really part of the build; they're just there as programming examples or a kind of source documentation. to prevent them from being localized, you may insert a line of comment following the xml declaration as follows. <?xml version="1.0" encoding='utf-8'?> <!-- do not localize this file: [reason...] it isn't part of the build; --> when translators see this line, they won't bother to look at the rest of the file. references xul is discussed in depth in xul language spec and xul window language. xul localizability issues xhtml 1.1 recommendation namespaces in xml extensible markup language (xml) 1.0 euro sign the unicode standard®, version 2.1 "xml applications" by frank boumphrey. pub...
panel - Archive of obsolete content
Archive › Mozilla › XUL › panel
hether the panel appears on top of all windows, or just on top of the window the panel is in. if this attribute is not set, the popup window level depends on the platform. on linux, the default value is top, otherwise, the default value is parent. if a panel has one or more text fields, this attribute should not be set, otherwise ime or on-screen keyboard popups will appear incorrectly. for these reasons, you should avoid setting the level if not needed. top the panel is shown in front of all other normal windows, including those of other applications. parent the panel is shown just above the window the panel is in, but behind other windows above it. if anchored, the child window maintains its relative position to its parent window. floating the panel floats above the window the ...
Application Update - Archive of obsolete content
.silent", false); // update service url: // you do not need to use all the %var% parameters. use what you need, %product%,%version%,%build_id%,%channel% for example pref("app.update.url", "https://yourserver.net/update/3/%product%/%version%/%build_id%/%build_target%/%locale%/%channel%/%os_version%/%distribution%/%distribution_version%/update.xml"); // url user can browse to manually if for some reason all update installation // attempts fail. pref("app.update.url.manual", "http://yourserver.net/yourpage"); // a default value for the "more information about this update" link // supplied in the "an update is available" page of the update wizard. pref("app.update.url.details", "http://yourserver.net/yourpage"); // user-settable override to app.update.url for testing purposes. //pref("app.update...
Creating XULRunner Apps with the Mozilla Build System - Archive of obsolete content
in most cases, developers of xulrunner applications can download an existing sdk and follow the instructions in getting started with xulrunner. this is by far the simplest approach. in some cases, however, you may want to use the mozilla build system to create your application. the only obvious reason for this would be if you need to implement part of your application in c++, as described in the introduction to the now classic creating custom firefox extensions with the mozilla build system. for the purposes of this article i'm using dave townsend's mccoy as an example. it's a straightforward xulrunner app that nonetheless uses most of the features any given application is likely to need. building xulrunner do i need to build xulrunner? if you are just creating a xulrunner app with some c++ com...
Getting started with XULRunner - Archive of obsolete content
wget -o- $xurl | tar -xj" sudo ln -s /opt/xulrunner/xulrunner /usr/bin/xulrunner sudo ln -s /opt/xulrunner/xpcshell /usr/bin/xpcshell you could also save this script to a file for convenience. note: if you are using firefox build from ubuntuzilla repository, replace /usr/lib/firefox/platform.ini with /opt/firefox/platform.ini. step 2: install xulrunner on windows, unzip the archive someplace reasonable. i unzipped it to a new c:\program files\xulrunner folder. on the mac, extract the tar.bz2 archive, which contains xulrunner as xul.framework. copy this to the /library/frameworks directory, or another location of your choice. on linux, you only need to unpack the archive if you are using a pre-release xulrunner. in all systems you should unzip the omni.ja file into some example director...
Gecko Compatibility Handbook - Archive of obsolete content
can cause problems with gecko-based browsers, especially in image maps. you should make sure that your name attributes are coded using valid characters only. bad code due to old apis and tools problem: obsolete apis or web authoring tools generate non-standard code. many older versions of cross-browser apis in common use around the web such as dynapi do not support gecko for one or more of the reasons listed above. this is also the case for older versions of web authoring tools such as macromedia's dreamweaver 2 and 3. newer versions of these apis and tools do support gecko however. for example, dynapi is now maintained at sourceforge and offers a gecko-compatible version. newer versions of web authoring tools support gecko. wrong doctype problem: an incorrect doctype can completely alter ...
2006-10-20 - Archive of obsolete content
and asks him to confirm the intention of his post. j. paul reed also questions why gtk1 is still being built since it is know to be unsupported on trunk. on october 20th boris zbarsky responded to j. paul reed previous post: boris zbarsky answered j. paul reed's question that was posted in his previous reply. j. paul reed had asked "why gtk1 was still being built". boris zbarsky's said: the reason why gtk1 builds are still being performed is because: when requests are made to change build boxes to newer versions the people responsible for making the change reply with "that would require an os upgrade". on october 20th j. paul reed responded to boris zbarsky's post: j. paul reed restates his overall goal that are "getting us to not rely on hardware that you have to have in a certain p...
2006-10-20 - Archive of obsolete content
available for download. completed rc3 testing key testing activities for ff2 rc3 are done. discussions sparky and comet going away on friday preed wants to get rid of sparky and comet (both older desktop class linux boxes). robert kaiser gave some background on the boxes. decommissioning sparky on friday preed wants to get rid of sparky (a linux build box) and wants to know if there are reasons wy not to do it. feature brainstorming + firefox 3 dria posted a link to the firefox feature brainstorming list (open to everyone). discussion of what is the best format for the list and how to use it best. meetings bon echo status meeting bon echo status meeting: october 17th, 2006 **at noon pdt**. meeting notes gecko status meeting october 19 (*thursday*) gecko 1.9 status meeting. ag...
2006-11-03 - Archive of obsolete content
d validation certificates major discussion this week started by gervase markham about security certificates, more specifically extended validation certificates. the aim of the group is to develop a new, higher standard for the validation which is done before certificate issuance, called extended validation. the idea was that such certs would be presented differently in the ui, to give the cas a reason to go to the extra effort, and to give customers a reason to buy them. in ie 7 at least, the use of an ev certificate is tied to the green background in the url bar. a decision has to be made as to the usefulness of extended validation certificates and weather or not they will make a difference to the reliability of information in certificates. if it does make a difference, does it warrant a di...
NPN_DestroyStream - Archive of obsolete content
« gecko plugin api reference « plug-in side plug-in api summary closes and deletes a stream. syntax #include <npapi.h> nperror npn_destroystream(npp instance, npstream* stream, nperror reason); parameters the function has the following parameters: instance pointer to current plug-in instance. stream pointer to current stream, initiated by either the browser or the plug-in. reason reason the stream was stopped so the application can give the user appropriate feedback. values: npres_done (most common): stream completed normally; all data was sent by the plug-in to the browser. npres_user_break: plug-in is terminating the stream due to a user request. npres_network_err: stream failed due t...
NPN_PostURL - Archive of obsolete content
sturlnotify. 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. if no custom headers are required, simply add a blank line ('\n') to the beginning of the file or buffer. npn_posturl is typically asynchronous: it returns immediately and only later handles the request. for this reason, you may find it useful to call npn_posturlnotify instead; this function notifies your plug-in upon successful or unsuccessful completion of the request. see also npn_geturl, npn_geturlnotify, npn_posturlnotify, npp ...
NPP_DestroyStream - Archive of obsolete content
« gecko plugin api reference « plug-in side plug-in api summary tells the plug-in that a stream is about to be closed or destroyed. syntax #include <npapi.h> nperror npp_destroystream(npp instance, npstream* stream, npreason reason); parameters the function has the following parameters: instance pointer to current plug-in instance. stream pointer to current stream. reason reason the stream was destroyed. values: npres_done (most common): completed normally; all data was sent to the instance. npres_user_break: user canceled stream directly by clicking the stop button or indirectly by some action such as deleting the instance or initiating higher-priority network operations. npres_network_err: stream fail...
NPP_HandleEvent - Archive of obsolete content
the browser window, to draw into. the plug-in has complete control over drawing and event handling within that window. mac os the browser does not give a windowed plug-in a native window, because the mac os platform does not support child windows. instead, the windowed plug-in draws into the graphics port associated with the the browser window, at the offset that the browser specifies. for this reason, npp_handleevent is only way the plug-in can receive events from its host application on mac os. when npp_handleevent is called, the current port is set up so that its origin matches the top-left corner of the plug-in. a plug-in does not need to set up the current port for mouse coordinate translation. see also npevent ...
NPSavedData - Archive of obsolete content
is deleted; can be returned to the plug-in to restore the data in future instances of the plug-in. syntax typedef struct _npsaveddata { int32 len; void* buf; } npsaveddata; fields the data structure has the following fields: len length in bytes of the buffer pointed to by buf; set by the plug-in. buf pointer to a memory buffer allocated by the plug-in with npn_memalloc(). can be any reasonable size; its contents are private to the plug-in and are not modified by the browser. description the npsaveddata object contains a block of per-instance information that the browser saves after the instance is deleted. this information can be returned to another instance of the same plug-in if the user returns to the web page that contains it. you can use the plug-in's npp_destroy() function t...
XEmbed Extension for Mozilla Plugins - Archive of obsolete content
you use the xid that was passed into your npp_setwindow() call and create a gtkplug to host inside of that socket. since the gtkplug is just a container, you can add your own widgets at your leisure with the packing you prefer. telling mozilla you support xembed as mentioned above, you will need to tell mozilla that you support the xembed protocol for hosting plugins. for backwards compatibility reasons if you don't tell mozilla that you support it it will try to hand you an xt widget as a parent. however, before you do so you should make sure that the browser also supports xembed when the plugin is first initialized. if you've built your plugin so that it will support either xt or xembed you can include a fallback for older style hosting. if you haven't you can return an error and the plugin w...
Why RSS Content Module is Popular - Including HTML Contents - Archive of obsolete content
this element is used to include an html <description>. note: strictly speaking, the rss content module and <content:encoded> are not quite being used correctly. it requires intertwinment with rdf's xml serialization. but this is how it has become common practice to use it. ...
Why RSS Slash is Popular - Counting Your Comments - Archive of obsolete content
this element gives the (current) total number of comments made for the item -- for the blog post. although not necessary, people also often use other rss modules to get at (and read) the comments (since rss does not currently provide facilities for this either). some use the well-formed web rss module for this. and some are now using atomic rss for this. (usi...
Why Well-Formed Web RSS Module is Popular - Syndicating Your Comments - Archive of obsolete content
this element lets you syndicate your comments. the uri in the <wfw:commentrss> element must point to an rss feed containing the comments for the <item> it is contained in. ...
Security Controls - Archive of obsolete content
problem with security controls is that they often make systems less convenient or more difficult to use. when usability is an issue, many users will attempt to circumvent security controls; for example, if passwords must be long and complex, users may write them down. balancing security, functionality, and usability is often a challenge. the goal should be to strike a proper balance: provide a reasonably secure solution while offering the functionality and usability that users require. another fundamental principle with security controls is using multiple layers of security—defense in depth. for example, sensitive data on a server may be protected from external attack by several controls, including a network-based firewall, a host-based firewall, and os patching. the motivation for havin...
Introduction to Public-Key Cryptography - Archive of obsolete content
n what the user has (the private key) as well as what the user knows (the password that protects the private key). however, it's important to note that these two assumptions are true only if unauthorized personnel have not gained access to the user's machine or password, the password for the client software's private key database has been set, and the software is set up to request the password at reasonable frequent intervals. neither password-based authentication nor certificate-based authentication address security issues related to physical access to individual machines or passwords. public-key cryptography can only verify that a private key used to sign some data corresponds to the public key in a certificate. it is the user's responsibility to protect a machine's physical security and to k...
Table Reflow Internals - Archive of obsolete content
aints, its rows and cells, and the actual heights of its rows and cells from the pass 2 reflow. if the table has a style height, it allocates extra height to its row groups, rows and cells. in each pass, row groups reflow rows which reflow cells which reflow cell blocks. ...
Tamarin Tracing Build Documentation - Archive of obsolete content
build system for mozilla developers. the cross-platform build system is used for daily automated build testing so it is the most reliable system. the tamarin codebase has the ability to build additional code which supports debugging hooks. in the xcode project, this is the debug_debugger and release_debugger configurations. the flash player builds tamarin with the debugging hooks off for codesize reasons, but the mozilla client will build tamarin with the debugging hooks on. cross-platform build first, you must have the mozilla build prerequisites for your platform. additionally, you need python 2.4 or later and gnu make 3.81 or later. (gnu make 3.80 does not work. nor does any other brand of make.) with the right prerequisites, use these commands to build tamarin tracing: $ hg clone http://hg.
-ms-ime-align - Archive of obsolete content
the -ms-ime-align css property is a microsoft extension aligning the input method editor (ime) candidate window box relative to the element on which the ime composition is active. the extension is implemented in microsoft edge and internet explorer 11. ime candidate lists are positioned on the screen with sufficient size to allow basic text input. in some cases, the ime may enforce a reasonable minimum size. in the case of -ms-ime-align: after, an ime might adjust the candidate window and keyboard input behavior to provide a better user experience, such as using a horizontal candidate list and allowing some keys to be sent to the app for suggestion list navigation. initial valueautoapplies toall elementsinheritednocomputed valueas specifiedanimation typediscrete syntax /* keyword valu...
Object.prototype.unwatch() - Archive of obsolete content
. syntax obj.unwatch(prop) parameters prop the name of a property of the object to stop watching. return value undefined. description the javascript debugger has functionality similar to that provided by this method, as well as other debugging options. for information on the debugger, see venkman. by default, this method is inherited by every object descended from object. note: the reason for unwatch() to take the property name prop as its only parameter is due to the "single handler allowing" behavior of the watch() method. examples see watch(). specifications not part of any standard. ...
Window.importDialog() - Archive of obsolete content
e large incompatibilities between implementations and the behavior may change in the future. obsoletethis feature is obsolete. although it may still work in some browsers, its use is discouraged since it could be removed at any time. try to avoid using it. this function was only available in the original, xul-based version of firefox for android, which is no longer supported; for that reason, this function is obsolete and should never be used. summary because opening windows on mobile isn't necessarily appropriate, the firefox mobile team designed the importdialog() method to replace window.opendialog(). instead of opening a new window, it merges the specified xul dialog into the main window. syntax newdialog = importdialog(aparent, asrc, aarguments) newdialog the opened wi...
Implementation Status - Archive of obsolete content
11. xforms submission model section title status notes bugs 11.1 submission partial from 1.1 we do not yet support @mode, @indent, @replace='text', @separator, @serialize, @target, header or method child elements 11.2 xforms-submit partial we currently limit (for security reasons) submission only back to the server that served the document. but the user can choose to remove this restriction on a site by site basis via a preference. click for more details. 330557; 11.3 xforms-submit-serialize supported 11.4 xforms-submit-done supported 11.5 xforms-submit-err...
Mozilla XForms Specials - Archive of obsolete content
nd to a boolean node we support an attribute labelposition in the namespace http://www.mozilla.org/projects/xfor...009/extensions, which allows the form author to define on which side of the checkbox the label will be shown. for details, see the input control documentation. misc cross domain submission not exactly either a limitation, or an extension, but it is worth mentioning here. for security reasons, it is not per default possible for an xforms to submit data to another domain. this is due to security reasons. information about how to whitelist domain can be found in the release notes the cross domain check also includes forms loaded from file://. forms loaded from that url should be local files, and thus trusted, but it is not always the case. so there is not automatic "whitelisting" of l...
RFE to the Custom Controls - Archive of obsolete content
xul, in many cases, is much better suited for application development than xhtml. therefore the control set may need to be more extensive to address the wider spectrum of requirements that a xul application will have on its controls. ...
Requests For Enhancement - Archive of obsolete content
Archive › Web › XForms › RFE
tions in our interfaces or the functionality of our controls, then this is the right place to pass along your requirements. custom controls if you have a custom control that you believe will help fulfill the needs of form authors or other custom controls authors, please file it here. this section could be of particular interest to people using custom controls in xul documents for the following reasons: xul, in many cases, is much better suited for application development than xhtml. therefore the control set may need to be more extensive to address the wider spectrum of requirements that a xul application will have on its controls. xul is a feature of mozilla only and custom control authors should be aware their controls won't work on other browser platforms. enhancements of xforms eleme...
Mozilla XForms User Interface - Archive of obsolete content
to a xsd:string type or a xsd:date type. when a xf:output binds to a node that has a type of xsd:date, we output the date value as plain text. an output bound to a date and also having @appearance='full' will display as a calendar. this article uses several notations. if you see fx 3.0 only, that means that the control will only be available for firefox 3.0 (gecko 1.9). there are several possible reasons for this restriction. the first is that the changes required for such controls could not be safely made to firefox 1.5 or firefox 2.0. the second is that the control is introduced in xforms 1.1 and we don't feel adding the enhancement would be prudent until the 1.1 spec is more stable. for instance, when the spec reaches 'recommendation'-level status. if you see xhtml/xul then it means the contr...
RDF in Fifty Words or Less - Archive of obsolete content
ou organize your bookmarks hierarchically intofolders. each bookmark is apointer to a web page called a uri (uniform resource identifier). but a web page is just one kind of internet resource. there are tons of others, including email messages, usenet news articles (or entire usenet news groups), and search results from your favorite web crawler, just to name a few. and fundamentally, there's no reason that you shouldn't be able to treat these as "bookmarks" as well, grouping them together into folders as you please, or maybe even creating "smart" folders that, when you open them, dynamically generate their contents by running common search that you define. and a "bookmark" could really have arbitrary properties associated with it: you might want to invent your own "classification" scheme for ...
Using the Right Markup to Invoke Plugins - Archive of obsolete content
you can invoke the java plugin for netscape 7 and other mozilla-based browsers by using the appropriate java mime type. here is an example: <object type="application/x-java-applet;jpi-version=1.4.1_01" width="460" height="160"> <par...
Windows Media in Netscape - Archive of obsolete content
exobject(clid); } catch(e) { ; } return player; } // instantiate players wmp7or9 = creategeckowmpobject("{6bf52a52-394a-11d3-b153-00c04f79faa6}"); if (!wmp7or9) { wmp64 = creategeckowmpobject("{22d6f312-b0f6-11d0-94ab-0080c74c7e95}"); } ..... note that the classids must be passed in curly braces "{}". the name geckoactivexobject rather than activexobject was introduced for two reasons: geckoactivexobject is limited to creating instances of windows media player activex controls. it therefore can not be used everywhere activexobject is used. activexobject is used by many web developers to detect the presence of internet explorer in much the same fashion as document.all is used. for example if (window.activexobject) { // internet explorer only script } server-side det...
Obsolete: XPCOM-based scripting for NPAPI plugins - Archive of obsolete content
te. this article was written on august 31, 2001; it is not compatible with current versions of firefox. this article applies to mozilla versions 0.9.2 and higher and netscape versions 6.1 and higher. it does not cover netscape 6 and 6.01 introduction plugins that used to take advantage of being scriptable via liveconnect in 4.x netscape browsers lost this possibility in the new world. the main reason for this is that there is no guarantee of java compatibility on a binary level due to the jri/jni switch. the new mozilla xpcom architecture allows xpcom components be scriptable via a different mechanism called xpconnect. we leverage some of these ideas to help you make your netscape communicator 4.x plugins exposed to javascript in mozilla based browsers. in order to make it still possible to s...
3D collision detection - Game development
h 2d collision detection, axis-aligned bounding boxes (aabb) are the quickest algorithm to determine whether the two game entities are overlapping or not. this consists of wrapping game entities in a non-rotated (thus axis-aligned) box and checking the positions of these boxes in the 3d coordinate space to see if they are overlapping. the axis-aligned constraint is there because of performance reasons. the overlapping area between two non-rotated boxes can be checked with logical comparisons alone, whereas rotated boxes require additional trigonometric operations, which are slower to calculate. if you have entities that will be rotating, you can either modify the dimensions of the bounding box so it still wraps the object, or opt to use another bounding geometry type, such as spheres (which a...
CDN - MDN Web Docs Glossary: Definitions of Web-related terms
these servers store duplicate copies of data so that servers can fulfill data requests based on which servers are closest to the respective end-users. cdns make for fast service less affected by high traffic. cdns are used widely for delivering stylesheets and javascript files (static assets) of libraries like bootstrap, jquery etc. using cdn for those library files is preferable for a number of reasons: serving libraries' static assets over cdn lowers the request burden on an organization's own servers. most cdns have servers all over the globe, so cdn servers may be geographically nearer to your users than your own servers. geographical distance affects latency proportionally. cdns are already configured with proper cache settings. using a cdn saves further configuration for static asset...
First interactive - MDN Web Docs Glossary: Definitions of Web-related terms
first interactive, also known as first cpu idle, is a non-standard web performance metric that measures when the user's window is quiet enough to handle user input, or what is termed as minimally interactive. minimally interactive is defined as when some, but not necessarily all, ui elements on the page have loaded and are interactive, and, on average, respond to user input in a reasonable amount of time. more information first interactive is a variation of time to interactive, which is split into first interactive and consistently interactive. these metrics have been proposed by the web incubator community group and are already being used in various tools. this metric has been called first cpu idle since lighthouse 3.0 ...
High-level programming language - MDN Web Docs Glossary: Definitions of Web-related terms
unlike low-level programming languages, it may use natural language elements, or may automate (or even entirely hide) significant areas of computing systems, making the process of developing simpler and more understandable relative to a lower-level language. the amount of abstraction provided defines how "high-level" a programming language is. ...
IDL - MDN Web Docs Glossary: Definitions of Web-related terms
er types such as unsigned long, urls, booleans, etc. unfortunately, there are no clear rules and the way idl attributes behave in conjunction with their corresponding content attributes depends on the attribute. most of the time, it will follow the rules laid out in the specification, but sometimes it doesn't. html specifications try to make this as developer-friendly as possible, but for various reasons (mostly historical), some attributes behave oddly (select.size, for example) and you should read the specifications to understand how exactly they behave. learn more general knowledge idl on wikipedia html attribute reference technical reference interface definition language ...
IPv6 - MDN Web Docs Glossary: Definitions of Web-related terms
ipv6 is the current version of the communication protocol underlying the internet. slowly ipv6 is replacing ipv4, among other reasons because ipv6 allows for many different ip addresses. learn more general knowledge ipv6 on wikipedia ...
Immutable - MDN Web Docs Glossary: Definitions of Web-related terms
an immutable object is one whose content cannot be changed. ...
VoIP - MDN Web Docs Glossary: Definitions of Web-related terms
voip (voice over internet protocol) is a technology used to transmit voice messages over ip (internet protocol) networks. common voip packages include skype, msn messenger, yahoo and many more. everything transferrred through voip is digital. it is also known as ip telephony, or broadband telephony. the main reason for using voip technology is because of cost. voip allows you to make a call directly from a computer, a special voip phone, or a traditional phone connected to a special adapter. a high speed internet connection is required for voip. usually, telephone calls over the internet do not incur further charges beyond what the user is paying for internet access, much in the same way that the user doesn't pay for sending individual emails over the internet. learn more general know...
Modularity - MDN Web Docs Glossary: Definitions of Web-related terms
the term modularity refers to the degree to which a system's components may be separated and recombined, it is also division of a software package into logical units. the advantage of a modular system is that one can reason the parts independently learn more modularity on wikipedia ...
Mobile accessibility - Learn web development
ccessed, to avoid confusion with navigating it. click here for a good hamburger menu example. user input on mobile devices, inputting data tends to be more annoying for users than the equivalent experience on desktop computers. it is more convenient to type text into form inputs using a desktop or laptop keyboard than a touchscreen virtual keyboard or a tiny mobile physical keyboard. for this reason, it is worth trying to minimize the amount of typing needed. as an example, instead of getting users to fill out their job title each time using a regular text input, you could instead offer a <select> menu containing the most common options (which also helps with consistency in data entry), and offer an "other" option that displays a text field to type any outliers into. you can see a simple exa...
Accessible multimedia - Learn web development
buttons. before moving onto creating our button functionality, let's remove the native controls so they don't get in the way of our custom controls. add the following, again at the bottom of your javascript: player.removeattribute('controls'); doing it this way round rather than just not including the controls attribute in the first place has the advantage that if our javascript fails for any reason, the user still has some controls available. wiring up our buttons first, let's set up the play/pause button. we can get this to toggle between play and pause with a simple conditional function, like the following. add it to your code, at the bottom: playpausebtn.onclick = function() { if(player.paused) { player.play(); playpausebtn.textcontent = 'pause'; } else { player.pause(...
WAI-ARIA basics - Learn web development
ome improvements: the search form is called out as a separate item, both when browsing through the page, and in the landmarks menu. the label text contained in the aria-label attribute is read out when the form input is highlighted. beyond this, the site is more likely to be accessible to users of older browsers such as ie8; it is worth including aria roles for that purpose. and if for some reason your site is built using just <div>s, you should definitely include the aria roles to provide these much needed semantics! the improved semantics of the search form have shown what is made possible when aria goes beyond the semantics available in html5. you'll see a lot more about these semantics and the power of aria properties/attributes below, especially in the accessibility of non-semantic c...
A cool-looking box - Learn web development
tyle> element in the head of the document. note: if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page. project brief your task is to create a cool, fancy box and explore the fun we can have with css. general tasks apply the css to the html. styling the box we'd like you to style the provided <p>, giving it the following: a reasonable width for a large button, say around 200 pixels. a reasonable height for a large button, centering the text vertically in the process. centered text. a slight increase in font size, to around 17-18 pixel computed style. use rems. write a comment about how you worked out the value. a base color for the design. give the box this color as its background color. the same color for the text; m...
Cascade and inheritance - Learn web development
larations in user style sheets (custom styles set by a user). normal declarations in author style sheets (these are the styles set by us, the web developers). important declarations in author style sheets important declarations in user style sheets it makes sense for web developers' stylesheets to override user stylesheets, so the design can be kept as intended, but sometimes users have good reasons to override web developer styles, as mentioned above — this can be achieved by using !important in their rules. test your skills! we have covered a lot in this article, but can you remember the most important information? you can find some further tests to verify that you've retained this information before you move on — see test your skills: the cascade. what's next if you understood mo...
Handling different text directions - Learn web development
e and direction of text can change, newer css layout methods do not refer to left and right, and top and bottom. instead they will talk about start and end along with this idea of inline and block. don't worry too much about that right now, but keep these ideas in mind as you start to look at layout; you will find it really helpful in your understanding of css. logical properties and values the reason to talk about writing modes and direction at this point in your learning however, is because of the fact we have already looked at a lot of properties which are tied to the physical dimensions of the screen, and make most sense when in a horizontal writing mode. let's take a look at our two boxes again — one with a horizontal-tb writing mode and one with vertical-rl. i have given both of these...
The box model - Learn web development
rds the actual size of the box — sure, it affects the total space that the box will take up on the page, but only the space outside the box. the box's area stops at the border — it does not extend into the margin. the alternative css box model you might think it is rather inconvenient to have to add up the border and padding to get the real size of the box, and you would be right! for this reason, css had an alternative box model introduced some time after the standard box model. using this model, any width is the width of the visible box on the page, therefore the content area width is that width minus the width for the padding and border. the same css as used above would give the below result (width = 350px, height = 150px). by default, browsers use the standard box model. if you wan...
Supporting older browsers - Learn web development
can help you understand the ie version of the grid, and we have included some additional useful links at the end of this lesson. however, unless you have a very high number of visitors in older ie versions, you may find it better to focus on creating a fallback that works for all non-supporting browsers. testing older browsers with the majority of browsers supporting flexbox and grid, it can be reasonably hard to test older browsers. one way is to use an online testing tool such as sauce labs, as detailed in the cross browser testing module. you can also download and install virtual machines, and run older versions of browsers in a contained environment on your own computer. having access to older versions of internet explorer is particularly useful, and for that purpose, microsoft has made a...
What is CSS? - Learn web development
sers have implemented it. this means that the code has been written to turn the instruction in our css file into something that can be output to the screen. we'll look at this process more in the lesson how css works. it is unusual for all browsers to implement a feature at the same time, and so there is usually a gap where you can use some part of css in some browsers and not in others. for this reason, being able to check implementation status is useful. on each property page on mdn you can see the status of the property you are interested in, so you can tell if you will be able to use it on a website. what follows is the compat data chart for the css font-family property. desktopmobilechromeedgefirefoxinternet exploreroperasafariandroid webviewchrome for androidfirefox for androidopera for ...
Styling lists - Learn web development
list-style-position: inside; } could be replaced by this: ul { list-style: square url(example.png) inside; } the values can be listed in any order, and you can use one, two or all three (the default values used for the properties that are not included are disc, none, and outside). if both a type and an image are specified, the type is used as a fallback if the image can't be loaded for some reason. controlling list counting sometimes you might want to count differently on an ordered list — e.g. starting from a number other than 1, or counting backwards, or counting in steps of more than 1. html and css have some tools to help you here. start the start attribute allows you to start the list counting from a number other than 1. the following example: <ol start="4"> <li>toast pita, l...
What do common web layouts contain? - Learn web development
you start out with a blank page, and you can take it so many directions. ...
How can we design for all types of users? - Learn web development
captions in your video to cater to visitors who can't hear the audio. some users have hearing challenges, lack functioning speakers, or work in a noisy environment (like on the train). transcript subtitles only work if somebody watches the video. many users don't have time, or lack the proper plugin or codec. additionally, search engines rely mainly on text to index your contents. for all these reasons, please provide a text transcript of the video/audio file. image compression some users may choose to display images, but still have limited bandwidth available, especially in developing countries and on mobile devices. if you want a successful website, please compress your images. there are various tools to help you, either online or local: installed software. imageoptim (mac), optipng (a...
How do I start to design my website? - Learn web development
ou have a prioritized list of goals, let's move on to the next question. how could a website bring me to my goals? so you have a list of goals and you feel you need a website to reach those goals. are you sure? let's look back at our example. we have five goals connected to music, one goal related to personal life (finding your significant other), and the completely unrelated cat photos. is it reasonable to build a single website to cover all those goals? is it even necessary? after all, scores of existing web services might bring you to your goals without building a new website. finding a girl/boyfriend is a prime case where it makes more sense to use existing resources rather than build a whole new site. why? because we'll spend more time building and maintaining the website rather than ac...
What is a web server? - Learn web development
erver is typically more available. (up and running) excusing downtime and systems troubles, a dedicated web server is always connected to the internet. a dedicated web server can have the same ip address all the time. this is known as a dedicated ip address. (not all isps provide a fixed ip address for home lines) a dedicated web server is typically maintained by a third-party. for all these reasons, finding a good hosting provider is a key part of building your website. examine the various services companies offer. choose one that fits your needs and budget. (services range from free to thousands of dollars per month.) you can find more details in this article. once you have web hosting service, you must upload your files to your web server. communicating through http second, a web serv...
How do you set up a local testing server? - Learn web development
he file on your local hard drive, a local file is being used. in contrast, if you view one of our examples hosted on github (or an example on some other remote server), the web address will start with http:// or https://, to show that the file has been received via http. the problem with testing local files some examples won't run if you open them as local files. this can be due to a variety of reasons, the most likely being: they feature asynchronous requests. some browsers (including chrome) will not run async requests (see fetching data from the server) if you just run the example from a local file. this is because of security restrictions (for more on web security, read website security). they feature a server-side language. server-side languages (such as php or python) require a speci...
Advanced form styling - Learn web development
pecial attention given to accessibility). twitter bootstrap can help normalize your forms. webshim is a huge tool that can help you deal with browser html5 support. the web forms part can be really helpful. remember that css and javascript can have side effects. so if you choose to use one of those libraries, you should always have robust fallback html in case the script fails. there are many reasons why scripts may fail, especially in the mobile world, and you need to design your web site or app to handle these cases as well as possible. test your skills! you've reached the end of this article, but can you remember the most important information? you can find some further tests to verify that you've retained this information before you move on — see test your skills: advanced styling. b...
The HTML5 input types - Learn web development
s — notably, touch devices with dynamic keyboards like smart phones — a different virtual keypad might be presented that is more suitable for entering email addresses, including the @ key. see the firefox for android keyboard screenshot below for an example: note: you can find examples of the basic text input types at basic input examples (see the source code also). this is another good reason for using these newer input types — improving the user experience for users of these devices. client-side validation as you can see above, email, along with other newer input types, provides built-in client-side error validation — performed by the browser before the data gets sent to the server. it is a helpful aid to guide users to fill out a form accurately, and it can save time — it is...
HTML forms in legacy browsers - Learn web development
ing using @supports: @supports (appearance: none) { input[type="search"] { appearance: none; /* restyle the search input */ } theappearance property can be used to display an element using platform-native styling, or, as is done with the value of none, remove default platform-native based styling. unobtrusive javascript one of the biggest problems is the availability of apis. for that reason, it's considered best practice to work with "unobtrusive" javascript. it's a development pattern that defines two requirements: a strict separation between structure and behaviors. if the code breaks, the content and the basic functionalities must remain accessible and usable. the principles of unobtrusive javascript (originally written by peter-paul koch for dev.opera.com) describes these ...
Other form controls - Learn web development
fferent nesting level) so they are less likely to be confused for actual options. if an <option> element has an explicit value attribute set on it, that value is sent when the form is submitted with that option selected. if the value attribute is omitted, as with the examples above, the content of the <option> element is used as the value. so value attributes are not needed, but you might find a reason to want to send a shortened or different value to the server than what is visually shown in the select box. for example: <select id="simple" name="simple"> <option value="banana">big, beautiful yellow banana</option> <option value="cherry">succulent, juicy cherry</option> <option value="lemon">sharp, powerful lemon</option> </select> by default, the height of the select box is enough to ...
CSS property compatibility table for form controls - Learn web development
ing compatibility tables try to summarize the state of css support for html forms. due to the complexity of css and html forms, these tables can't be considered a perfect reference. however, they will give you good insight into what can and can't be done, which will help you learn how to do things. how to read the tables values for each property, there are four possible values: yes there's reasonably consistent support for the property across browsers. you may still face strange side effects in certain edge cases. partial while the property works, you may frequently face strange side effects or inconsistencies. you should probably avoid these properties unless you master those side effects first. no the property simply doesn't work or is so inconsistent that it's not reliable. n.a. ...
Sending form data - Learn web development
orm: open the developer tools. 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. the only thing displayed to the user is the url called. as we mentioned above, with a get request the user will see the data in their url bar, but with a post request they won't. this can be very important for two reasons: if you need to send a password (or any other sensitive piece of data), never use the get method or you risk displaying it in the url bar, which would be very insecure. if you need to send a large amount of data, the post method is preferred because some browsers limit the sizes of urls. in addition, many servers limit the length of urls they accept. on the server side: retrieving the data...
Styling web forms - Learn web development
s, with our above style rule applied. the defaults differed in a number of ways. inheriting should change their fonts to that of the parent's font family — in this case the default serif font of the parent container. they all do, with a strange exception — <input type="submit"> does not inherit from the parent paragraph in chrome. rather, it uses the font-family: system-ui. this is another reason to use <button> elements over their equivalent input types! there's a lot of debate as to whether forms look better using the system default styles, or customized styles designed to match your content. this decision is yours to make, as the designer of your site, or web application. box sizing all text fields have complete support for every property related to the css box model, such as width,...
Test your skills: Advanced styling - Learn web development
the finished example: download the starting point for this task to work in your own editor or in an online editor. advanced form styling 2 in our next task we provide you with a set of three radio buttons. we want you to give them custom styling. we've already provided you with a basic reset to build upon. first of all, get rid of their default styling. next, give the radio buttons a reasonable base style — the style they have when the page first loads. this can be anything you like, but you probably want to set a width and height (of somewhere between about 18 and 24 pixels), and a subtle border and/or background color. now give the radio buttons a different style for when they are selected. align the radio buttons nicely with the labels. try updating the live code below to r...
UI pseudo-classes - Learn web development
r showing (i.e. the contents of the placeholder attribute) because the value of the element is empty. the following are also interesting, but as yet not well-supported in browsers: the :blank pseudo-class selects empty form controls. :empty also matches elements that have no children, like <input>, but it is more general — it also matches other empty elements like <br> and <hr>. :empty has reasonable browser support; the :blank pseudo-class's specification is not yet finished, so it not yet supported in any browser. the :user-invalid pseudo-class, when supported, will be similar to :invalid, but with better user experience. if the value is valid when the input receives focus, the element may match :invalid as the user enters data if the value is temporarily invalid, but will only match :...
Your first form - Learn web development
lues: submit, reset, or button. a click on a submit button (the default value) sends the form's data to the web page defined by the action attribute of the <form> element. a click on a reset button resets all the form widgets to their default value immediately. from a ux point of view, this is considered bad practice, so you should avoid using this type of button unless you really have a good reason to include one. a click on a button button does... nothing! that sounds silly, but it's amazingly useful for building custom buttons — you can define their chosen functionality with javascript. note: you can also use the <input> element with the corresponding type to produce a button, for example <input type="submit">. the main advantage of the <button> element is that the <input> element o...
Web forms — Working with user data - Learn web development
this module provides a series of articles that will help you master the essentials of web forms. web forms are a very powerful tool for interacting with users — most commonly they are used for collecting data from users, or allowing them to control a user interface. however, for historical and technical reasons it's not always obvious how to use them to their full potential. in the articles listed below, we'll cover all the essential aspects of web forms including marking up their html structure, styling form controls, validating form data, and submitting data to the server. looking to become a front-end web developer? we have put together a course that includes all the essential information you need to work towards your goal. get started prerequisites before starting this module, you...
Dealing with files - Learn web development
s in your filenames with "%20" (the character code for spaces in uris), resulting in all your links being broken. it's better to separate words with dashes, rather than underscores: my-file.html vs. my_file.html. the short answer is that you should use a hyphen for your file names. the google search engine treats a hyphen as a word separator but does not regard an underscore that way. for these reasons, it is best to get into the habit of writing your folder and file names lowercase with no spaces and with words separated by dashes, at least until you know what you're doing. that way you'll bump into fewer problems later down the road. what structure should your website have? next, let's look at what structure our test site should have. the most common things we'll have on any website projec...
Add a hitmap on top of an image - Learn web development
<a>, the entire image links to one webpage. an image map, on the other hand, contains several active regions (called "hotspots") that each link to a different resource. formerly, image maps were a popular navigation device, but it’s important to thoroughly consider their performance and accessibility ramifications. text links (perhaps styled with css) are preferable to image maps for several reasons: text links are lightweight, maintainable, often more seo-friendly, and support accessibility needs (e.g., screen readers, text-only browsers, translation services). how to insert an image map, properly step 1: the image not just any image is acceptable. the image must make it clear what happens when people follow image links. alt text is mandatory, of course, but many people never see it.
Use HTML to solve common problems - Learn web development
Learn › HTML › Howto
sage across best in your document. how to create a list of items with html how to stress or emphasize content how to indicate that text is important how to display computer code with html how to annotate images and graphics how to mark abbreviations and make them understandable how to add quotations and citations to web pages how to define terms with html hyperlinks one of the main reasons for html is making navigation easy with hyperlinks, which can be used in many different ways: how to create a hyperlink how to create a table of contents with html images & multimedia how to add images to a webpage how to add video content to a webpage scripting & styling html only sets up document structure. to solve presentation issues, use css, or use scripting to make your page ...
Advanced text formatting - Learn web development
o get the browser to display the contents of cite, without writing your own solution using javascript or css. if you want to make the source of the quotation available on the page you need to make it available in the text via a link or some other appropriate way. there is a <cite> element, but this is meant to contain the title of the resource being quoted, e.g. the name of the book. ...
Adding vector graphics to the Web - Learn web development
me in the browser. svg can be harder to create than raster images, depending on what kind of image you are trying to create. svg is not supported in older browsers, so may not be suitable if you need to support older versions of internet explorer with your web site (svg started being supported as of ie9.) raster graphics are arguably better for complex precision images such as photos, for the reasons described above. note: in inkscape, save your files as plain svg to save space. also, please refer to this article describing how to prepare svgs for the web. adding svg to your pages in this section we'll go through the different ways in which you can add svg vector graphics to your web pages. the quick way: <img> to embed an svg via an <img> element, you just need to reference it in the...
Images in HTML - Learn web development
the head and torso of a dinosaur skeleton; it has a large head with long sharp teeth"> the easiest way to test your alt text is to purposely misspell your filename. if for example our image name was spelled dinosooooor.jpg, the browser wouldn't display the image, and would display the alt text instead: so, why would you ever see or need alt text? it can come in handy for a number of reasons: the user is visually impaired, and is using a screen reader to read the web out to them. in fact, having alt text available to describe images is useful to most users. as described above, the spelling of the file or path name might be wrong. the browser doesn't support the image type. some people still use text-only browsers, such as lynx, which displays the alt text of images. you may wa...
From object to iframe — other embedding technologies - Learn web development
java applets and flash, pdf (which can be shown in a browser with a pdf plugin), and even content like videos, svg and images! note: a plugin, in this context, refers to software that provides access to content the browser cannot read natively. however, you are unlikely to use these elements very much — applets haven't been used for years, flash is no longer very popular, due to a number of reasons (see the case against plugins, below), pdfs tend to be better linked to than embedded, and other content such as images and video have much better, easier elements to handle those. plugins and these embedding methods are really a legacy technology, and we are mainly mentioning them in case you come across them in certain circumstances like intranets, or enterprise projects. if you find yourself...
Video and audio content - Learn web development
they're based upon. in the united states, patents covered mp3 until 2017, and h.264 is encumbered by patents through at least 2027. because of those patents, browsers that wish to implement support for those codecs must pay typically enormous license fees. in addition, some people simply prefer to avoid restricted software and prefer to use only open formats. due to these legal and preferential reasons, web developers find themselves having to support multiple formats to capture their entire audience. the codecs described in the previous section exist to compress video and audio into manageable files, since raw audio and video are both exceedingly large. each web browser supports an assortment of codecs, like vorbis or h.264, which are used to convert the compressed audio and video into bina...
Multimedia and Embedding - Learn web development
use html to include multimedia in your web pages, including the different ways that images can be included, and how to embed video, audio, and even entire webpages. looking to become a front-end web developer? we have put together a course that includes all the essential information you need to work towards your goal. get started prerequisites before starting this module, you should have a reasonable understanding of the basics of html, as previously covered in introduction to html. if you've not worked through this module (or something similar), work through it first, then come back! note: if you are working on a computer/tablet/other device where you don't have the ability to create your own files, you could try out (most of) the code examples in an online coding program such as jsbin...
HTML table basics - Learn web development
Learn › HTML › Tables › Basics
w to contain the footer, etc. you can find more details and an example at page layouts in our accessibility learning module. this was commonly used because css support across browsers used to be terrible; table layouts are much less common nowadays, but you might still see them in some corners of the web. in short, using tables for layout rather than css layout techniques is a bad idea. the main reasons are as follows: layout tables reduce accessibility for visually impaired users: screenreaders, used by blind people, interpret the tags that exist in an html page and read out the contents to the user. because tables are not the right tool for layout, and the markup is more complex than with css layout techniques, the screenreaders' output will be confusing to their users. tables produce tag...
Choosing the right approach - Learn web development
previous overview: asynchronous to finish this module off, we'll provide a brief discussion of the different coding techniques and features we've discussed throughout, looking at which one you should use when, with recommendations and reminders of common pitfalls where appropriate. we'll probably add to this resource as time goes on. prerequisites: basic computer literacy, a reasonable understanding of javascript fundamentals. objective: to be able to make a sound choice of when to use different asynchronous programming techniques. 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 ...
General asynchronous programming concepts - Learn web development
overview: asynchronous next in this article, we'll run through a number of important concepts relating to asynchronous programming, and how this looks in web browsers and javascript. you should understand these concepts before working through the other articles in the module. prerequisites: basic computer literacy, a reasonable understanding of javascript fundamentals. objective: to understand the basic concepts behind asynchronous programming, and how they manifest in web browsers and javascript. asynchronous? normally, a given program's code runs straight along, with only one thing happening at once. if a function relies on the result of another function, it has to wait for the other function to finish and return, and until that happens, the ent...
Functions — reusable blocks of code - Learn web development
variables and other things defined inside the function are inside their own separate scope, meaning that they are locked away in their own separate compartments, unreachable from code outside the functions. the top level outside all your functions is called the global scope. values defined in the global scope are accessible from everywhere in the code. javascript is set up like this for various reasons — but mainly because of security and organization. sometimes you don't want variables to be accessible from everywhere in the code — external scripts that you call in from elsewhere could start to mess with your code and cause problems because they happen to be using the same variable names as other parts of the code, causing conflicts. this might be done maliciously, or just by accident. f...
Making decisions in your code — conditionals - Learn web development
y not what we want! to make this work you've got to specify a complete test either side of each or operator: if (x === 5 || x === 7 || x === 10 ||x === 20) { // run my code } switch statements if...else statements do the job of enabling conditional code well, but they are not without their downsides. they are mainly good for cases where you've got a couple of choices, and each one requires a reasonable amount of code to be run, and/or the conditions are complex (for example, multiple logical operators). for cases where you just want to set a variable to a certain choice of value or print out a particular statement depending on a condition, the syntax can be a bit cumbersome, especially if you've got a large number of choices. in such a case, switch statements are your friend — they take ...
Client-side storage - Learn web development
rea/javascript/apis/client-side-storage/cache-sw/video-store-offline/sw.js. the origin is https://mdn.github.io, and therefore the given path has to be /learning-area/javascript/apis/client-side-storage/cache-sw/video-store-offline/sw.js. if you wanted to host this example on your own server, you'd have to change this accordingly. this is rather confusing, but it has to work this way for security reasons. installing the service worker the next time any page under the service worker's control is accessed (e.g. when the example is reloaded), the service worker is installed against that page, meaning that it will start controlling it. when this occurs, an install event is fired against the service worker; you can write code inside the service worker itself that will respond to the installation. ...
Fetching data from the server - Learn web development
hen() onto the end of our first one, the success function that contains the json returned from the response.json() promise. we set this to be the value of the products variable, then run initialize(products), which starts the process of displaying all the products in the user interface. to handle errors, we chain a .catch() block onto the end of the chain. this runs if the promise fails for some reason. inside it, we include a function that is passed as a parameter, an error object. this error object can be used to report the nature of the error that has occurred, in this case we do it with a simple console.log(). however, a complete website would handle this error more gracefully by displaying a message on the user's screen and perhaps offering options to remedy the situation, but we don't ne...
Arrays - Learn web development
px; background-color: #f5f9fa; } active learning: top 5 searches a good use for array methods like push() and pop() is when you are maintaining a record of currently active items in a web app. in an animated scene for example, you might have an array of objects representing the background graphics currently displayed, and you might only want 50 displayed at once, for performance or clutter reasons. as new objects are created and added to the array, older ones can be deleted from the array to maintain the desired number. in this example we're going to show a much simpler use — here we're giving you a fake search site, with a search box. the idea is that when terms are entered in the search box, the top 5 previous search terms are displayed in the list. when the number of terms goes over...
Useful string methods - Learn web development
ew that you'll potentially use quite often that we'll look at here. let's enter some examples into the browser developer console. finding the length of a string this is easy — you simply use the length property. try entering the following lines: let browsertype = 'mozilla'; browsertype.length; this should return the number 7, because "mozilla" is 7 characters long. this is useful for many reasons; for example, you might want to find the lengths of a series of names so you can display them in order of length, or let a user know that a username they have entered into a form field is too long if it is over a certain length. retrieving a specific string character on a related note, you can return any character inside a string by using square bracket notation — this means you include squa...
Inheritance in JavaScript - Learn web development
tion. specialized objects delegate functionality to a generic object type. when using inheritance, you are advised to not have too many levels of inheritance, and to keep careful track of where you define your methods and properties. it is possible to start writing code that temporarily modifies the prototypes of built-in browser objects, but you should not do this unless you have a really good reason. too much inheritance can lead to endless confusion, and endless pain when you try to debug such code. ultimately, objects are just another form of code reuse, like functions or loops, with their own specific roles and advantages. if you find yourself creating a bunch of related variables and functions and want to track them all together and package them neatly, an object is a good idea. objects...
Working with JSON - Learn web development
s superpowers. we want the third one, so we use [2]. note: we've made the json seen above available inside a variable in our jsontest.html example (see the source code). try loading this up and then accessing data inside the variable via your browser's javascript console. arrays as json above we mentioned that json text basically looks like a javascript object, and this is mostly right. ...
Object-oriented JavaScript for beginners - Learn web development
namespace — when you access their properties and methods, you have to start calls with person1 or person2; the functionality contained within is neatly packaged away so it won't clash with other functionality. they do, however, have the same name property and greeting() method available. note that they are using their own name value that was assigned to them when they were created; this is one reason why it is very important to use this, so each one uses its own value, and not some other value. let's look at the constructor calls again: let person1 = new person('bob'); let person2 = new person('sarah'); in each case, the new keyword is used to tell the browser we want to create a new object instance, followed by the function name with its required parameters contained in parentheses, and t...
Object prototypes - Learn web development
constructor('karen', 'stephenson', 26, 'female', ['playing drums', 'mountain climbing']); now try accessing your new object's features, for example: person3.name.first person3.age person3.bio() this works well. you won't need to use it often, but it can be really useful when you want to create a new instance and don't have a reference to the original constructor easily available for some reason. the constructor property has other uses. for example, if you have an object instance and you want to return the name of the constructor it is an instance of, you can use the following: instancename.constructor.name try this, for example: person1.constructor.name note: the value of constructor.name can change (due to prototypical inheritance, binding, preprocessors, transpilers, etc.). the...
CSS performance optimization - Learn web development
the browser can paint the page once it has downloaded the css and built the css object model. browsers follow a specific rendering path: paint only occurs after layout, which occurs after the render tree is created, which in turn requires both the dom and the cssom trees. ...
Multimedia: Images - Learn web development
xample use case for priority hints on images are carousels where the first image is a higher priority than the subsequent images. rendering strategy as images are loaded asynchronously and continue to load after the first paint, if their dimensions aren't defined before load, they can cause reflows to the page content. for example, when text gets pushed down the page by images loading. for this reason, it's critical that you set width and height attributes so that the browser can reserve space for them in the layout. for any background images, it's important you set a background-color value so any content overlaid is still readable before the image has downloaded. conclusion in this section we took a look at image optimization. you now have a general understanding of how to optimize half of...
Web performance resources - Learn web development
below is a quick review of best practices, tools, apis with links to provide more information about each topic. best practices start with learning the critical rendering path of the browser. knowing this will help you understand how to improve the performance of the site. using resource hints such as rel=preconnect, rel=dns-prefetch, rel=prefetch, and rel=preload keep the size of javascript to a minimum. only use as much javascript as needed for the current page. css performance factors use http/2 on your server (or cdn). use a cdn for resources which can reduce load times significantly. compress your resources using gzip, brotli, and zopfli. ...
Multimedia: video - Learn web development
type='video/webm; codecs="vp8, vorbis"'> <source src="web_banner.mp4" type="video/mp4"> </video> this hero-video code (above) is common to conference websites and corporate home pages. it includes a video that is auto-playing, looping, and muted. there are no controls, so there is no way to hear audio. the audio is often empty, but still present, and still using bandwidth. there is no reason to serve audio with video that is always muted. removing audio can save 20% of the bandwidth. depending on your choice of software, you might be able to remove audio during export and compression. if not, a free utility called ffmpeg can do it for you. this is the ffmpeg command string to remove audio: ffmpeg -i original.mp4 -an -c:v copy audiofreeversion.mp4 video preload the preload attri...
Introduction to the server side - Learn web development
t returns the same hard-coded content from the server whenever a particular resource is requested). when a user wants to navigate to a page, the browser sends an http "get" request specifying its url. the server retrieves the requested document from its file system and returns an http response containing the document and a success status (usually 200 ok). if the file cannot be retrieved for some reason, an error status is returned (see client error responses and server error responses). dynamic sites a dynamic website is one where some of the response content is generated dynamically, only when needed. on a dynamic website html pages are normally created by inserting data from a database into placeholders in html templates (this is a much more efficient way of storing large amounts of conte...
Getting started with Ember - Learn web development
p: npm install --save-dev todomvc-app-css todomvc-common next, find the ember-cli-build.js file inside the todomvc directory (it's right there inside the root) and open it in your chosen code editor. ember-cli-build.js is responsible for configuring details about how your project is built — including bundling all your files together, asset minification, and creating sourcemaps — with reasonable defaults, so you don't typically need to worry about this file. we will however add lines to the ember-cli-build.js file to import our shared css files, so that they become part of our build without having to explicitly @import them into the app.css file (this would require url rewrites at build time and therefore be less efficient and more complicated to set up). in ember-cli-build.
Ember resources and troubleshooting - Learn web development
ecisions, and allows for more consistent code, while keeping the template more structural rather than having them filled with bespoke logic. see also: reactiveconf 2017: secrets of the glimmer vm what is the state of the mut helper? mut was not covered in this tutorial and is really baggage from a transitional time when ember was moving from two-way bound data to the more common and easier-to-reason-about one-way bound data flow. it could be thought of as a build-time transform that wraps its argument with a setter function. more concretely, using mut allows for template-only settings functions to be declared: <checkbox @value={{this.somedata}} @ontoggle={{fn (mut this.somedata) (not this.somedata)}} /> whereas, without mut, a component class would be needed: import component from '@...
Ember app structure and componentization - Learn web development
this is because the default css absolutely positions the checkbox + label with negative top and left values to m...
Framework main features - Learn web development
icle would need to import authorcredit. import authorcredit from "./components/authorcredit"; once that’s done, authorcredit could be used inside the article component like this: ... <authorcredit /> ... dependency injection real-world applications can often involve component structures with multiple levels of nesting. an authorcredit component nested many levels deep might, for some reason, need data from the very root level of our application. let's say that the magazine site we're building is structured like this: <app> <home> <article> <authorcredit {/* props */} /> </article> </home> </app> our app component has data that our authorcredit component needs. we could rewrite home and article so that they know to pass props down, but this could get tedious if t...
Beginning our React todo list - Learn web development
summary now our todo list app actually looks a bit more like a real app! the problem is: it doesn’t actually do anything. we’ll start fixing that in the next chapter! previous overview: client-side javascript frameworks next in this module introduction to client-side frameworks framework main features react getting started with react beginning our react ...
Starting our Svelte Todo list app - Learn web development
// let rollup handle all other warnings normally handler(warning); } }), ... ] by design, these warnings are implemented in the compiler itself, and not as a plug-in that you may choose to add to your project. the idea is to check for a11y issues in your markup by default and let you opt-out of specific warnings. note: you should only disable these warnings if you have good reasons to do so, for example while building a quick prototype. it's important to be a good web citizen and make make your pages accessible to the broadest possible userbase. the accessibility rules checked by svelte are taken from eslint-plugin-jsx-a11y, a plugin for eslint that provides static checks for many accessibility rules on jsx elements. svelte aims to implement all of them in its compiler, ...
TypeScript support in Svelte - Learn web development
rk in progress to support typescript in svelte projects in several code editors; the most complete support so far is available in the svelte for vs code extension, which is developed and maintained by the svelte team. this extension offers type checking, inspecting, refactoring, intellisense, hover-information, auto-completion, and other features. this kind of developer assistance is another good reason to start using typescript in your projects. note: make sure you are using svelte for vs code and not the old "svelte" by james birtles, which has been discontinued. in case you have it installed, you should uninstall it and install the official svelte extension instead. anyway, assuming you are inside the vs code application, from the root of your project's folder, type code . (the trailing d...
Creating our first Vue component - Learn web development
e in the app are we recording whether a todo item is actually done. to achieve this, we want to bind the component's done prop to the checked attribute on the <input> element, so that it can serve as a record of whether the checkbox is checked or not. however, it's important that props serve as one-way data binding — a component should never alter the value of its own props. there are a lot of reasons for this. in part, components editing props can make debugging a challenge. if a value is passed to multiple children, it could be hard to track where the changes to that value were coming from. in addition, changing props can cause components to re-render. so mutating props in a component would trigger the component to rerender, which may in-turn trigger the mutation again. to work around this...
Getting started with Vue - Learn web development
if you choose a router, you will also have a views directory). .vue files (single file components) like in many front-end frameworks, components are a central part of building apps in vue. these components let you break a large application into discrete building blocks that can be created and managed separately, and transfer data between each other as required. these small blocks can help you reason about and test your code. while some frameworks encourage you to separate your template, logic, and styling code into separate files, vue takes the opposite approach. using single file components, vue lets you group your templates, corresponding script, and css all together in a single file ending in .vue. these files are processed by a js build tool (such as webpack), which means you can take a...
Adding a new todo form: Vue events, methods, and models - Learn web development
ioned earlier, v-model syncing works by updating the variable using events. for text inputs, this sync happens using the input event. often, this means that vue is syncing the data after every keystroke. the .lazy modifier causes v-model to use the change event instead. this means that vue will only sync data when the input loses focus or the form is submitted. for our purposes, this is much more reasonable since we only need the final data. to use both the .lazy modifier and the .trim modifier together, we can chain them, e.g. v-model.lazy.trim="label". update your v-model attribute to chain lazy and trim as shown above, and then test your app again. try for example, submitting a value with whitespace at each end. passing data to parents with custom events we now are very close to being abl...
Understanding client-side JavaScript frameworks - Learn web development
go on to, to continue your svelte learning journey. which frameworks did we choose? we are publishing our initial set of articles with guides focusing on four frameworks. three of them are very popular and well-established — react/reactdom, ember, and vue — whereas svelte is a comparative newcomer that shows a lot of promise and has gained a lot of recent popularity. there is a variety of reasons for this: they are popular choices that will be around for a while — like with any software tool, it is good to stick with actively-developed choices that are likely to not be discontinued next week, and which will be desirable additions to your skill set when looking for a job. they have strong communities and good documentation. it is very important to be able to get help with learning a...
Implementing feature detection - Learn web development
document.createelement('p'); para.textcontent = 'argh, no geolocation!'; document.body.appendchild(para); } try your example out! here we use the modernizr.geolocation test to check whether geolocation is supported by the current browser. if it is, we run some code that gets your device's current location, and plots it on a google map. summary this article covered feature detection in a reasonable amount of detail, going through the main concepts and showing you how to both implement your own feature detection tests and use the modernizr library to implement tests more easily. next up, we'll start looking at automated testing. previous overview: cross browser testing next in this module introduction to cross browser testing strategies for carrying out testing handling c...
Handling common JavaScript problems - Learn web development
cript 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. such incompatibility problems persisted well into the early 2000s, as old browsers were still being used and still needed supporting. this is one of the main reasons why libraries like jquery came into existence — to abstract away differences in browser implementations (e.g. see the code snippet in how to make an http request) so developers only have to write one simple bit of code (see jquery.ajax()). 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 sin...
Git and GitHub - Learn web development
eful for you to get to know at least the basics of git terminal commands, even if you intend to use a gui. a github account. if you haven't already got one, sign up now using the provided link. in terms of prerequisite knowledge, you don't need to know anything about web development, git/github or vcses to start this module. however, it is recommended that you know some coding so that you have reasonable computer literacy, and some code to store in your repositories! it is also preferrable that you have some basic terminal knowledge, so for example moving between directories, creating files, and modifying the system path. note: github is not the only site/toolset you can use with git. there are other alternatives such as gitlab that you could try, and you could also try setting your own gi...
Accessibility API cross-reference
mantic elements' of html5 (such as main and footer), but there is not a one-to-one mapping between the aria roles and the semantics of html5. aria can be used to 'fill out' the missing semantics of html, but may also be used in other markup languages (such as svg) and expresses semantics using attributes, compared with html, which tends to have distinct named elements for its roles. for all these reasons, aria and html are given separate columns. aria abstract roles should not be used by content authors. the gnome accessibility architecture is implemented via atk and at-spi, and was implemented by sun microsystems. it will be reused for kde accessibility via at-spi . we find that it uses very similar naming conventions as java accessibility, and for those purposes the two to be nearly the same.
Accessibility Features in Firefox
yle, user scripts let you easily control any aspect of a web page's design or interaction. we expect enterprising script writers will eventually fix annoying accessibility issues in popular web pages, and (hopefully) share their tricks with everyone! fire vox extension by charles l. chen is a screen reader extension built just for firefox which can read mathml community contributions the real reason behind firefox's success is the great community of volunteers and organizations that realize they have something to benefit from a browser open to utilizing their ideas and hard work. contributions come in many forms. the mozilla firefox community welcomes bug reports, ideas, documentation, answering questions in the support forums -- and nearly any kind of community involvement resulting in a br...
CSUN Firefox Materials
also includes a full-featured session manager with crash recovery that can save and restore combinations of opened tabs and windows. fire vox is a screen reader extension built just for firefox which can read mathml the accessibility extension, from the university of illinois, provides new menus and keyboard shortcuts for accessing every feature of a web page community contributions the real reason behind firefox's success is the great community of volunteers and organizations that realize they have something to benefit from a browser open to utilizing their ideas and hard work. contributions come in many forms. the mozilla firefox community welcomes bug reports, ideas, documentation, answering questions in the support forums -- and nearly any kind of community involvement resulting in a br...
Multiprocess on Windows
er than typelib metadata, however com requires typelibs whenever it is being used with interpreted languages. in particular, typelibs were originally designed to work with 1990s-era visual basic. typelib metadata is limited to supporting the same language features which were supported by vb at that time. given those two options, it may seem that oicf is the preferred format. however, for various reasons, our com interceptor currently only supports typelib metadata. in order for the interceptor to be able to work with our interfaces, we must do some additional work to compensate for typelib's weaknesses. the required steps are as follows: ensure that you generate typelibs for all of your com interfaces; ensure that those interfaces are registered; register any outparams that consist of arra...
Software accessibility: Where are we today?
cessibility aids. this solution has seen only partial success, largely due to the fact that it requires significant changes to applications which are made accessible. because most popular desktop and productivity applications are not open source, this forced disabled people to rely on the companies which produce this software to make it accessible. these companies were often reluctant for various reasons including the large amount of time required to do so. on a positive note, recent federal purchasing rules such as section 508 have caused many companies to pay attention and implement msaa support. enter open source software microsoft was on the right track with microsoft active accessibility, but because the source code to most popular desktop applications which are used in large corporations i...
Mozilla’s UAAG evaluation report
is. a ui for this would be good. 2.4 allow time-independent interaction. (p1) nr need to look into this 2.5 make captions, transcripts available. (p1) na this relates to multimedia players 2.6 respect synchronization cues. (p1) na this relates to multimedia players 2.7 repair missing content. (p2) p no alt repair strategies in place. reasons: the title attribute is almost never present when the alt isn't. in the rare cases where it is, it is of no help (typically it's just the filename, maybe with a file size). also, in the overwhelming majority of cases, the filename is unintelligible. developers interested in this problem can look at the getalternatetext() method -- see the cvs history for suggestions. we consider this to be a ver...
Capturing a minidump
, in which case manual capture of a minidump is desired. this page describes how to capture these minidumps on windows, to permit better debugging. privacy and minidumps warning! unlike the minidumps submitted by breakpad, these minidumps contain the complete contents of program memory. they are therefore much more likely to contain private information, if there is any in the browser. for this reason, you may prefer to generate minidumps against a clean profile where possible. capturing a minidump: application crash to capture a full minidump for an application crash, you can use a tool called windbg. install debugging tools for windows microsoft distributes the debugging tools for windows for free, those include windbg which you will need here. download it from install debugging tools fo...
Debugging OpenGL
this article provides suggestions for how to improve your efficiency while debugging opengl code in gecko. opengl debug mode when running a debug build, you can enable the opengl debug mode by defining the environment variable moz_gl_debug. if you start up firefox with this variable defined, the following behavior changes occur: each time you issue an opengl call, a check is performed to ensure that the gl context is current, using a thread-local static variable to keep track of this. if the context isn't current, the call aborts. every time an opengl call completes, glfinish() gets run automatically. this flushes out each call, essentially turning opengl into a synchronous api. ...
HTTP logging
directly into your startup disk's applications folder. if you've put it elsewhere, change the path used on the third line appropriately.) reproduce whatever problem you're trying to debug. quit firefox and look for the generated log.txt log files on your desktop. note: the generated log file uses unix-style line endings. older editors may have problems with this, but if you're using an even reasonably modern mac os x application to view the log, you won't have any problems. start logging using command line arguments since firefox 61 it's possible to start logging in a bit simpler way than setting environment variables: using command line arguments. here is an example for the windows platform, on other platforms we accept the same form of the arguments: if firefox is already running,...
How Mozilla's build system works
backend provides a common framework from which to author consumers. along the same vein, you don't need to use treemetadataemitter to consume mozbuildsandbox instances. nor do you need to use buildreader to traverse the moz.build files. this is just the default framework we've established for our build system. legacy content the content below is considered legacy. it is preserved for historical reasons until this entire page is rewritten. makefile basics makefiles can be quite complicated, but mozilla provides a number of built-in rules that should enable most makefiles to be simpler. complete documentation for make is beyond the scope of this document but is available here. one concept you will need be familiar with is variables in make. variables are defined by the syntax variable = value...
The Firefox codebase: CSS Guidelines
reviews if you are changing css: avoid !important but if you have to use it, make sure it's obvious why you're using it (ideally with a comment). the overriding css section contains more information about this. avoid magic numbers; prefer automatic sizing or alignment methods. some examples to avoid: absolutely positioned elements hardcoded values such as: vertical-align: -2px; . the reason you should avoid such "hardcoded" values is that, they don't necessarily work for all font-size configurations. avoid setting styles in javascript. it's generally better to set a class and then specify the styles in css. classlist is generally better than classname. there's less chance of overwriting an existing class. only use generic selectors such as :last-child, when it is what you me...
Creating Custom Events That Can Pass Data
asses entry would be domci_class(myfirstevent)). mozilla/dom/src/base/nsdomclassinfo.cpp mozilla contains many convenience macros to make changes like the one you're making easier. your modification of this file is basically just two macro calls. try to make sure of two things: keep your stuff at the back. you know never know what depends on that enum you modified keep your stuff organized. same reason as above. you need to make the following two modifications: around line 1000: ns_define_classinfo_data({truncated name}, nsdomgenericsh, dom_default_scriptable_flags) around line 2900: dom_classinfo_map_begin({truncated name}, nsidom{truncatedname}) dom_classinfo_map_entry(nsidom{truncated name}) dom_classinfo_event_map_entries dom_classinfo_map_end remember, {truncated name} is the sa...
Commenting IDL for better documentation
hem into beautiful, easy to search and read documentation. but by following the guidelines here, you can help make sure that our tools can generate a "good start" version of the documentation for your interfaces, and that the writers will be able to easily figure out what the tools are not able to do automatically. comment format doxygen supports several comment formats; for style and consistency reasons, we use the following: /** * */ note the two asterisks ("**") on the first line of the comment. that lets doxygen (and by extension, our automated documentation import tools) know that the comment should be absorbed into documentation. if you use any other format for your comments, our tools will ignore them. following the rules below will ensure that our tools are able to produce the best po...
Listening to events on all tabs
long aflags ); parameters abrowser the browser representing the tab whose location changed. awebprogress the progress instance responsible for handling the events. arequest the nsirequest object representing the associated request. alocation an nsiuri object indicating the tab's new uri. aflags optional: this is a value which explains the situation or the reason why the location has changed. optional from gecko 10 onprogresschange called when updated progress information for the download of a document is available. void onprogresschange( nsidomxulelement abrowser, nsiwebprogress awebprogress, nsirequest arequest, print32 acurselfprogress, print32 amaxselfprogress, print32 acurtotalprogress, print32 amaxtotalprogress ); parameters abr...
SVG Guidelines
when used as an image format, it is sometimes less obvious whether it would be best to use svg or a raster image format for any given image. the vector format svg and raster formats like png both have their place. when choosing whether or not to use svg it is best to understand the advantages and disadvantages of both. file size whether svg or a raster format will produce a smaller file for a given image depends very much on the image. for example, consider an image of a path with a gradient fill. ...
mach
t work like a charm - while "mach" may not necessarily work like a charm for everyone. why even bother with a competing build system in arch when octopi does what you want and even has a gui? those makepkg scripts named pkgbuild are (typically) simple bash scripts that are easy to maintain and modify. python based mach tends to involve more complexity and potential for breakage. another possible reason: mach gives you an error, while running, say bootstrap.py directly (that is to type in a bash shell: python2 ./bootstrap.py enter-key ) in an otherwise empty ..../subdir/ may work for you! less may be better! and mach's error messages tend to be cryptic and not utterly helpful. that above bootstrap.py will download and setup everything so you can build a mozilla app such as firefox etcetera, so...
Experimental features in Firefox
ceeds, the message indicates that the request was upgraded, instead of showing a warning. release channel version added enabled by default? nightly 60 no developer edition 60 no beta 60 no release 60 no preference name security.mixed_content.upgrade_display_content ftp support disabled for security reasons, mozilla intends to remove support for ftp from firefox in 2020, effective in firefox 82. see bug 1622409 for implementation progress. the network.ftp.enabled preference must be enabled (set to true) to allow ftp to be used. release channel version added enabled by default? nightly 77 yes developer edition 77 no beta 77 no ...
Multiple Firefox profiles
having different profiles would help separate work and personal life, or allow each family member to have his or her own set of bookmarks, settings, and add-ons. ...
Cross Process Object Wrappers
ccesses the current document uri via a cpow. you might expect the value of uri to come back as "hello.com". but it might not: in order to avoid deadlocks, cpow messages can bypass normal messages and be processed first. it’s possible that the request for the documenturi property will be processed before the "changedocumenturi" message, in which case uri will have its previous value. for this reason, it’s best not to mix cpows with normal message manager messages. it’s also a bad idea to use cpows for anything security-related, since you may get results that are not consistent with surrounding code that might use the message manager. safe and unsafe cpows the main reason cpows can be bad for responsiveness is that they make the chrome process block on the content process. essentially,...
Limitations of chrome scripts
object in these situations. in some situations, the content process may not be initialized when an add-on asks for access to its content. in this case, the shim will return a javascript object that looks somewhat like a window or a document for about:blank. however, this "dummy" object is completely static and only exposes a few of the normal properties that windows and documents have. for this reason, add-ons that try to access content objects in fresh <browser> elements may run into trouble. to make the shim unnecessary: factor the code that needs to access content into a separate script, load that script into the content process as a frame script, and communicate between the chrome script and the frame script using the message-passing apis. see the article on using the message manager. li...
Using the Browser API
Mozilla › Gecko › Chrome › API › Browser API › Using
tml an <iframe> is turned into a browser iframe by setting the mozbrowser attribute on it: <iframe src="http://mozilla.org" mozbrowser> in addition, the <iframe> can be loaded in its own child process — separate to the page embedding this frame — by including the remote attribute. <iframe src="http://hostname.tld" mozbrowser remote> warning: this last attribute is necessary for security reasons if you plan to load content from an untrusted/unknown origin. if you don't use it, you run the risk of your application being compromised by a malicious web site. it is implied for webextensions, which always run in a separate content process from web content. aside from the iframe, there are some basic controls: <button> elements, a simple <form> to implement the browser controls, and a sear...
mozbrowserasyncscroll
the total content height in css pixels of the document within the browser <iframe>. note: top + height may be larger than scrollheight. this indicates that the content is over-scrolled, which occurs when the page "rubber-bands" after being scrolled all the way to the bottom. similarly, left + width may be greater than scrollwidth, and both left and top may be negative. note: for performance reasons, this event is asynchronous. that means that the value retrieved through the event object can be different than the real current position of the scroll when the event is processed. examples var browser = document.queryselector("iframe"); browser.addeventlistener("mozbrowserasyncscroll", function( event ) { console.log("the scroll top position of the document is:" + event.details.top + "px"...
HTML parser threading
html parser threading the html parser parses data received from the network off the main thread. (there's currently one parser thread serving all parser instances.) data received from document.write() is parsed on the main thread. main objects nshtml5parser contains the code for dealing with data from document.write(). (for historical reasons, it also contains unrelated fragment parsing code that should be refactored into a separate class in due course.) nshtml5streamparser contains the code for dealing with data from the network. nshtml5parser owns nshtml5streamparser. script-created parsers (i.e. parsers created using document.open()) don't have an nshtml5streamparser instance. nshtml5parser has one tokenizer/tree builder pair for parsing data from document.write(). it also has another...
HTTP Cache
utput stream immediately, even before the output stream is closed. this is called concurrent read/write. concurrent read and write important difference in behavior from the old cache: the cache now supports reading a cache entry data while it is still being written by the first consumer - the writer. this can only be engaged for resumable responses that (bug 960902) don't need revalidation. reason is that when the writer is interrupted (by e.g. external canceling of the loading channel) concurrent readers would not be able to reach the remaning unread content. this could be improved by keeping the network load running and being stored to the cache entry even after the writing channel has been canceled. when the writer is interrupted, the first concurrent reader in line does a range req...
IPDL Best Practices
e allocpprotocol and deallocpprotocol are asymmetric, if ipdl ends up shutting down the protocol tree due to an error, the auto pointer will attempt to trigger protocol deletion a second time. while this can be worked around with actordestroy, being explicit about deleting the protocol with send__delete__ is easier to maintain, with symmetric alloc/deallocpprotocol functions also being easier to reason about. minimize overall use of messages reducing ipc traffic is a righteous goal. consider the following protocol: async protocol pasyncquerier { child: pasyncquery(); } async protocol pasyncquery { child: kickoffquery(nsstring query); parent: returnresult(nsstring result); __delete__(); } in this situation, there is a guaranteed sequence of messages that will be sent. following acto...
Implementing QueryInterface
nterface(aiid, &foundinterface); } else { ns_addref(foundinterface); status = ns_ok; } // ... it will be difficult, if not impossible, to get the right thing to happen if any of your base classes participate in true aggregation. you won't be able to catch calls to queryinterface on the aggregated objects, which may then return wrong interfaces. one more reason to avoid aggregation specifically, and complicated hierarchies in general. the ns_get_iid macro you can use the ns_get_iid macro instead of typing out the full getiid expression. in general, i disapprove of macros except in cases where the macro must expand to different text in different situations, e.g., different platforms, debugging vs. non-debugging, et al. in such cases macros are indispen...
Introduction to Layout in Mozilla
ia presshell method incremental reflows targeted at a specific frame dirty, content-changed, style-changed, user-defined nshtmlreflowcommand object encapsulates info queued and processed asynchronously, nsipressshell::appendreflowcommand, processreflowcommands incremental reflow recursively descend to target recovering reflow state child rs.reason set to incremental incremental reflow process reflow “normally” at target frame child rs.reason set based on rc’s type incremental reflow propagate damage to frames later “in the flow” incremental reflow multiple reflow commands are batched nsreflowpath maintains a tree of target frames amortize state recovery and damage propagation c...
JavaScript Tips
prefer to loop through childnodes rather than using first/lastchild with next/previoussibling. but prefer haschildnodes() to childnodes.length > 0. similarly prefer document.getelementsbytagname(atag).item(0) != null to document.getelementsbytagname(atag).length > 0. prefer to use localname rather than tagname. xul elements have many of the attributes mapped to properties. this was done for a reason, so use them! the properties are: align allowevents contextmenu datasources dir flex height id left maxheight maxwidth minheight minwidth observes orient pack persist ref statustext top tooltip tooltiptext width xul also maps the ordinal attribute but this defaults to "1" if it is not present. xul also maps the class...
AddonManager
stant description error_network_failure a network error occurred. error_incorrect_hash the downloaded file did not match the expected hash. error_corrupt_file the file appears to be corrupt. error_file_access there was an error accessing the filesystem. error_signedstate_required the addon must be signed and isn't. update check reasons constant description update_when_user_requested an update check performed at the explicit request of the user. update_when_new_app_detected an update check performed when a new version of the application has been detected. update_when_new_app_installed an update check performed after a new version of the application has been installed. up...
AsyncShutdown.jsm
rn promise; }, function info() { let status = ... // collect any information that may be useful for debugging shutdown issues with this blocker return status; } }); in this example, at some point during phase profilebeforechange, function condition will be called. phase profilebeforechange is guaranteed to not terminate until promise is either resolved or rejected. if, for some reason, promise is never resolved/rejected, firefox will crash during shutdown to avoid blocking system shutdown, preventing the user from restarting firefox or burning through a battery. in this case, a crash report is produced, with information on all the shutdown blockers that have not been resolved, and all the additional debug information returned by calls to info(). instances of phase note th...
OS.File.Info
e, 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 { // inf...
OSFile.jsm
f-main thread file i/o, main thread api. calling os.file.directoryiterator from the main thread asynchronous, off-main thread file directory access, main thread api. ... from a worker thread in some cases, the main thread api for os.file is not appropriate as it would require too much message passing, or because the code that requires file i/o is already executed on a worker thread. for this reason, api clients can also spawn their own worker threads and make use of os.file directly from these threads. os.file for workers synchronous file i/o for worker threads os.file.directoryiterator for workers visiting directories synchronously from a worker thread ... shared components os.path and os.constants.path manipulation of paths os.file.error representation of file-related errors...
Sqlite.jsm
ally. parameters can be bound to the statement by defining the params argument. this argument can be an array of positional parameters or an object of named parameters. if the statement does not contain any bound parameters, this argument can be omitted or specified as null. note: callers are strongly encouraged to use bound parameters instead of dynamically creating sql statements for security reasons. bound parameters aren't prone to sql injection like manual sql statement construction (e.g., concatenating a raw value into the executed sql statement). note: callers are encouraged to pass objects rather than arrays for bound parameters because they prevent foot guns. with positional arguments, it is simple to modify the parameter count or positions without fixing all users of the statement. ...
Webapps.jsm
, aoldapp, amanifest, aisupdate) _getids: function(aissigned, azipreader, aconverter, anewapp, aoldapp,) _checkforstoreidmatch: function(aisupdate, anewapp, astoreid, astoreversion) revertdownloadpackage: function(aid, aoldapp, anewapp, aisupdate, aerror) uninstall: function(amanifesturl) _promptforuninstall: function(adata) confirmuninstall: function(adata) denyuninstall: function(adata, areason = "error_unknown_failure") getself: function(adata, amm) checkinstalled: function(adata, amm) getinstalled: function(adata, amm) getnotinstalled: function(adata, amm) geticon: function(adata, amm) getall: function(acallback) isreceipt: function(data) addreceipt: function(adata, amm) removereceipt: function(adata, amm) replacereceipt: function(adata, amm) setenabled: function(adata) ge...
Bootstrapping a new locale
_options --enable-application=browser" >> .mozconfig make -f client.mk configure create a language pack first, we'll create a build directory. this sounds worse than it is, you won't need to actually build, but we'll need to setup something that looks like it. you're still in the l10n directory, right? we'll create build right next to it. the name of that directory doesn't really matter, so no reason to change it. mkdir ../build cd ../build now we'll set up a not-so-compile environment by calling configure. if you just checked out the localizable parts of en-us above, it will create a plethora of warnings no such file or directory, but no errors. ../mozilla/configure --disable-compile-environment --enable-application=browser whenever you need a build directory, these are the steps that ...
Index
esent you with the technical information you need to become an official release. we'll primarily focus on getting your release repository setup and the mercurial commands you'll need to know to use that repository. 16 translation phase localization, localization:tools congratulations on completing the initial setup! as a reward for your efforts, you get to move on to the very reason you've come here: to localize mozilla projects. 17 localization sign-off reviews guide, localization, mozilla this article presents an overview of why we do sign-off reviews of localizations, the details on the criteria used for the sign-off reviews, and the process for requesting a review and for following its progress. 18 localization technical reviews guide,...
Translation phase
this is where the technical aspect of the process begins to divide. at mozilla, we localize many different projects that can be categorized into three different groups. each group of projects employs a different type of l10n tool for, you guessed it, localizing the projects. the l10n tools are meant to help you maintain your localized content from release to release and leverage already localized materials when localizing new content. ...
Uplifting a localization from Central to Aurora
sure that your aurora clone doesn't have quality issues. in particular, did you land all the fixes for your work on both central and aurora? because mercurial suggests that you didn't. look at the merge conflicts, and figure out if there's stuff that you still want to land on aurora. if so, you want to fix those issues on aurora alone, verify them there, and then go back to this page. one of the reasons why we suggested that you do the merging in a separate tree is just this. you can just throw your merge candidate away as long as you find fixes that you've forgotten on either aurora or beta, and address those in their own repos first. push them to hg.mozilla.org there, verify the builds, and then try to merge l10n-central and aurora again. there is one scenario where you don't want to have the...
Creating localizable web applications
few html elements with the gettext function call as possible, you could try to put the <strong/> html tag outside of the php code (cf. snippet 2). however, in this snippet, the concatenation of the $persona['date'] variable is still hardcoded and only allows one ordering of the sentence, while some grammars might require, for instance, to put the date in front of the "added" descriptor. for this reason, it is better to leave the <strong/> html tags inside the gettext function call and take advantage of the printf() variable that will be substituted by the date upon interpretation of the code (snippet 3). snippet 4. good: <h3> <?printf( /* l10n: %s is the author's username */ _("created by <a href=\"%s\">%s</a>"), $locale_conf->url('/gallery/designer/' . $persona['author']), ...
Web Localizability
es localization. the following list contains links to pages that highlight steps that can be taken to make web content localizable. the documentation is divided into 4 parts: how to create localizable content. how to choose the right localization format. how to create localizable web applications. how to set up the infrastructure for localization. why localizability is important there are many reasons why you should start thinking about making your web app localizable as soon as possible. you will make localizer's life easier, for which they will be grateful. you will have quality content, localized and adapted to the needs of the local market. extending you web app to support new languages will be easy. the content will be easier to maintain and update. you will end up writing more semantic...
MathML Demo: <mo> - operator, fence, separator, or accent
oduct of a fenced row vector and a fenced column vector as shown below. [ a b c d ] ⁢ [ a b c d ] we want the row vector to typeset at the same level as the top row of the column vector, but this is difficult to achieve. this problem can be solved using aligned arrays, as follows a b c d ⁢ a b c d however, all reasonable attempts to fence the column vector will fail because latex fences are symmetric. in mathml, operators that are used for fencing are never symmetric and are always stretchy by default. (i.e., as documented in the suggested operator dictionary). hence <mo symmetric="true"> must be scripted if the intent is to emulated latex fence behavior. the commands \big, \big, \bigg and \bigg produce a dis...
Mozilla Web Developer FAQ
ne or more of the unknown and unintentional interactions within the program. the usual counter argument is that mozilla doesn’t need to match the behavior of browser x in every possible case but only in the alleged common cases. however, it turns out mozilla is doing that already. mozilla’s standards mode is, obviously, already compatible with other browsers that implement the same standards reasonably correctly. on the other hand, mozilla’s quirks mode already accommodates common non-standardisms that are due to the behaviors of common legacy browsers. instead of putting time and effort into reverse-engineering and cloning legacy browsers, it makes more sense to focus on implementing standards. standards (when implemented by others as well) promote interoperability better than cloning l...
Mozilla Style System Documentation
hich have style contexts pointing to rule node a), with each style context in the format [element type: rule node]: [doc: b] ,------------' | `-----------. [title: c] [para: f] [para: d] | | [quote: a] [quote: a] | [span: e] the reason the rule tree shares style data naturally is that most style rules specify properties in very few structs. as stated above, each style struct contains only features that are inherited by default or those that are set to their initial value ("reset") by default. this leads to (or perhaps three, depending on how you count) two types of sharing. for those structs where all the values are inherited b...
Activity Monitor, Battery Status Menu and top
his menu for the first time in a while it says “collecting power usage information” for a few seconds, and if you have top open during that time you'll see that, once again, systemstats is running and using a lot of cpu. furthermore, if you click on an application name in the menu activity monitor will be opened and that application’s entry will be highlighted. based on these facts it seems reasonable to assume that “energy impact” is again being used to determine which applications are "using significant energy". testing shows that once an energy-intensive application is started it takes less than a minute for it to show up in the battery status menu. and once the application stops using high amounts of energy it takes a few minutes to disappear. the exception is when the application...
GPU performance
see also debugging with pix. nvidia perfhud - last i checked required a special build to be used. nvidia parallel nsight - haven't tried. amd gpu shaderanalyzer - will compile a shader and show the machine code and give static pipeline estimations. not that useful for firefox because all of our shaders are pretty simple. ...
Intel Power Gadget
(b) it shows this data in graph form, which is occasionally useful. on mac and linux, tools/power/rapl is probably a better tool to use. understanding the power gadget output the following screenshot (from the mac version) demonstrates the available measurements. the three panes display the following information: power: shows power estimates for the package and the cores ("ia"). these are reasonably useful for power profiling purposes, but mozilla's rapl utility provides these along with gpu and ram estimates, and in a command-line format that is often easier to use. frequency: shows operating frequency measurements for the cores ("ia") and the gpu ("gt"). these measurements aren't particularly useful for power profiling purposes. temperature: shows the package temperature. this is int...
Memory reporting
emory reporters can be divided into the two following kinds. traversal-based reporters traverse one or more data structures and measure the size of all the allocated blocks in the data structure. counter-based reporters maintain a counter that is incremented on each relevant allocation and decremented on each relevant deallocation. traversal-based reporters are preferable, for the following reasons. they are less error-prone. we've had multiple bugs in the past with counter-based reporters. the cost of reporting isn't incurred unless the memory reporter is queried. they provide more information to dmd, which is a tool that helps keep about:memory's "heap-unclassified" number low. see below for more details. sometimes counter-based reporters are unavoidable, particularly when writing...
Power profiling overview
uce power consumption. one consequence of the existence of c-states is that observations made during power profiling — even more than with other kinds of profiling — can disturb what is being observed. for example, the gecko profiler takes samples at 1000hz using a timer. each of these samples can trigger a wakeup, which consumes power and obscures firefox's natural wakeup patterns. for this reason, integrating power measurements into the gecko profiler is unlikely to be useful, and other power profiling tools typically use much lower sampling rates (e.g. 1hz.) p-states intel processors also support multiple p-states. p0 is the state where the processor is operating at maximum frequency and voltage, and higher-numbered p-states operate at a lower frequency and voltage to reduce power cons...
perf
wakeups perf can also be used to do high-context profiling of wakeups. ...
powermetrics
rouping of parent and child processes (in coalitions) is obvious. the meaning of the columns is as follows. name: coalition/process name. process names within coalitions are indented. id: coalition/process id number. cpu ms/s: cpu time used by the coalition/process, per second, during the sample period. the sum of the process values typically exceeds the coalition value slightly, for unknown reasons. user%: percentage of that cpu time spent in user space (as opposed to kernel mode.) deadlines (<2 ms, 2-5 ms): these two columns count how many "short" timers woke up threads in the process, per second, during the sample period. high frequency timers, which typically have short time-to-deadlines, can cause high power consumption and should be avoided if possible. wakeups (intr, pkg idle): th...
Profile Manager
description of these. launch option command line argument run firefox in offline mode -offline run firefox in safe mode -safe-mode start firefox with a console -console start new instance -no-remote note: it isn't possible to start a second instance of firefox without passing it the -no-remote command line argument. for this reason, if you attempt to launch firefox using profile manager, and it detects that another instance of firefox is already running, it will automatically add the -no-remote argument for you, regardless of whether this launch option was checked. locked profiles some profiles may be shown as locked in the main window. such profiles are currently being used by an instance of firefox. if you attempt ...
L20n Javascript API
he ids list. it will be called when the entities become available (asynchronously) or whenever the translation of any of the entities changes. localize should be the preferred way of localizing the ui. the callback function is passed an l10n object with the following properties: entities: an object whose keys are the identifiers and value are the entity objects as returned by getentitysync, reason: an object with the reason why callback was invoked. the reason object can be: { locales: array<string> } if callback was invoked because of a change of the current locale (see requestlocales), { global: string } if callback was invoked because the value of one of the globals used in the translation of ids has changed. ctx.ready(callback: function) fires the function passed as argument a...
AsyncTestUtils extended framework
asynctestutils framework to a nested event loop in a backwards-compatible fashion. how does this affect my tests? thanks to javascript enhancements available on the mozilla platform, it is possible for a function to yield control in such a way that the function stops running at the line where you use a yield statement and resumes execution on the next line when resumed. this allows you to write reasonably normal looking functions instead of having to chain together a whole bunch of functions and callbacks. your test functions need to agree to the following contract: the asynchronous function contract a function should yield false or return false when something asynchronous is going on. when the asynchronous operation is complete, something needs to call async_driver(). returning false tell...
Leak And Bloat Tests
this page describes how to perform tests that measure memory leaks and bloat for mailnews and its sub-components. aim to provide a continuous check within mailnews and its sub-components for the following items: total memory leaks. total memory usage (aka bloat). provide a consistent number from build to build where no source code has changed. provide reasonable coverage for the normal activities that a user performs. method current method: measure leaks and bloats, in a similar way to firefox (using xpcom_mem_leak_log and --trace-malloc). the method of testing memory bloat and leaks will be the same sequence of events, using the same set of test data. startup main mail window open address book and message composition windows close address book and message composition windows ...
MailNews automated testing
vides additional facilities as described on the mailnews automated testing page (see below). "make check" is used to run compiled code tests. these tests can go beyond the limitations of xpcshell-tests (for example, access c++ code) and other testing options that don't test at the right level. testing frameworks the asynctestutils extended framework supports: asynchronous test operation: a reasonably convenient means of writing tests that involve asynchronous operations by using generators. in the long term we would like to lose this extra complexity in favor of the event-loop-spinning style of operation used by mozmill. message synthesis: create messages by specifying what properties the messages should have. message injection: inject synthesized messages via local or imap (using a fak...
About NSPR
trives to not export the lowest common denominator, but to exploit the best features of each operating system on which it runs, and still provide a uniform service across a wide range of host offerings. threads threads are the major feature of nspr. the industry's offering of threads is quite sundry. nspr, while far from perfect, does provide a single api to which clients may program and expect reasonably consistent behavior. the operating systems provide everything from no concept of threading at all up to and including sophisticated, scalable and efficient implementations. nspr makes as much use of what the systems offer as it can. it is a goal of nspr that nspr impose as little overhead as possible in accessing those appropriate system features. thread synchronization thread synchronizati...
NSPR build instructions
dual 32-bit/64-bit platform, nspr build generates a 32-bit build by default. to generate a 64-bit build, specify the --enable-64bit configure option. --target=x86_64-pc-mingw32 for 64-bit builds on windows, when using the mozillabuild environment. --enable-win32-target=win95 this option is only used on windows. nspr build generates a "winnt" configuration by default on windows for historical reasons. we recommend most applications use the "win95" configuration. the "win95" configuration supports all versions of windows. the "win95" name is historical; it should have been named "win32". to generate a "win95" configuration, specify the --enable-win32-target=win95 configure option. --enable-debug-rtl this option is only used on windows. nspr debug build uses the release c run-time library b...
NSPR Error Handling
s specified is invalid (as reported by the network). pr_address_in_use_error network address specified (prnetaddr) is in use. pr_connect_refused_error the peer has refused to allow the connection to be established. pr_network_unreachable_error the network address specifies a host that is unreachable (perhaps temporary). pr_connect_timeout_error the connection attempt did not complete in a reasonable period of time. pr_not_connected_error the preceding function attempted to use connected semantics on a network file descriptor that was not connected. pr_load_library_error failure to load a dynamic library. pr_unload_library_error failure to unload a dynamic library. pr_find_symbol_error symbol could not be found in the specified library. pr_insufficient_resources_error there are ...
PR_AcceptRead
of the prnetaddr structures. if 0, no data will be read from the peer. timeout the timeout interval only applies to the read portion of the operation. pr_acceptread blocks indefinitely until the connection is accepted; the read will time out after the timeout interval elapses. returns a positive number indicates the number of bytes read from the peer. the value -1 indicates a failure. the reason for the failure can be obtained by calling pr_geterror. description pr_acceptread accepts a new connection and retrieves the newly created socket's descriptor and the connecting peer's address. also, as its name suggests, pr_acceptread receives the first block of data sent by the peer. ...
PR_AttachSharedMemory
...
PR_CloseDir
closes the specified directory. syntax #include <prio.h> prstatus pr_closedir(prdir *dir); parameter the function has the following parameter: dir a pointer to a prdir structure representing the directory to be closed. returns if successful, pr_success. if unsuccessful, pr_failure. the reason for the failure can be retrieved via pr_geterror. description when a prdir object is no longer needed, it must be closed and freed with a call to pr_closedir call. note that after a pr_closedir call, any prdirentry object returned by a previous pr_readdir call on the same prdir object becomes invalid. see also pr_opendir ...
PR_DestroyPollableEvent
h a pollable event and release related resources. syntax nspr_api(prstatus) pr_destroypollableevent(prfiledesc *event); parameter the function has the following parameter: event pointer to a prfiledesc structure previously created via a call to pr_newpollableevent. returns the function returns one of the following values: if successful, pr_success. if unsuccessful, pr_failure. the reason for the failure can be retrieved via pr_geterror. ...
PR_EnumerateHostEnt
, this structure is filled in by the runtime if the result of the call is greater than 0. returns the function returns one of the following values: if successful, the function returns the value you should specify in the enumindex parameter for the next call of the enumerator. if the function returns 0, the enumeration is ended. if unsuccessful, the function returns -1. you can retrieve the reason for the failure by calling pr_geterror. description pr_enumeratehostent is a stateless enumerator. the principle input, the prhostent structure, is not modified. ...
PR GetAddrInfoByName
...
PR_GetConnectStatus
nblocking connection. syntax prstatus pr_getconnectstatus(const prpolldesc *pd); parameter the function has the following parameter: pd a pointer to a prpolldesc satructure whose fd field is the socket and whose in_flags field must contain pr_poll_write and pr_poll_except. returns the function returns one of these values: if successful, pr_success. if unsuccessful, pr_failure. the reason for the failure can be retrieved via pr_geterror. if pr_geterror returns pr_in_progress_error, the nonblocking connection is still in progress and has not completed yet.other errors indicate that the connection has failed. description after pr_connect on a nonblocking socket fails with pr_in_progress_error, you may wait for the connection to complete by calling pr_poll on the socket with the ...
PR_GetHostByAddr
atehostent. bufsize number of bytes in the buf parameter. the buffer must be at least pr_netdb_buf_size bytes. hostentry this structure is allocated by the caller. on output, this structure is filled in by the runtime if the function returns pr_success. returns the function returns one of the following values: if successful, pr_success. if unsuccessful, pr_failure. you can retrieve the reason for the failure by calling pr_geterror. description pr_gethostbyaddr is used to perform reverse lookups of network addresses. that is, given a valid network address (of type prnetaddr), pr_gethostbyaddr discovers the address' primary name, any aliases, and any other network addresses for the same host. ...
PR_GetHostByName
atehostent. bufsize number of bytes in the buf parameter. the buffer must be at least pr_netdb_buf_size bytes. hostentry this structure is allocated by the caller. on output, this structure is filled in by the runtime if the function returns pr_success. returns the function returns one of the following values: if successful, pr_success. if unsuccessful, pr_failure. you can retrieve the reason for the failure by calling pr_geterror. ...
PR_GetPeerName
gets the network address of the connected peer. syntax #include <prio.h> prstatus pr_getpeername( prfiledesc *fd, prnetaddr *addr); parameters the function has the following parameters: fd a pointer to a prfiledesc object representing a socket. addr on return, the address of the peer connected to the socket. returns if successful, pr_success. if unsuccessful, pr_failure. the reason for the failure can be obtained by calling pr_geterror. ...
PR_GetProtoByName
caller. bufsize number of bytes in the buffer parameter. the buffer must be at least pr_netdb_buf_size bytes. result on input, a pointer to a prprotoent structure. on output, this structure is filled in by the runtime if the function returns pr_success. returns the function returns one of the following values: if successful, pr_success. if unsuccessful, pr_failure. you can retrieve the reason for the failure by calling pr_geterror. ...
PR_GetProtoByNumber
caller. bufsize number of bytes in the buffer parameter. the buffer must be at least pr_netdb_buf_size bytes. result on input, a pointer to a prnetaddr structure. on output, this structure is filled in by the runtime if the function returns pr_success. returns the function returns one of the following values: if successful, pr_success. if unsuccessful, pr_failure. you can retrieve the reason for the failure by calling pr_geterror. ...
PR_GetSockName
gets network address for a specified socket. syntax #include <prio.h> prstatus pr_getsockname( prfiledesc *fd, prnetaddr *addr); parameters the function has the following parameters: fd a pointer to a prfiledesc object representing the socket. addr on return, the address of the socket. returns if successful, pr_success. if unsuccessful, pr_failure. the reason for the failure can be obtained by calling pr_geterror. ...
PR_GetSocketOption
g the socket whose options are to be retrieved. data a pointer to a structure of type prsocketoptiondata. on input, the option field of this structure must be set to indicate which socket option to retrieve for the socket represented by the fd parameter. on output, this structure contains the requested socket option data. returns if successful, pr_success. if unsuccessful, pr_failure. the reason for the failure can be obtained by calling pr_geterror. ...
PR_InitializeNetAddr
r to be assigned in the network address structure. the value is specified in host byte order. addr a pointer to the prnetaddr structure to be manipulated. returns the function returns one of the following values: if successful, pr_success. if unsuccessful, pr_failure. this may occur, for example, if the value of val is not within the ranges defined by prnetaddrvalue. you can retrieve the reason for the failure by calling pr_geterror. description pr_initializenetaddr allows the assignment of special network address values and the port number, while also setting the state that indicates the version of the address being used. the special network address values are identified by the enum prnetaddrvalue: typedef enum prnetaddrvalue{ pr_ipaddrnull, pr_ipaddrany, pr_ipaddrloopback }...
PR_Interrupt
description the purpose of pr_interrupt is to request that a thread performing some task stop what it is doing and return to some control point. it is assumed that a control point has been mutually arranged between the thread doing the interrupting and the thread being interrupted. when the interrupted thread reaches the prearranged point, it can communicate with its peer to discover the real reason behind the change in plans. the interrupt request remains in the thread's state until it is delivered exactly once or explicitly canceled. the interrupted thread returns pr_failure (-1) with an error code (see pr_geterror) for blocking operations that return a prstatus (such as i/o operations, monitor waits, or waiting on a condition). to check whether the thread was interrupted, compare the res...
PR_LoadLibrary
erenced library. syntax #include <prlink.h> prlibrary* pr_loadlibrary(const char *name); parameters the function has this parameter: name a platform-dependent character array that names the library to be loaded, as returned by pr_getlibraryname. returns if successful, returns a reference to an opaque prlibrary object. if the operation fails, returns null. use pr_geterror to find the reason for the failure. description this function loads and returns a reference to the specified library. the returned reference becomes the library's identity. the function suppresses duplicate loading if the library is already known by the runtime. each call to pr_loadlibrary must be paired with a corresponding call to pr_unloadlibrary in order to return the runtime to its original state. ...
PR_MkDir
t may be applicable to other platforms in the future. possible values include the following: 00400. read by owner. 00200. write by owner. 00100. search by owner. 00040. read by group. 00020. write by group. 00010. search by group. 00004. read by others. 00002. write by others. 00001. search by others. returns if successful, pr_success. if unsuccessful, pr_failure. the actual reason can be retrieved via pr_geterror. description pr_mkdir creates a new directory with the pathname name. all the path components up to but not including the leaf component must already exist. for example, if the pathname of the directory to be created is a/b/c/d, the directory a/b/c must already exist. see also pr_rmdir ...
PR_NOT_REACHED
terminates the calling application with a message to the log. syntax #include <prlog.h> void pr_not_reached(const char *_reasonstr); parameters the macro has this parameter: reasonstr a string that describes why you should not have reached this statement. returns nothing description this macro writes the specified reason string to the log and terminates the application. this macro compiles to nothing if compile-time options are not specified to enable logging. ...
PR_NetAddrToString
ar *string, pruint32 size); parameters the function has the following parameters: addr a pointer to the network address to be converted. string a buffer that will hold the converted string on output. size the size of the result buffer (string). returns the function returns one of the following values: if successful, pr_success. if unsuccessful, pr_failure. you can retrieve the reason for the failure by calling pr_geterror. description the network address to be converted (addr) may be either an ipv4 or ipv6 address structure, assuming that the nspr library and the host system are both configured to utilize ipv6 addressing. if addr is an ipv4 address, size needs to be at least 16. if addr is an ipv6 address, size needs to be at least 46. ...
PR_OpenSharedMemory
f not exist */ #define pr_shm_excl 0x2 /* fail if already exists */ parameters the function has the following parameters: name the name of the shared memory segment. size the size of the shared memory segment. flags options for creating the shared memory. mode same as passed to pr_open. returns pointer to opaque structure prsharedmemory, or null if an error occurs. retrieve the reason for the failure by calling pr_geterror and pr_getoserror. description pr_opensharedmemory creates a new shared memory segment or associates a previously created memory segment with the specified name. when parameter create is (pr_shm_excl | pr_shm_create) and the shared memory already exists, the function returns null with the error set to pr_file_exists_error. when parameter create is pr_shm_...
PR_Poll
ll will block waiting for i/o to become ready. if this time expires without any i/o becoming ready, pr_poll returns zero. returns the function returns one of these values: if successful, the function returns a positive number indicating the number of prpolldesc structures in pds that have events. the value 0 indicates the function timed out. the value -1 indicates the function failed. the reason for the failure can be obtained by calling pr_geterror. description this function returns as soon as i/o is ready on one or more of the underlying socket objects. a count of the number of ready descriptors is returned unless a timeout occurs, in which case zero is returned. the in_flags field of the prpolldesc data structure should be set to the i/o events (readable, writable, exception, or s...
PR_PushIOLayer
stack above which the new layer is to be added. layer a pointer to a prfiledesc object representing the new layer to be added to the stack. returns the function returns one of the following values: if the layer is successfully pushed onto the stack, pr_success. if the layer is not successfully pushed onto the stack, pr_failure. use pr_geterror to get additional information regarding the reason for the failure. description a file descriptor for a layer (possibly allocated using pr_createiolayerstub) may be pushed onto an existing stack of file descriptors at any time. the new layer is inserted into the stack just above the layer with the identity specified by id. even if the id parameter indicates the topmost layer of the stack, the value of the file descriptor describing the origin...
PR_Read
sc object for the file or socket. buf a pointer to a buffer to hold the data read in. on output, the buffer contains the data. amount the size of buf (in bytes). returns one of the following values: a positive number indicates the number of bytes actually read in. the value 0 means end of file is reached or the network connection is closed. the value -1 indicates a failure. to get the reason for the failure, call pr_geterror. description the thread invoking pr_read blocks until it encounters an end-of-stream indication, some positive number of bytes (but no more than amount bytes) are read in, or an error occurs. ...
PR_ReadDir
ectory. pr_skip_both. skip both "." and ".." pr_skip_hidden. skip hidden files. on windows platforms and the mac os, this value identifies files with the "hidden" attribute set. on unix platform, this value identifies files whose names begin with a period ("."). returns a pointer to the next entry in the directory. if the end of the directory is reached or an error occurs, null. the reason can be retrieved via pr_geterror. description pr_readdir returns a pointer to a directory entry structure: struct prdirentry { const char *name; }; typedef struct prdirentry prdirentry; the structure has the following field: name name of entry, relative to directory name. the flags parameter is an enum of type prdirflags: typedef enum prdirflags { pr_skip_none = 0x0, pr_ski...
PR_Recv
nt the size of buf (in bytes). flags must be zero or pr_msg_peek. timeout a value of type printervaltime specifying the time limit for completion of the receive operation. returns the function returns one of the following values: a positive number indicates the number of bytes actually received. the value 0 means the network connection is closed. the value -1 indicates a failure. the reason for the failure can be obtained by calling pr_geterror. description pr_recv blocks until some positive number of bytes are transferred, a timeout occurs, or an error occurs. no more than amount bytes will be transferred. ...
PR_RecvFrom
at will be filled in with the address of the sending peer on return. timeout a value of type printervaltime specifying the time limit for completion of the receive operation. returns the function returns one of the following values: a positive number indicates the number of bytes actually received. the value 0 means the network connection is closed. the value -1 indicates a failure. the reason for the failure can be obtained by calling pr_geterror. description pr_recvfrom receives up to a specified number of bytes from socket, which may or may not be connected. the operation blocks until one or more bytes are transferred, a timeout has occurred, or there is an error. no more than amount bytes will be transferred. pr_recvfrom is usually used with a udp socket. ...
PR_RmDir
removes a directory with a specified name. syntax #include <prio.h> prstatus pr_rmdir(const char *name); parameter the function has the following parameter: name the name of the directory to be removed. returns if successful, pr_success. if unsuccessful, pr_failure. the actual reason can be retrieved via pr_geterror. description pr_rmdir removes the directory specified by the pathname name. the directory must be empty. if the directory is not empty, pr_rmdir fails and pr_geterror returns the error code pr_directory_not_empty_error. see also pr_mkdir ...
PR_Send
s obsolete parameter must always be zero. timeout a value of type printervaltime specifying the time limit for completion of the receive operation. returns the function returns one of the following values: a positive number indicates the number of bytes successfully sent. if the parameter fd is a blocking socket, this number must always equal amount. the value -1 indicates a failure. the reason for the failure can be obtained by calling pr_geterror. description pr_send blocks until all bytes are sent, a timeout occurs, or an error occurs. ...
PR_SendTo
buf (in bytes). flags this obsolete parameter must always be zero. addr a pointer to the address of the destination. timeout a value of type printervaltime specifying the time limit for completion of the receive operation. returns the function returns one of the following values: a positive number indicates the number of bytes successfully sent. the value -1 indicates a failure. the reason for the failure can be obtained by calling pr_geterror. description pr_sendto sends a specified number of bytes from a socket to the specified destination address. the calling thread blocks until all bytes are sent, a timeout has occurred, or there is an error. ...
PR_SetPollableEvent
set a pollable event. syntax nspr_api(prstatus) pr_setpollableevent(prfiledesc *event); parameter the function has the following parameter: event pointer to a prfiledesc structure previously created via a call to pr_newpollableevent. returns the function returns one of the following values: if successful, pr_success. if unsuccessful, pr_failure. the reason for the failure can be retrieved via pr_geterror. ...
PR_SetSocketOption
description on input, the caller must set both the option and value fields of the prsocketoptiondata object pointed to by the data parameter. ...
PR_StringToNetAddr
address. syntax #include <prnetdb.h> prstatus pr_stringtonetaddr( const char *string, prnetaddr *addr); parameters the function has the following parameters: string the string to be converted. addr on output, the equivalent network address. returns the function returns one of the following values: if successful, pr_success. if unsuccessful, pr_failure. you can retrieve the reason for the failure by calling pr_geterror. description for ipv4 addresses, the input string represents numbers in the internet standard "." notation. ipv6 addresses are indicated as strings using ":" characters separating octets, with numerous caveats for shortcutting (see rfc #1884). if the nspr library and the host are configured to support ipv6, both formats are supported. otherwise, use of an...
PR_TransmitFile
onnection should be closed immediately after successful transfer of the file. timeout time limit for completion of the transmit operation. returns a positive number indicates the number of bytes successfully written, including both the headers and the file. the value -1 indicates a failure. if an error occurs while sending the file, the pr_transmitfile_close_socket flag is ignored. the reason for the failure can be obtained by calling pr_geterror. description the pr_transmitfile function sends a complete file (sourcefile) across a connected socket (networksocket). if headers is non-null, pr_transmitfile sends the headers across the socket before sending the file. the enumeration prtransmitfileflags, used in the flags parameter, is defined as follows: typedef enum prtransmitfilefl...
PR_UnloadLibrary
unloads a library loaded with pr_loadlibrary. syntax #include <prlink.h> prstatus pr_unloadlibrary(prlibrary *lib); parameters the function has this parameter: lib a reference previously returned from pr_loadlibrary. returns the function returns one of the following values: if successful, pr_success. if unsuccessful, pr_failure. use pr_geterror to find the reason for the failure. description this function undoes the effect of a pr_loadlibrary. after calling this function, future references to the library using its identity as returned by pr_loadlibrary will be invalid. ...
PR_Wait
expression is false, the thread should wait. the thread should act on the data only when the expression is true. the boolean expression must be evaluated while in the monitor and within a loop. in pseudo-code, the sequence is as follows: pr_entermonitor(&ml); while (!expression) wait; ... act on the state change ... pr_exitmonitor(&ml); a thread can be resumed from a wait for a variety of reasons. the most obvious is that it was notified by another thread. if the value of timeout is not pr_interval_no_timeout, pr_wait resumes execution after the specified interval has expired. if a timeout value is used, the boolean expression must include elapsed time as part of the monitored data. resuming from the wait is merely an opportunity to evaluate the expression, not an assertion that the exp...
PR_WaitForPollableEvent
atomically unsetting the event before returning. syntax nspr_api(prstatus) pr_waitforpollableevent(prfiledesc *event); parameter the function has the following parameter: event pointer to a prfiledesc structure previously created via a call to pr_newpollableevent. returns the function returns one of the following values: if successful, pr_success. if unsuccessful, pr_failure. the reason for the failure can be retrieved via pr_geterror. ...
PR_Write
ction has the following parameters: fd a pointer to the prfiledesc object for a file or socket. buf a pointer to the buffer holding the data to be written. amount the amount of data, in bytes, to be written from the buffer. returns one of the following values: a positive number indicates the number of bytes successfully written. the value -1 indicates that the operation failed. the reason for the failure is obtained by calling pr_geterror. description the thread invoking pr_write blocks until all the data is written or the write operation fails. therefore, the return value is equal to either amount (success) or -1 (failure). note that if pr_write returns -1, some data (less than amount bytes) may have been written before an error occurred. ...
PR_Writev
ter than pr_max_iovector_size. if it is, the function will fail and the error will be set to pr_buffer_overflow_error. timeout a value of type printervaltime describing the time limit for completion of the entire write operation. returns one of the following values: a positive number indicates the number of bytes successfully written. the value -1 indicates that the operation failed. the reason for the failure can be obtained by calling pr_geterror. description the thread calling pr_writev blocks until all the data is written or the write operation fails. therefore, the return value is equal to either the sum of all the buffer lengths (on success) or -1 (on failure). note that if pr_writev returns -1, part of the data may have been written before an error occurred. if the timeout par...
Certificate functions
6 and later cert_encodepolicyconstraintsextension mxr 3.12 and later cert_encodepolicymappingextension mxr 3.12 and later cert_encodesubjectkeyid mxr 3.12 and later cert_encodeusernotice mxr 3.12 and later cert_extractpublickey mxr 3.2 and later cert_findcertbyname mxr 3.2 and later cert_findcrlentryreasonexten mxr 3.12 and later cert_findcrlnumberexten mxr 3.12 and later cert_findnameconstraintsexten mxr 3.12 and later cert_filtercertlistbycanames mxr 3.4 and later cert_filtercertlistbyusage mxr 3.4 and later cert_filtercertlistforusercerts mxr 3.6 and later cert_findcertbydercert mxr 3.2 and later ...
Cryptography functions
mxr 3.2 and later pk11_getblocksize mxr 3.2 and later pk11_getcertfromprivatekey mxr 3.9.3 and later pk11_getcurrentwrapindex mxr 3.2 and later pk11_getdefaultarray mxr 3.8 and later pk11_getdefaultflags mxr 3.8 and later pk11_getdisabledreason mxr 3.8 and later pk11_getfirstsafe mxr 3.2 and later pk11_getinternalkeyslot mxr 3.2 and later pk11_getinternalslot mxr 3.2 and later pk11_getkeygen mxr 3.4 and later pk11_getkeylength mxr 3.2 and later pk11_getkeystrength m...
JSS FAQ
Mozilla › Projects › NSS › JSS › JSS FAQ
named. in general, a key is a handle to an underlying object on a pkcs #11 token, not merely a java object residing in memory. symmetric key usage: basically encrypt/decrypt is for data and wrap/unwrap is for keys. jss 3.2 has jca support. when will jss have jsse support? not in the near future due to pluggability is disabled in the jsse version included in j2se 1.4.x for export control reasons. ...
JSS Provider Notes
n, implemented in software or hardware. there is no clean way to specify this token through the jca api. by default, the jss provider carries out all operations except messagedigest on the internal key storage token, a software token included in jss/nss. messagedigest operations take place by default on the internal crypto token, another internal software token in jss/nss. there is no good design reason for this difference, but it is necessitated by a quirk in the nss implementation. in order to use a different token, use cryptomanager.setthreadtoken(). this sets the token to be used by the jss jca provider in the current thread. when you call getinstance() on a jca class, the jss provider checks the current per-thread default token (by calling cryptomanager.getthreadtoken()) and instructs the...
Mozilla-JSS JCA Provider notes
n, implemented in software or hardware. there is no clean way to specify this token through the jca api. by default, the jss provider carries out all operations except messagedigest on the internal key storage token, a software token included in jss/nss. messagedigest operations take place by default on the internal crypto token, another internal software token in jss/nss. there is no good design reason for this difference, but it is necessitated by a quirk in the nss implementation. in order to use a different token, use cryptomanager.setthreadtoken(). this sets the token to be used by the jss jca provider in the current thread. when you call getinstance() on a jca class, the jss provider checks the current per-thread default token (by calling cryptomanager.getthreadtoken()) and instructs the n...
NSS_3.12.2_release_notes.html
bug 432260: [[@ pkix_pl_httpdefaultclient_hdrcheckcomplete - pkix_pl_memcpy] crashes when there is no content-length header in t...
NSS 3.12.6 release notes
ed the following bugs have been fixed in nss 3.12.6. ...
NSS 3.20 release notes
e - enumerates the set of dhe parameters embedded in nss that can be used with function ssl_dhegroupprefset new macros in ssl.h ssl_enable_server_dhe - a socket option user to enable or disable dhe ciphersuites for a server socket notable changes in nss 3.20 the tls library has been extended to support dhe ciphersuites in server applications. for backward compatibility reasons, the server side implementation of the tls library keeps all dhe ciphersuites disabled by default. they can be enabled with the new socket option ssl_enable_server_dhe and the ssl_optionset or the ssl_optionsetdefault api. the server side implementation of the tls does not support session tickets while using a dhe ciphersuite (see bug 1174677). support for the following ciphersuites has been ...
NSS 3.28 release notes
ffects tls 1.2. nss will now only generate signatures with the combinations of hash and signature scheme that are defined in tls 1.3, even when negotiating tls 1.2. this means that sha-256 will only be used with p-256 ecdsa certificates, sha-384 with p-384 certificates, and sha-512 with p-521 certificates. sha-1 is permitted (in tls 1.2 only) with any certificate for backward compatibility reasons. new functions to configure signature schemes are provided: ssl_signatureschemeprefset, ssl_signatureschemeprefget. the old ssl_signatureprefset and ssl_signatureprefset functions are now deprecated. nss will now no longer assume that default signature schemes are supported by a peer if there was no commonly supported signature scheme. nss will now check if rsa-pss signing is support...
PKCS11 FAQ
Mozilla › Projects › NSS › PKCS11 › FAQ
d having to prompt for a password when performing an rsa verify operation, des encryption, and so on. therefore, nss can move keys around when necessary and possible. when operating in fips mode, moving keys is significantly harder. in this case nss uses a single token to handle both key and cert storage and crypto operations. in general, you not should use different slots unless you have a good reason. much of nss's token selection is based on where the key involved is currently stored. if the token that has your private keys doesn't also do symmetric operations, for example, it's likely that the internal token will end up doing the symmetric operations. is the pkcs #11 module supplied with nss accessible through a shared library? yes, the token is call softokn3 (softokn3.dll on windows, lib...
sslerr.html
ation code." the remote system has reported that it received a message with a bad message authentication code from the local system. this may indicate that an attack on that server is underway. ssl_error_bad_cert_alert -12271 "ssl peer cannot verify your certificate." the remote system has received a certificate from the local system, and has rejected it for some reason. ssl_error_revoked_cert_alert -12270 "ssl peer rejected your certificate as revoked." the remote system has received a certificate from the local system, and has determined that the certificate has been revoked. ssl_error_expired_cert_alert -12269 "ssl peer rejected your certificate as expired." the remote system has received a certifica...
NSS Tools pk12util
only the protection of the private keys but also the certificate and meta-data associated with the keys. password based encryption is used to protect private keys on export to a pkcs #12 file and also the entire package when allowed. if no algorithm is specified, the tool defaults to using "pkcs12 v2 pbe with sha1 and 3key triple des-cbc" for private key encryption. for historical export control reasons "pkcs12 v2 pbe with sha1 and 40 bit rc4" is the default for the overall package encryption when not in fips mode and no package encryption when in fips mode. the private key is always protected with strong encryption by default. a list of ciphers follows. symmetric cbc ciphers for pkcs #5 v2: "des_cbc" "rc2-cbc" "rc5-cbcpad" "des-ede3-cbc" --- default for key encryption "aes-128-cbc"...
Performance Hints
should be used for the first n entries of the array. similarly, new array("a", "b", "c") or ["a", "b", "c"] will cause a 3-element array to be allocated to hold the contents of the javascript array. eval and new function avoid calling eval when possible. calls to eval are slow because the script being executed must be compiled. constructing a new function object can be slow for the same reason, while function expressions are more efficient because the function can be compiled. for example, the code function myobject(a) { this.s = a; this.tostring = new function("return this.s"); } could be written more efficiently as function myobject(a) { this.s = a; this.tostring = function () { return this.s } } beginning with rhino 1.4 release 2, code passed to eval and new fu...
Shumway
ents (such as those surrounding flash drm) get in the way. some of its current limitations are just temporary, however. there are a few situations where a user may use shumway to view your content: their platform does not support adobe flash player. the user did not install adobe flash player. the user has adobe flash player disabled (or set to "click-to-enable") for performance or security reasons. there might be a time where users want to experience your content but flash is no longer supported by adobe. to emphasize a point: the current behavior is that shumway works on any swf file unless (or until) the adobe flash player plugin is activated. shumway is made with the same constraints as any website. users who disable flash because of security or performance concerns can still see co...
Creating JavaScript tests
ur heavily loaded test machines, lowering the value of our test suite for everyone. just don't do it, it's never worth it. do not add performance tests to the test suite. it is not generally even possible to tell if the speed of any particular feature is going to be important in the real world without running a real-world benchmark. it is very hard to write a good real-world benchmark. for this reason, the best place to find out if a change is performance sensitive is on arewefastyet.com. focus on writing fast, light tests that cover a single feature. there is basically no cost to adding a new test, so add as many feature tests as needed to cover each feature orthogonally. remember that whenever a test fails, someone -- probably you -- is going to have to figure out what went wrong. testing ...
Index
cified class, with the specified prototype and parent, then invokes a constructor function to initialize the new object. cx is a pointer to a context associated with the runtime in which to create the new object. clasp is a pointer to the class of object to create. proto and parent may specify objects to be used as the new object's prototype and parent. if either is null, the engine tries to find reasonable defaults. 218 js_contextiterator jsapi reference, spidermonkey js_contextiterator steps through the set of contexts associated with the runtime rt. each call to js_contextiterator returns the next context in the cycle. 219 js_convertarguments jsapi reference, obsolete, spidermonkey js_convertarguments provides a convenient way to translate a series of...
Bytecode Descriptions
ripts. gen must be the internal generator object for the current frame. after this instruction, the script should suspend itself with await (rather than exiting any other way). the result promise is the async function's result promise, gen->as<asyncfunctiongeneratorobject>().promise(). implements: await, steps 2-9. asyncresolve operands: (asyncfunctionresolvekind fulfillorreject) stack: valueorreason, gen ⇒ promise resolve or reject the current async function's result promise with 'valueorreason'. this instruction must appear only in non-generator async function scripts. gen must be the internal generator object for the current frame. this instruction must run at most once per async function call, as resolving/rejecting an already resolved/rejected promise is not permitted. the result promi...
Garbage collection
y roots". gray roots are used by the gecko cycle collector to find cycles that pass through the js heap. handle in our gc, a handle is a pointer that has elsewhere been registered by a root. in other words, it is an updatable pointer to a gc thing (it is essentially a cell** that the gc knows about.) root a starting point to the gc graph traversal, a root is known to be alive for some external reason (one other than being reachable by some other part of the gc heap.) weak pointer in common cs terminology, a weak pointer is one that doesn't keep the pointed-to value live for gc purposes. typically, a weak pointer value has a get() method that returns a null pointer if the object has been gc'd. in gecko/spidermonkey, a weak pointer is a pointer to an object that can be gc'd that is not marked...
Property cache
ate without them, so it is disabled permanently. see bug 440834. property cache entries each entry in the property cache hash table is either populated or not; unpopulated entries have .kpc == null. if an entry is populated, the .kpc field points to the bytecode instruction at which it was populated. the entry is valid only for subsequent lookups that occur at the same instruction, for several reasons: the script, not the property cache entry, contains the id of the property being accessed. a property cache entry could be valid for a getprop but not a setprop, e.g. because the property has a setter and not a getter; or vice versa. lookups for jof_name instructions are quite different from ordinary property lookups: name lookups follow the scope chain and the prototype chain, whereas the ...
Tracing JIT
ace monitor and recorded in the monitor's trace recorder. recording mode is temporary -- ideally it only lasts as long as it takes to record a single iteration of a loop in the interpreter -- and can end in a number of ways. all transitions out of recording mode eventually involve returning to monitoring mode: if the recorder is asked to record a bytecode that it cannot, for various low-level reasons, faithfully record, the recorder may choose to abort the recording. aborting a recording is always an option in tracemonkey, and on abort the monitor simply discards the recorder and its fragment and returns to monitoring mode. the monitor also keeps track of how many times it has attempted to record a trace starting at each pc value, so if a particular pc causes too many aborted recordings, the...
SpiderMonkey Internals
f two table sizes. jshash resolves collisions via chaining, so each entry burns a malloc and can fragment the heap. jsdhash uses open addressing. jslong.cpp, jslong.h 64-bit integer emulation, and compatible macros that use intrinsic c types, like long long, on platforms where they exist (most everywhere, these days). jsprf.* portable, buffer-overrun-resistant sprintf and friends. for no good reason save lack of time, the %e, %f, and %g formats cause your system's native sprintf, rather than js_dtoa(), to be used. this bug doesn't affect spidermonkey, because it uses its own js_dtoa() call in jsnum.cpp to convert from double to string, but it's a bug that we'll fix later, and one you should be aware of if you intend to use a js_*printf() function with your own floating type arguments - vario...
JIT Optimization Outcomes
y, uses different optimization strategies to speed up various operations. the most typical operations that are relevant for fast program execution are property accesses and function calls. this page documents the meaning of different optimization outcomes. general outcomes general outcomes shared between various optimization strategies. genericfailure the optimization attempt failed, and the reason was not recorded. genericsuccess optimization succeeded. disabled the optimization has been explicitly disallowed. notypeinfo optimization failed because there was no type information associated with an object containing the property. this failure mode is unlikely and occurs if the target object is obtained in some roundabout way. noanalysisinfo todo noshapeinfo the baseline compiler re...
JS_ConstructObject
cified class, with the specified prototype and parent, then invokes a constructor function to initialize the new object. cx is a pointer to a context associated with the runtime in which to create the new object. clasp is a pointer to the class of object to create. proto and parent may specify objects to be used as the new object's prototype and parent. if either is null, the engine tries to find reasonable defaults. js_constructobjectwitharguments is the same but additionally passes zero or more arguments to the constructor. neither of these functions is quite like the javascript new keyword. for details on how we find the appropriate constructor and default prototype, see js_newobject: choosing a default prototype. roughly speaking, we use parent or cx to find a global object, and then fin...
JS_InitClass
erties and functions. the jsclass is an internal data structure that is not exposed outside the javascript engine. it specifies the name of the class, its flags, and its property access functions. these include native c functions for instance finalization, adding and deleting properties, getting and setting property values, and enumerating, converting, and resolving properties. the jsapi provides reasonable default behavior for all of these; ordinarily you don't want to overload any of them. after a successful call to js_initclass, javascript code can see and manipulate the class's constructor and prototype just as if it were an ordinary javascript function with a prototype property. javascript code can create new instances using the new keyword. classes can have methods and properties that are ...
Shell global objects
undefined and causes the firing of any onpromisesettled hooks set on debugger instances that are observing the given promise's global as a debuggee. getwaitforallpromise(densepromisesarray) calls the getwaitforallpromise jsapi function and returns the result promise. resolvepromise(promise, resolution) resolve a promise by calling the jsapi function js::resolvepromise. rejectpromise(promise, reason) reject a promise by calling the jsapi function js::rejectpromise. functions available only if spidermonkey_promise is not defined makefakepromise() create an object whose [[class]] name is 'promise' and call js::dbg::onnewpromise on it before returning it. it doesn't actually have any of the other behavior associated with promises. settlefakepromise(promise) 'settle' a promise created b...
Thread Sanitizer
e tsan instrumentation is implemented as an llvm pass and integrated into clang. the version of clang you need to use depends on what firefox release you are compiling if you are building from mozilla-central, you must use clang 3.6 or later. clang 3.4 + tsan cannot compile firefox due to an internal compiler error; some versions of clang 3.5 packaged by linux distros do not work for the same reason. you can check which version of clang you have by running the command: clang -v if you are not building from mozilla-central and are building firefox 39 or earlier, you must use clang 3.3. you can find precompiled binaries for llvm/clang 3.3 on the llvm releases page. we recommend using clang 3.6 or later. building firefox getting the source if you don't have a source code repository...
Web Replay
the developer tools can be used to interact with this tab in the same way as a recording tab, though playing forward to the end will pause the tab instead of allowing further recording. save recording and replay on a different machine (partially implemented) recordings can be replayed on a different machine from the one which recorded them. this requires using the same build of firefox and a reasonably similar version of the operating system; otherwise the tab will probably crash. this feature has had little testing or polishing and there is not yet a good definition of 'reasonably similar'. time travel features this section describes extensions to the developer tools that use time travel to help debug a recording/replaying tab. step back when paused, the reverse step button in the deb...
Redis Tips
zsets membership sets, bitstrings state hashes heartbeats zsets hit counters zsets message broadcast pubsub search reverse indexes (never use keys in production) documentation redis has fantastic documentation. yet redis is so easy to learn and use that you'll seldom feel you need to consult it. there are three reasons to look at the docs for every command you use. time complexity - each command's complexity is given in big-o notation. this is immensely helpful. related commands - an ever-growing list of related commands is given on the right-hand side of the page. recipes - at the bottom of many pages is a section that gives usage patterns or recipes for the command under discussion. there are many ins...
Exploitable crashes
hree things, in order: look at the top frame of the stack trace. if you see a hex address such as 0x292c2830 rather than a function name such as nslistboxbodyframe::getrowcount at the top of the stack, a bug has caused the program to transfer control to a "random" part of memory that isn't part of the program. these crashes are almost always exploitable to run arbitrary code. look at the crash reason, which will usually be something like "kern_protection_failure (0x0002) at 0x00000000". this is typically located right above the stack trace. the last number, in this case 0x00000000, is the memory address firefox was prevented from accessing. if the address is always zero (or close to zero, such as 0x0000001c), it's probably a null dereference bug. these bugs cause the browser to crash, but the...
Secure Development Guidelines
strncpy does not guarantee \0 termination. strncat confusing size argument; can write 1 byte beyond the size. snprintf, vsnprintf return value differs on various platforms. alloca never use this. calling alloca() with a user-controlled size == game over. use malloc() i...
Animated PNG graphics
Mozilla › Tech › APNG
= 'ihdr' height the delay_num and delay_den parameters together specify a fraction indicating the time to display the current frame, in seconds. 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). if the the value of the numerator is 0 the decoder should render the next frame as quickly as possible, though viewers may impose a reasonable lower bound. frame timings should be independent of the time required for decoding and display of each frame, so that animations will run at the same rate regardless of the performance of the decoder implementation. dispose_op specifies how the output buffer should be changed at the end of the delay (before rendering the next frame). valid values for dispose_op are: value cons...
Places Expiration
expiration is handled in toolkit/components/places/nsplacesexpiration.js. algorithm expiration is based on hardware specs, specifically on memory size and available disk space. this means on mobile and old systems expiration will be more aggressive than on high-end hardware, to try keep the database size at a reasonable (and performant) value. all of expiration uses the storage async api, that ensures i/o is in a separate thread, plus it won't block any read thanks to the use of the wal journaling system. common expiration runs on a timer, every 3 minutes and uses a simple adaptive algorithm: if the last step was unable to expire enough entries the next one will expire more entries, otherwise if the previous step completed the cleanup the next step will be delayed. this ensures expir...
Querying Places
can also be mapped to showing and hiding menus. to get at a container's contents, you must first open the container. most container types populate themselves lazily, so opening a container actually corresponds to executing the given query. while a container is open, it will listen to the history and bookmarks systems' notifications and modify their contents to keep themselves up-to-date. for this reason, it is best to close a container as soon as you are done with it, since it will give better performance. if you close a container and re-open it before any history or bookmark change notifications come, the results will generally still be there and this operation will be fast. this example uses the places history service to display all the titles of the history pages. // queries parameters (e.g...
Avoiding leaks in JavaScript XPCOM components
_element, _filterradiogroup, true); while (iterator.nextnode()) radiochildren.push(iterator.currentnode); return this.mradiochildren = radiochildren; in this example, the iterator object is an xpcom object that is wrapped so the javascript code can use it. the _filterradiogroup object is a javascript function that is wrapped so that xpcom code can use it. the reason closures matter here is that the _filterradiogroup function has access to the iterator variable. (var declarations inside javascript functions are function-scope, including the part of the function before the declaration.) this means that the value of iterator, the wrapper for the native tree walker, is reachable from the function. but the tree walker owns a reference to the wrapper for that func...
Starting WebLock
on to keep things simple. the first step in this implementation phase, then, is to create the functionality that accesses this weblock white list and uses its data to determine which domains are allowed and which are to be blocked. for this, we need to use the file interfaces available in xpcom. file interfaces files and directories are abstracted and encapsulated by interfaces. there are a few reasons for not using strings to represent file locations, but the most important one is that not all file systems can be represented by a series of characters separated by a slash. on the macintosh platform, for example, files are represented as a triplet - two numbers and one string - so using a string on the macintosh does not adequately identify files on that operating system. nsifile, the file int...
Components.utils.importGlobalProperties
le.log(atob(encoded)); // "hello" alternative methods if importglobalproperties does not support the targeted firefox version, here are some alternative methods to import these objects. import from jsm this method worked until blob and file were no longer apart of jsm modules. it is suspected this works up till firefox 35. this imports blob, file, along with the regular services. the reason this works is because js code modules actually have blob and file. cu.import() will return the full global of a code module. knowing that, we can just get a valid blob by importing a known module that has the objects, such as services.jsm const {blob, file, services} = cu.import("resource://gre/modules/services.jsm", {}); reference: stackoverflow :: use blob on firefox add-on hiddendomwindow ...
imgIContainer
container(); parameters none. return value missing description exceptions thrown missing exception missing description violates the xpcom interface guidelines getrootlayoutframe() if this image is type_vector, that is really an embedded svg document, and this method returns a pointer to the root nsiframe of that document. if not (or if the root nsiframe is not available for some reason), this method returns nsnull. "notxpcom" for convenience, since we have no need for nsresult return-val. nsiframe getrootlayoutframe(); parameters none. return value missing description exceptions thrown missing exception missing description violates the xpcom interface guidelines gettype() direct c++ accessor for 'type' attribute, for convenience. pruint16 gettype(); parameter...
imgIRequest
ilable 0x1 we received enough image data from the network or filesystem that we know the width and height of the image, and have thus called setsize() on the container. status_load_partial 0x2 used internally by imgrequest to flag that a request is being cancelled as a result of a failure of a proxy holder and not an internal failure. at least i think that's what it does. regardless, there's no reason for this flag to be public, and it should either go away or become a private state flag within imgrequest. do not rely on it. status_load_complete 0x4 the data has been fully loaded to memory, but not necessarily fully decoded. status_error 0x8 an error occurred loading the image. status_frame_complete 0x10 the first frame has been completely decoded. status_decode_complete 0x20 the whole...
mozIColorAnalyzer
preference is given to colors that are more interesting. it avoids the background color if it can be discerned and ignores sufficiently transparent colors. this is intended to be used on favicon images. larger images take longer to process, especially those with a larger number of unique colors. if imageuri points to an image that has more than 128^2 pixels, this method will fail for performance reasons before analyzing it. void findrepresentativecolor( in nsiuri imageuri, in mozirepresentativecolorcallback callback ); parameters imageuri a uri pointing to the image - ideally a data: uri, but any scheme that will load when setting the src attribute of a dom img element should work. callback function to call when the representative color is found or an error occu...
nsIApplicationCache
d this cache's group as its manifest. item_dynamic 8 this item was added to the cache using the dynamic scripting api. item_foreign 16 this item was listed in the application manifest, but named a different cache group as its manifest. item_fallback 32 this item was listed as a fallback entry. item_opportunistic 64 this item matched an opportunistic cache namespace and was cached for that reason. methods activate() makes this cache the active application cache for this group. future loads associated with this group will come from this cache. other caches from this cache group will be deactivated. void activate(); parameters none. addnamespaces() add a set of namespace entries to the application cache. void addnamespaces( in nsiarray namespaces ); parameters namespaces an nsiarray...
nsIBrowserHistory
in nsiuri auri); obsolete since gecko 9.0 note: the markpageasfollowedlink and markpageastyped methods were moved to nsinavhistoryservice in gecko 22.0 so that all markpageas* methods can be found in one interface. attributes attribute type description count obsolete since gecko 15.0 pruint32 indicates if there are entries in global history. for performance reasons this does not return the real number of entries. read only. lastpagevisited obsolete since gecko 10.0 autf8string the last page that was visited in a top-level window. read only. note: the count attribute was removed in gecko 15.0 because it was only used to determine if there were any entries at all anyway, so the nsinavhistoryservice.hashistoryentries attribute is better ...
nsICancelable
netwerk/base/public/nsicancelable.idlscriptable this interface provides a means to cancel an operation that is in progress. 1.0 66 introduced gecko 1.8 inherits from: nsisupports last changed in gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0) method overview void cancel(in nsresult areason); methods cancel() call this method to request that this object abort whatever operation it may be performing. void cancel( in nsresult areason ); parameters areason a failure code indicating why the operation is being canceled. it is an error to pass a success code. ...
nsIChannel
whether or not the end consumer for this load has been determined. load_call_content_sniffers 21 if this flag is set, the channel should call the content sniffers as described in netwerk/build/nsnetcid.h about ns_content_sniffer_category. see nsicontentsniffer [en-us] note: channels may ignore this flag; however, new channel implementations should only do so with good reason. load_classify_uri 22 this flag tells the channel to use uri classifier service to check the uri when opening the channel. methods asyncopen() asynchronously open this channel. data is fed to the specified stream listener as it becomes available. the stream listener's methods are called on the thread that calls asyncopen and are not called until after asyncopen returns. i...
nsIConsoleService
against stack overflows from listeners which could log messages (this could be done inadvertently through listeners implemented in javascript), we do not call any listeners when another error is already being logged. void registerlistener( in nsiconsolelistener listener ); parameters listener the nsiconsolelistener to add. reset() to clear the message buffer (for example, for privacy reasons): void reset(); parameters none. note: console listeners expect you to log an empty string message before calling reset, so they too can clear their message buffers. (this also works before gecko 19.) unregisterlistener() deregisters a listener. void unregisterlistener( in nsiconsolelistener listener ); parameters listener the nsiconsolelistener to remove. examples retrieving ...
nsIContentSecurityPolicy
ng, in nsiuri selfuri ); parameters policystring selfuri scanrequestdata() called after the content security policy object is created to fill in the appropriate request and request header information needed in case a report needs to be sent. void scanrequestdata( in nsihttpchannel achannel ); parameters achannel sendreports() manually triggers violation report sending given a uri and reason. the uri may be null, in which case "self" is sent. void sendreports( in astring blockeduri, in astring violateddirective ); parameters blockeduri the uri that violated the policy. violateddirective the directive that was violated. shouldload() delegate method called by the service when sub-elements of the protected document are being loaded. given a bit of information about the request, d...
nsIDNSListener
...
nsIDOMEvent
. read only. defaultprevented boolean used to indicate whether preventdefault() has been called for this event. read only. eventphase unsigned short used to indicate which phase of event flow is currently being evaluated. read only. explicitoriginaltarget nsidomeventtarget the explicit original target of the event. if the event was retargeted for some reason other than an anonymous boundary crossing, this will be set to the target before the retargeting occurs. for example, mouse events are retargeted to their parent node when they happen over text nodes (bug 185889), and in that case .target will show the parent and .explicitoriginaltarget will show the text node. .explicitoriginaltarget differs from .originaltarget in that it will never contain ano...
nsIDocShell
eated this window. types are defined in constants. busyflags unsigned long current busy state for docshell. valid states are defined in constants. read only. canexecutescripts boolean whether this docshell can execute scripts based on its hierarchy. the rule of thumb here is that we disable js if this docshell or any of its parents disallow scripting, unless the only reason for js being disabled in this docshell is a parent docshell having a document that is in design mode. in that case, we explicitly allow scripting on the current docshell. read only. canvashasfocus boolean tells the docshell whether the canvas should have focus. called by the focus manager when the user tabs to the frame rather than an element. obsolete since gecko 1.9.2 c...
nsIDroppedLinkHandler
nt, out astring aname, [optional] in boolean adisallowinherit ); parameters aevent a drop event. aname the link title if it exists, or an empty string otherwise. return value a uri, or null if there is no valid link to be dropped. exceptions thrown ns_error_dom_security_err error will be thrown and the event canceled if the receiving target should not load the uri for security reasons. this will occur if the source of the drag initiated a link for dragging that it itself cannot access. this prevents a source document from tricking the user into a dragging a chrome url for example. droplinks() given a drop event, determines the link being dragged. if non-empty links array is returned the caller can, for instance, load it. if empty links array is returned, there is no valid ...
nsIFeedProgressListener
en processed and is available in the received nsifeedresult object. note: if the feed type is one of the entry or item-only types, this event will never be called. void handlefeedatfirstentry( in nsifeedresult result ); parameters result an nsifeedresult describing the feed at the point at which the first entry is found, but before processing it. handlestartfeed() called as soon as a reasonable start to a feed is detected; this lets your code know that the feed does appear to be an actual feed rather than some other sort of document. void handlestartfeed( in nsifeedresult result ); parameters result an nsifeedresult describing the current state of the feed at the moment parsing begins. reporterror() called by the feed processor when a fatal xml parsing error occurs, or i...
nsIFileInputStream
l be deleted again when it is closed again. close_on_eof 1<<2 if this is set, the file will close automatically when the end of the file is reached. reopen_on_rewind 1<<3 if this is set, the file will be reopened whenever seek(0) occurs. if the file is already open and the seek occurs, it will happen naturally. ...
nsIFileProtocolHandler
esulting string may contain url-escaped characters. geturlspecfromfile() converts the nsifile to the corresponding url string. if the nsifile is a local file, then the result will be a file:// url string. the resulting string may contain url-escaped characters. note: under some platforms this is a lossy conversion. note: callers should use geturlspecfromactualfile() if possible, for performance reasons. autf8string geturlspecfromfile( in nsifile file ); parameters file the nsifile to convert. return value corresponding url string. the resulting string may contain url-escaped characters. newfileuri() this method constructs a new file uri. nsiuri newfileuri( in nsifile afile ); parameters afile the nsifile to convert. return value a reference to a new nsiuri object. re...
nsIFileStreams
first delete, the file will be deleted again when it is closed again. close_on_eof 1<<2 if this is set, the file will close automatically when the end of the file is reached. reopen_on_rewind 1<<3 if this is set, the file will be reopened whenever seek(0) occurs. if the file is already open and the seek occurs, it will happen naturally. (the file will only be reopened if it is closed for some reason.) methods init() void init( in nsifile file, in long ioflags, in long perm, in long behaviorflags ); parameters file file to read from (must qi to nsilocalfile). ioflags file open flags listed in prio.h (see pr_open documentation) or -1 to open the file in default mode (pr_rdonly). perm file mode bits listed in prio.h or -1 to use the default value (0). behaviorflags flag...
nsIIOService
s banned. this involves consulting a list of unsafe ports, corresponding to network services that may be easily exploitable. 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. this gives the protocol handler ultimate control over its own security policy while ensuring reasonable, default protection. is similar to nsiprotocolhandler.allowport(). boolean allowport( in long aport, in string ascheme ); parameters aport the port to check ascheme the scheme for the protocol handler that could override the ioservice's decision. return value true if the port is allowed, false otherwise. extractscheme() utility to extract the scheme from a url string, consi...
nsIInputStream
blocking" (see the isnonblocking() method). a blocking input stream may suspend the calling thread in order to satisfy a call to close(), available(), read(), or readsegments(). a non-blocking input stream, on the other hand, must not block the calling thread of execution. note: blocking input streams are often read on a background thread to avoid locking up the main application thread. for this reason, it is generally the case that a blocking input stream should be implemented using thread-safe addref and release. method overview unsigned long available();deprecated since gecko 17.0 unsigned long long available(); void close(); boolean isnonblocking(); unsigned long read(in charptr abuf, in unsigned long acount); native code only! unsigne...
nsIJSON
ecodetojsval(in astring str, in jscontext cx); native code only! deprecated since gecko 2.0 methods decode() obsolete since gecko 7.0 (firefox 7.0 / thunderbird 7.0 / seamonkey 2.4) decodes a json string, returning the javascript object it represents. note: this method is more flexible than it should be, and accepts some not-correctly-structured json. for that reason, it has been removed in gecko 7.0. jsobject decode( in astring str ); parameters str the json string to decode. return value the original javascript object, reconstructed from the json string. decodetojsval() note: this method may only be used from native code, and provides a way to decode a json string to a jsval for use in your native code. don't forget to gcroot the result bef...
nsIJumpListItem
widget/public/nsijumplistitem.idlscriptable implements windows 7 taskbar jump list item interfaces. 1.0 66 introduced gecko 2.0 inherits from: nsisupports last changed in gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) note: to consumers: it's reasonable to expect we'll need support for other types of jump list items (an audio file, an email message, etc.). to add types, create the specific interface here, add an implementation class to winjumplistitem, and add support to addlistbuild and removed items processing. method overview boolean equals(in nsijumplistitem item); attributes attribute type description type short retrieves the jump list item type. read only. constants constant value description jumplist_item_empty 0 empty list ite...
nsIMsgWindow
her or not the existing message pane and header should be cleared before the html is displayed. stopurls() this is equivalent to calling stop(nsiwebnavigation::stop_network) on the nsiwebnavigation object. void stopurls(); closewindow() when the msg window is being unloaded from the content window, this notification can be used to force a flush on anything the message window hangs on. for some reason xpconnect is still hanging onto the message window even though all of our objects have let go of it. this forces a release. it clears out the content listener, the windowcommands, the statusfeedback and the docshell objects. void closewindow(); remarks see also ...
nsINavHistoryResultNode
s last changed in gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) attributes attribute type description accesscount unsigned long total number of times the uri has been accessed. for hosts, this is the total number of the children under it, rather than the total number of times the host has been accessed (getting that information would require an additional query, so for performance reasons that information isn't given by default). read only. bookmarkindex long when this item is in a bookmark folder (its parent is of type folder), this is the index into that folder at which this node resides. these indices start at 0 and increase in the order at which the nodes appear in the bookmark folder. for items that are not in a bookmark folder, this value is -1. read only. dateadded prt...
nsIOutputStream
snonblocking() method). a blocking output stream may suspend the calling thread in order to satisfy a call to close(), flush(), write(), writefrom(), or writesegments(). a non-blocking output stream, on the other hand, must not block the calling thread of execution. note: blocking output streams are often written to on a background thread to avoid locking up the main application thread. for this reason, it is generally the case that a blocking output stream should be implemented using thread-safe addref and release. method overview void close(); void flush(); boolean isnonblocking(); unsigned long write(in string abuf, in unsigned long acount); unsigned long writefrom(in nsiinputstream afromstream, in unsigned long acount); unsigned long w...
nsIPlacesImportExportService
or exporting places data. 1.0 66 introduced gecko 1.9 inherits from: nsisupports last changed in gecko 14.0 (firefox 14.0 / thunderbird 14.0 / seamonkey 2.11) in the past, this interface also offered methods for importing places data, but those methods are now part of the bookmarkhtmlutils.jsm javascript code module. the interface name has been kept for compatibility reasons for code using the export service. implemented by: @mozilla.org/import-export-service;1 as a service: var placesimportexportservice = components.classes["@mozilla.org/import-export-service;1"] .getservice(components.interfaces.nsiplacesimportexportservice); method overview void backupbookmarksfile(); void exporthtmltofile(in nsilocalfile afi...
nsIProtocolProxyCallback
solve. aproxyinfo the resulting proxy info or null if there is no associated proxy info for auri. as with the result of nsiprotocolproxyservice's resolve method, a null result implies that a direct connection should be used. astatus the status of the callback. this is a failure code if the request could not be satisfied, in which case the value of astatus indicates the reason for the failure and aproxyinfo will be null. the value returned from asyncresolve. see also nsicancelable nsiuri nsiproxyinfo nsiprotocolproxyservice ...
nsIRequestObserver
ify the end of an asynchronous request. this call is always preceded by a call to onstartrequest(). ...
nsISHistory
modifyindex a boolean flag that indicates if the current index of session history should be modified to the parameter index. exceptions thrown ns_ok history entry for the index is obtained successfully. ns_error_failure error in obtaining history entry for the given index. purgehistory() called to purge older documents from history. documents can be removed from session history for various reasons. for example to control memory usage of the browser, to prevent users from loading documents from history, to erase evidence of prior page loads and so on. void purgehistory( in long numentries ); parameters numentries the number of toplevel documents to be purged from history. during purge operation, the latest documents are maintained and older numentries documents are removed from...
nsISHistoryListener
ell when new pages are loaded in a frame or content area; for example by calling nsiwebnavigation.loaduri(). note: you can't cancel this operation. void onhistorynewentry( in nsiuri anewuri ); parameters anewuri the uri of the document to be added to session history. onhistorypurge() called when entries are removed from session history. entries can be removed from session history for various reasons; for example to control the browser's memory usage, to prevent users from loading documents from history, to erase evidence of prior page loads, etc. to purge documents from session history call nsishistory.purgehistory(). boolean onhistorypurge( in long anumentries ); parameters anumentries the number of entries to be removed from session history. return value true to allow the purge opera...
nsIServerSocketListener
versocket aserv, in nsresult astatus); methods onsocketaccepted() this method is called when a client connection is accepted. void onsocketaccepted( in nsiserversocket aserv, in nsisockettransport atransport ); parameters aserv the server socket. atransport the connected socket transport. onstoplistening() this method is called when the listening socket stops for some reason. the server socket is effectively dead after this notification. void onstoplistening( in nsiserversocket aserv, in nsresult astatus ); parameters aserv the server socket. astatus the reason why the server socket stopped listening. if the server socket was manually closed, then this value will be ns_binding_aborted. see also nsiserversocket nsisockettransport ...
nsISupports proxies
the same effect in a much simpler manner. for more information about alternatives, see making cross-thread calls using runnables. the following interface is now obsolete: nsiproxyobjectmanager. about xpcom proxies a proxy, in this context, is a stub object which enables a method of any class which is derived from nsisupports and has a typelib to be called on any in-process thread. the main reason for nsisupports proxies is that javascript and ui are on a single thread. when one is busy, the other is blocked. a good example of this is the old install.js scripts that were used in xpinstall in older mozilla versions. they from the majority of javascript code, which is small and can be quickly run. xpinstall installation scripts are sometimes very complex and can require long execution time d...
nsITraceableChannel
r = { 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); } ); } }; services.obs.addobserver(httpresponseobserver, 'http-on-examine-response', false); // services.obs.removeobserver(httpresponseobse...
nsIUpdateItem
the xpi file. can be null and if supplied must be in the format of "type:hash" (see the types in nsicryptohash and nsixpinstallmanager.initmanagerwithhashes(). read only. xpiurl astring the url of the xpi where this item can be downloaded. read only. constants item type constants constants representing types of update checks. constants that callers can use to indicate the reason for an add-on update check. internal code uses other constants in nsextensionmanager.js.in. constant gecko version description 1.8 1.8.1 1.9 1.9.1 1.9.2 type_app 0x01 type_extension 0x02 type_theme 0x04 type_locale 0x08 type_multi_xpi 0x20 type_addon type_extension...
nsIUploadChannel
se implement nsiinputstream.readsegments() implement nsiseekablestream.seek(). history here is that we need to support both streams that already have headers (for example, content-type and content-length) information prepended to the stream (by plugins) as well as clients (composer, uploading application) that want to upload data streams without any knowledge of protocol specifications. for this reason, we have a special meaning for the acontenttype parameter. void setuploadstream( in nsiinputstream astream, in acstring acontenttype, in long acontentlength ); parameters astream the stream to be uploaded by this channel. acontenttype if acontenttype is empty, the protocol will assume that no content headers are to be added to the uploaded stream and that any required headers are already ...
nsIWebProgressListener
in nsiwebprogress awebprogress, in nsirequest arequest, in nsiuri alocation, [optional] in unsigned long aflags ); parameters awebprogress the nsiwebprogress instance that fired the notification. arequest the associated nsirequest. this may be null in some cases. alocation the uri of the location that is being loaded. aflags this is a value which explains the situation or the reason why the location has changed. optional from gecko 11 onprogresschange() notification that the progress has changed for one of the requests associated with awebprogress. progress totals are reset to zero when all requests in awebprogress complete (corresponding to onstatechange() being called with astateflags including the state_stop and state_is_window flags). note: if any progress value is u...
nsIWindowMediator
er in windowmediator's internal state or with the window. note: it compares the nsixulwindow to nsiwidgets. a pure interface would use all nsixulwindows. but we expect this to be called from callbacks originating in native window code. they are expected to hand us comparison values which are pulled from general storage in the native widget, and may not correspond to an nsiwidget at all. for that reason this interface requires only objects one step removed from the native window (nsiwidgets), and its implementation must be very understanding of what may be completely invalid pointers in those parameters. boolean calculatezposition( in nsixulwindow inwindow, in unsigned long inposition, in nsiwidget inbelow, out unsigned long outposition, out nsiwidget outbelow ); parameters inwin...
nsIXMLHttpRequestEventTarget
ion is canceled by the user. onerror nsidomeventlistener a javascript function object that gets invoked if the operation fails to complete due to an error. onload nsidomeventlistener a javascript function object that gets invoked when the operation is successfully completed. onloadend nsidomeventlistener a javascript function object that gets invoked when the operation is completed for any reason; it will always follow a an abort, error, or load event. onloadstart nsidomeventlistener a javascript function object that gets invoked exactly once when the operation begins. onprogress nsidomeventlistener a javascript function object that gets invoked zero or more times, after the loadstart event, but before any abort, error, or load events occur. handling the events when the handler fun...
NS_ADDREF
summary macro addrefs the argument. do not use when the pointer might be null; use ns_if_addref in those cases. ns_addref(foo) is equivalent to foo->addref(); this macro exists mainly for historical reasons, but for consistency and for symmetry with ns_release it should still be used. syntax ns_addref(foo); see also ns_if_addref ns_release ...
Warnings
ut the number of sort operations that have occurred for a sql statement. this happens when you have an order by clause that does not use an index. when you do not use an index, all the results from the query have to first be fetched, and then those results are sorted. however, when the index is used, the data can be obtained row by row from the database, which will be much faster. if, for some reason you cannot use an index in your order by clause, you can suppress this warning by including a sql comment in your query that contains this text: /* do not warn (bug [everything in these brackets does not matter] */ the bug mentioned should explain why the query cannot use an index. ...
Using the clipboard
have to call it. tell the transferring object about the type of data being copied. tell the transferring object about the data to copy. create a clipboard object which refers to the system clipboard. tell the clipboard object to copy the data using the transferring object. you might wonder why a transferring object is needed instead of just putting the object directly on the clipboard. one reason is that some systems do not copy the data right away. instead, they wait until the data is pasted. another reason is that the transferable can hold multiple representations of the same data. for example, a piece of html can be represented in both its original html form and in plain text. if an application wants to get the data from the clipboard and doesn't understand html, it can use the plain t...
XPCOM ownership guidelines
terrific for factory functions, but can be problematic for mere getters. it's unfortunate if you just needed access to it for a moment. in the latter case, caching the pointer you got back makes you a de facto owner. this may not be appropriate; and it may be hard to remedy without knowing if the object in question was truly created in response to your query. needing it isn't, by itself, a valid reason for owning it. you don't own an object because you need it. in fact often you own it because it needs you. if you own it, it shouldn't own you. even transitively. or put another way: the ownership graph for any system should be acyclic. anytime there is a cycle of ownership, there is a situation that isn't automatically handled by destructors. special code must be provided and called to break ...
xptcall FAQ
what is xptcall? xptcall is a small low level xpcom method call library. it is implemented using platform specific c/c++ and assembly language code. it is used to facilitate cross language and cross thread method calls. porting this code is required in order to make mozilla run on any given platform. why does xptcall exist? xptcall exists for two reasons: to support invoking arbitrary methods on xpcom interfaces. to support dynamically impersonating any xpcom interface. both of these facilities are required by xpconnect. these facilities are also used by xpcom/proxy. it may also be used by other subsystems in the future. the xptcall approach was chosen over an approach that would have required generating stub code for calling and implementing all interfaces. though the chosen a...
XPIDL
ter for the attribute n n must_use y y adds moz_must_use to the generated function declarations n n method parameters each method parameter can be specified in one of three modes: in, out, or inout. an out parameter is essentially an auxiliary return value, although these are moderately cumbersome to use from script contexts and should therefore be avoided if reasonable. an inout parameter is an in parameter whose value may be changed as a result of the method; these parameters are rather annoying to use and should generally be avoided if at all possible. out and inout parameters are reflected as objects having the .value property which contains the real value of the parameter; it is not initialized in the case of out parameters and is initialized to the pa...
Autoconfiguration in Thunderbird
c ip here! server_name autoconfig.*; location / { root /var/www/autoconfig; } } ssl https was added in june 2019 to the spec. please use https whenever possible. former versions of this spec defined http only. http is still supported for existing hosts and in order to support domain hosters. http is deprecated now, but will need to be supported until at least end of 2023 for both of these reasons. configuration file this is described at how to create a configuration file and defined on the sub-pages. ...
Buddy icons in mail
the icon will show is on disk at: <profile home>/nim/<value of pref aim.session.screenname>/picture/<screenname for card>.gif if aim.session.screenname is not set, the icon will not appear. if there is no card matching the email, the icon will not appear. if there is a card, but no screenname, the icon will not appear. and finally, if there is no icon, the icon will not appear. the reason this file name scheme was chosen was is this is how netscape 7.0 im stores buddy icons on disk. so if you use nim, and you use buddy icons, this will just work for free. notes: you do not have to be online to use this feature. we do not show any buddy icon if you are in "collapsed" header mode. ...
nsIMsgCloudFileProvider
ons of the nsirequestobserver's used by the asynchronous methods of nsimsgcloudfileprovider. constant value description offlineerr 0x80550014 returned when it appears that there is no active network connection. autherr 0x8055001e returned when authorizing has failed. uploaderr 0x8055311a returned when uploading has failed for an unknown reason. uploadwouldexceedquota 0x8055311b returned when uploading has failed because the user has exceeded their storage quota. uploadexceedsfilelimit 0x8055311c returned when uploading has failed because the file being uploaded is larger than the file size limit. uploadcanceled 0x8055311d returned when uploading has stopped because it was cancelled by the us...
Mail composition back end
t few weeks reorganizing the mail composition back end, so i thought it would be helpful to put together a small doc on the new interfaces and how one can use them. the mail composition back end is responsible for the assembly and creation of rfc822 messages to be delivered either via smtp or nntp services. you also have the ability to save rfc822 files to disk, should you need this data for some reason. included in this functionality is the code to copy the messages to the appropriate locations after delivery (i.e. a "sent" folder) as well as the ability to store messages for features like "drafts" and "templates". several (but not all) of these interfaces are specified in idl. this will change in the coming weeks and allow for developers to write javascript to take advantage of the back end se...
Main Windows
evant. see developer.thunderbird.net for newer information. the base chrome directory of thunderbird can sometimes appear confusing when you're just beginning to look at it. as such, i've always thought it would be nice to have a list of what xul, js, or other files are that are here, what they do, and where they overlay at different points within the client. things appear confusing for several reasons: much of the code is written to be portable, so instead of duplicating it, its been put in overlays that are loaded over many different types of windows. some of the code was written based off of early firefox code, but is not exactly the same. you’ll sometimes see reimplementations of things that are already in toolkit, written specially for thunderbird. messenger.xul the base mail win...
Add to iPhoto
ctypes.bool, // returns a bool this.cfurlref, // input: url to convert ctypes.voidptr_t); // input: pointer to fsref to fill the corefoundation.cfurlgetfsref() method is used to fill out a carbon fsref structure to describe the location of a file represented by a cfurl object. the main reason i include this here is because of the last parameter, which should be a pointer to an fsref, but that's not declared until we get around to declaring the carbon api, and i think that's worth noting. cfarray the cfarray type is used to create arrays of objects; the objects in the array can be of any type, thanks to a set of callbacks you can provide to handle managing their memory and performing...
Drawing and Event Handling - Plugins
inting requires that the field printinfo contain a standard mac os thprint (see printing.h). of course, npp_print is also called with printinfo->mode equal to np_embed when the instance is embedded. in this case, platformprint->embedprint.window contains the window in which the plug-in should print. on ms windows, note that the coordinates for the window rectangle are in twips format. for this reason, you need to convert the x - and y - coordinates using the windows api call dptolp when you output text. setting the window the browser calls the npp_setwindow function to set the window in which a plug-in draws or returns an error code. this window is valid for the life of the instance, or until npp_setwindow is called again with a different value. subsequent calls to npp_setwindow for a give...
Version, UI, and Status Information - Plugins
isplay your message on the status line. void npn_status(npp instance, const char *message); the instance parameter is the current plug-in instance, that is, the one that the status message belongs to. in the message parameter, pass the string you want to display on the status line. the browser always displays the last status line message it receives, regardless of the message source. for this reason, your message is always displayed, but you have no control over how long it stays in the status line before another message replaces it. you should use a different method to display messages that the user needs to see, such as error messages. getting agent information a plug-in can check which browser is running on the user's current system. browsers communicate with http servers, which store a...
Accessibility Inspector - Firefox Developer Tools
essibility engine started already, e.g., you might be a screenreader user or tester). this is because the accessibility engine runs in the background when the accessibility features are turned on. while it’s running, it slows performance and takes up memory; therefore it interferes with the metrics from other panels such as memory and performance as well as overall browser performance. for this reason, you should keep it turned off when you aren't specifically using it. when first implemented, the accessibility engine had to be explicitly turned on. starting in firefox 79, it is automatically enabled when you do one of the following: choose accessibility in the tools > web developer menu. select the accessibility tab in the developer tools toolbox. right-click in the main browser window,...
Debugger.Object - Firefox Developer Tools
promise is pending. "fulfilled", if the promise has been fulfilled. "rejected", if the promise has been rejected. if the referent is not a promise, throw a typeerror. promisevalue return a debuggee value representing the value the promise has been fulfilled with. if the referent is not a promise, or the promise has not been fulfilled, throw a typeerror. promisereason return a debuggee value representing the value the promise has been rejected with. if the referent is not a promise, or the promise has not been rejected, throw a typeerror. promiseallocationsite if the referent is a promise, this is the javascript execution stack captured at the time of the promise’s allocation. this can return null if the promise was not created from script. if the r...
Edit fonts - Firefox Developer Tools
f the font editor shows the fonts used by the currently inspected element, grouped by font family. fonts are considered "used" when there is text content in the inspected element that has the font applied to it. empty elements will not have any fonts used and will display the message "no fonts were found for the current element." fonts will be included in this section for one of the following reasons: they are listed in the element's font-family css declaration value. they are applied to the element as part of the browser's default styling (times new roman for most browsers), and no author-defined font has been supplied. they are used by a descendant of the inspected element, for example, when it is a container for other elements which have text content with fonts applied. they are sys...
Examine and edit HTML - Firefox Developer Tools
as a tree (this ui is also called the markup view). just to the left of each node is an arrow: click the arrow to expand the node. if you hold the alt key while clicking the arrow, it expands the node and all the nodes underneath it. moving the mouse over a node in the tree highlights that element in the page. nodes that are not visible are shown faded/desaturated. this can happen for different reasons such as using display: none or that the element doesn't have any dimensions. there is an ellipsis shown between the opening and closing tag of an element when the node is collapsed if it has larger contents. now children are indicated in the tree with this icon: at the right side of some nodes there are markers shown indicating different pieces of information related to it: event ...
Frame rate - Firefox Developer Tools
e, the average frame rate, and the lowest frame rate. using the frame rate graph the great value of the frame rate graph is that, like the web console, it gives you a quick indication of where your site might be having problems, enabling you to use the other tools for more in-depth analysis. for example, here's a screenshot of a performance profile: you can see that the average frame rate is reasonably healthy, but there are three spots where frame rate collapses for tens of milliseconds. this would certainly cause a noticeable stutter for any animations that were playing in the page. the frame rate graph is correlated with the waterfall summary directly above it, and there we can see that the first two drops in the frame rate are correlated with orange bars, which denote time spent execut...
Animating CSS properties - Firefox Developer Tools
rview compared with the version that uses margin, we're seeing a lot less green and a lot more pink, which could be either layout or style recalculation. frame rate compared with the version that uses margin, this is looking pretty good. we're averaging nearly 60fps, and apart from one dip near the start, we're getting a consistently high frame rate. waterfall the timeline view shows the reason for the improved frame rate. compared with the version that uses margin, we're not spending any time time in layout or (more importantly in this case) in paint: in this case, using transform significantly improved the site's performance, and the performance tools were able to show how and why it did. ...
Intensive JavaScript - Firefox Developer Tools
ity test 50 times, for some quite large numbers. using requestanimationframe in the first attempt at fixing this, we'll split up the function into a number of much smaller self-contained functions, and schedule each one using requestanimationframe(). requestanimationframe() tells the browser to run the given function in each frame, just before it performs a repaint. as long as each function is reasonably small, the browser should be able to keep inside its frame budget. it's pretty simple to split up calculateprimes(): we will just calculate primality for each number in a separate function: function dopointlesscomputationswithrequestanimationframe() { function testcandidate(index) { // finishing condition if (index == iterations) { console.log(primes); pointlesscomput...
Debugging Firefox Desktop - Firefox Developer Tools
ion: /path/to/firefox --start-debugger-server passed with no arguments, --start-debugger-server makes the debugger server listen on port 6000. to use a different port, pass the desired port number: /path/to/firefox --start-debugger-server 1234 note: in windows, the start-debugger-server call will only have one dash: firefox.exe -start-debugger-server 1234 note: by default, and for security reasons, the devtools.debugger.force-local option is set. if you want to debug a firefox instance from an external machine, you can change this option, but only do this on a trusted network or set a strong firewall rule to lock down which machines can access it. ...
Console messages - Firefox Developer Tools
a link back to the original source, not the compressed version. async stack frames stack traces show stack frames for async functions separately from those for synchronous functions. when you run code containing an async function, its traces (console.trace or thrown error) are shown with an async: prefix. css note: css warnings and reflow messages are not shown by default, for performance reasons (see bug 1452143). use the filtering feature to show them. some css messages contain a disclosure triangle at the left of the message. click it to view more information about the error, as well as which dom nodes are affected by the error. reflow events the web console also logs reflow events under the css category. a reflow is the name given to the operation in which the browser calculate...
about:debugging (before Firefox 68) - Firefox Developer Tools
eeding the server. just click the "push" button to send a push event to the service worker: service workers not compatible in firefox 49+, a warning message will be displayed in the service workers section of the workers page if service workers are incompatible with the current browser configuration, and therefore cannot be used or debugged. service workers can be unavailable for several reasons: if you are using a private browsing window. if your history preference is set to "never remember history" or "always use private browsing mode". if the dom.serviceworkers.enable preference is set to false in about:config. ...
AnalyserNode.frequencyBinCount - Web APIs
integer half that of the analysernode.fftsize. this generally equates to the number of data values you will have to play with for the visualization. syntax var arraylength = analysernode.frequencybincount; value an unsigned integer, equal to the number of values that analysernode.getbytefrequencydata() and analysernode.getfloatfrequencydata() copy into the provided typedarray. for technical reasons related to how the fast fourier transform is defined, it is always half the value of analysernode.fftsize. therefore, it will be one of 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, and 16384. 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...
Animation.onremove - Web APIs
tion() { console.log('animation removed'); } console.log(anim.replacestate); }); here we have a <div> element, and an event listener that fires the event handler code whenever the mouse moves. the event handler sets up an animation that animates the <div> element to the position of the mouse pointer. this could result in a huge animations list, which could create a memory leak. for this reason, modern browsers automatically remove overriding forward filling animations. a console message is logged each time an animation it removed, invoked when the remove event is fired. specifications specification status comment web animationsthe definition of 'animation.onremove' in that specification. working draft editor's draft. ...
Animation.persist() - Web APIs
Web › API › Animation › persist
tion() { console.log('animation removed'); } console.log(anim.replacestate); }); here we have a <div> element, and an event listener that fires the event handler code whenever the mouse moves. the event handler sets up an animation that animates the <div> element to the position of the mouse pointer. this could result in a huge animations list, which could create a memory leak. for this reason, modern browsers automatically remove overriding forward filling animations. you can see the replacestate of the animation being logged at the end of the handler. this will be active for each animation by default, or persisted if the persist() call is uncommented. specifications specification status comment web animationsthe definition of 'persist()' in that specificati...
Animation.playState - Web APIs
urrenttime property is not updating. previously, web animations defined a pending value to indicate that some asynchronous operation such as initiating playback was yet to complete. this is now indicated by the separate animation.pending property. example in the growing/shrinking alice game example, players can get an ending with alice crying into a pool of tears. in the game, for performance reasons, the tears should only be animating when they're visible. so they must be paused as soon as they are animated like so: // setting up the tear animations tears.foreach(function(el) { el.animate( tearsfalling, { delay: getrandommsrange(-1000, 1000), // randomized for each tear duration: getrandommsrange(2000, 6000), // randomized for each tear iterations: infinity,...
Animation.replaceState - Web APIs
tion() { console.log('animation removed'); } console.log(anim.replacestate); }); here we have a <div> element, and an event listener that fires the event handler code whenever the mouse moves. the event handler sets up an animation that animates the <div> element to the position of the mouse pointer. this could result in a huge animations list, which could create a memory leak. for this reason, modern browsers automatically remove overriding forward filling animations. you can see the replacestate of the animation being logged at the end of the handler. this will be active for each animation by default, or persisted if the persist() call is uncommented. specifications specification status comment web animationsthe definition of 'animation.replacestate' in tha...
Animation - Web APIs
Web › API › Animation
ll play from end to beginning. animation.updateplaybackrate() sets the speed of an animation after first synchronizing its playback position. automatically removing filling animations it is possible to trigger a large number of animations on the same element. if they are indefinite (i.e., forwards-filling), this can result in a huge animations list, which could create a memory leak. for this reason, modern browsers have implemented the part of the web animations spec that automatically removes overriding forward filling animations, unless the developer explicitly specifies to keep them. you can see this in action in our simple replace indefinite animations demo. the related javascript features are: animation.commitstyles() for commiting the end styling state of an animation to the eleme...
AudioParam.setTargetAtTime() - Web APIs
timestep of length timeconstant, the value will have approached target by another 1-e-1≈63.2%1 - e^{-1} \approx 63.2%. for the complete formula (which uses a first-order linear continuous time-invariant system), check the web audio specification. if you absolutely need to reach the target value by a specific time, you can use audioparam.exponentialramptovalueattime(). however, for mathematical reasons, that method does not work if the current value or the target value is 0. choosing a good timeconstant as mentioned above, the value changes exponentially, with each timeconstant bringing you another 63.2% toward the target value. you don't have to worry about reaching the target value; once you are close enough, any further changes will be imperceptible to a human listener. depending on your...
BatteryManager.chargingTime - Web APIs
syntax var time = battery.chargingtime on return, time is the remaining time in seconds until the battery, which is a batterymanager object, is fully charged, or 0 if the battery is already fully charged. if the battery is currently discharging, this value is infinity. ...
BatteryManager.dischargingTime - Web APIs
syntax var time = battery.dischargingtime on return, time is the remaining time in seconds until the battery, which is a batterymanager object, is fully discharged and the system will suspend. ...
BluetoothDevice - Web APIs
service. bluetoothdevice.paired read only a boolean value indicating whether the device is paired with the system. bluetoothdevice.gattserver read only a reference to the device's gatt server or null if the device is disconnected. methods bluetoothdevice.watchadvertisments() a promise that resolves to undefined or is rejected with an error if advetisments can’t shown for any reason. bluetoothdevice.unwatchadvertisments() stops watching for advertisments. bluetoothdevice.connectgatt() a promise that resolves to an instance of bluetoothgattremoteserver. specifications specification status comment web bluetooththe definition of 'bluetoothdevice' in that specification. draft initial definition. ...
CSSRuleList - Web APIs
order as it appears in the style sheet css. the number of rules in the list is rules.length. note that being indirect-modify (changeable but only having read-methods), rules are not added or removed from the list directly, but instead here, only via its parent stylesheet. in fact, .insertrule() and .deleterule() are not even methods of cssrulelist, but only of cssstylesheet. if however, for some reason the list does need to be modified but has no parent stylesheet (perhaps being a livecopy of a list that does), it cannot just be assigned one (as it has no such property), and neither can it be assigned to one (as stylesheet.cssrules is read-only), but it must unfortunately be inserted into one, rule by rule, and unless combining lists, after any existing list therein is deleted, rule by rule. e...
CSSStyleSheet - Web APIs
st cannot be modified directly, there's no useful way to create a new cssstylesheet object manually (although constructable stylesheet objects is coming to the web platform soon and is already supported in blink). to create a new stylesheet, insert a <style> or <link> element into the document. a (possibly incomplete) list of ways a stylesheet can be associated with a document follows: reason for the style sheet to be associated with the document appears in document. stylesheets list getting the owner element/rule given the style sheet object the interface for the owner object getting the cssstylesheet object from the owner <style> and <link> elements in the document yes .ownernode htmllinkelement, htmlstyleelement, or svgstyleelement .
CanvasRenderingContext2D - Web APIs
specified point is inside the area contained by the stroking of a path. transformations objects in the canvasrenderingcontext2d rendering context have a current transformation matrix and methods to manipulate it. the transformation matrix is applied when creating the current default path, painting text, shapes and path2d objects. the methods listed below remain for historical and compatibility reasons as svgmatrix objects are used in most parts of the api nowadays and will be used in the future instead. canvasrenderingcontext2d.currenttransform current transformation matrix (svgmatrix object). canvasrenderingcontext2d.gettransform retrieves the current transformation matrix being applied to the context. canvasrenderingcontext2d.rotate() adds a rotation to the transformation matrix. ...
Drawing shapes with canvas - Web APIs
are stored as a list of sub-paths (lines, arcs, etc) which together form a shape. every time this method is called, the list is reset and we can start drawing new shapes. note: when the current path is empty, such as immediately after calling beginpath(), or on a newly created canvas, the first path construction command is always treated as a moveto(), regardless of what it actually is. for that reason, you will almost always want to specifically set your starting position after resetting a path. the second step is calling the methods that actually specify the paths to be drawn. we'll see these shortly. the third, and an optional step, is to call closepath(). this method tries to close the shape by drawing a straight line from the current point to the start. if the shape has already been clos...
CloseEvent() - Web APIs
typearg is a domstring representing the name of the event. closeeventinit optional is a closeeventinit dictionary, having the following fields: "wasclean", optional and defaulting to false, of type long, indicates if the connection has been closed cleanly or not. "code", optional and defaulting to 0, of type unsigned short, that is the connection close code sent by the server. "reason", optional and defaulting to '', of type domstring, that is a human-readable reason why the server closed the connection. the closeeventinit dictionary also accepts fields from the eventinit dictionary. specifications specification status comment html living standardthe definition of 'closeevent()' in that specification. living standard initial defin...
CloseEvent - Web APIs
reserved for future use by the websocket standard. 2000–2999 reserved for use by websocket extensions. 3000–3999 available for use by libraries and frameworks. may not be used by applications. available for registration at the iana via first-come, first-serve. 4000–4999 available for use by applications. closeevent.reason read only returns a domstring indicating the reason the server closed the connection. this is specific to the particular server and sub-protocol. closeevent.wasclean read only returns a boolean that indicates whether or not the connection was cleanly closed. methods this interface also inherits methods from its parent, event. closeevent.initcloseevent() initializes the value of a ...
console - Web APIs
Web › API › Console
roperty console. it's exposed as window.console, and can be referenced as simply console. for example: console.log("failed to open the specified link") this page documents the methods available on the console object and gives a few usage examples. note: this feature is available in web workers. note: the actual console interface is defined as all lower case (i.e. not console), for historical reasons. methods console.assert() log a message and stack trace to console if the first argument is false. console.clear() clear the console. console.count() log the number of times this line has been called with the given label. console.countreset() resets the value of the counter with the given label. console.debug() outputs a message to the console with the log level debug. console.dir...
Crypto.getRandomValues() - Web APIs
replaced with the newly generated random numbers. note that typedarray is modified in-place, and no copy is made. exceptions this method can throw an exception under error conditions. domexception (name: quotaexceedederror) the requested length exceeds 65,536 bytes. usage notes don't use getrandomvalues() to generate encryption keys. instead, use the generatekey() method. there are a few reasons for this; for example, getrandomvalues() is not guaranteed to be running in a secure context. there is no minimum degree of entropy mandated by the web cryptography specification. user agents are instead urged to provide the best entropy they can when generating random numbers, using a well-defined, efficient pseudorandom number generator built into the user agent itself, but seeded with values...
CryptoKey - Web APIs
Web › API › CryptoKey
properties cryptokey.type string which may take one of the following values: "secret": this key is a secret key for use with a symmetric algorithm. "private": this key is the private half of an asymmetric algorithm's cryptokeypair. ...
DOMException.code - Web APIs
Web › API › DOMException › code
new dom exceptions don't use this anymore: they put this info in the domexception.name attribute. syntax var domexceptioncode = domexceptioninstance.code; value a short number. specifications specification status comment web idlthe definition of 'code' in that specification. candidate recommendation browser compatibility the compatibility table on this page is generated from structured data. ...
Binary strings - Web APIs
Web › API › DOMString › Binary
mat, however this will not be visible to the final user, since the length of javascript strings is calculated using two bytes as the unit. binary strings are not part of the javascript language design. however at least one native function requires binary strings as its input, btoa(): invoking it on a string that contains codepoints greater than 255 will cause a character out of range error. the reason that brought to use utf-16 code units as placeholders for uint8 numbers is that as web applications become more and more powerful (adding features such as audio and video manipulation, access to raw data using websockets, and so forth) it has become clear that there are times when it would be helpful for javascript code to be able to quickly and easily manipulate raw binary data. in the past, th...
DataTransfer.types - Web APIs
the datatransfer.types read-only property returns an array of the drag data formats (as strings) that were set in the dragstart event. the order of the formats is the same order as the data included in the drag operation. the formats are unicode strings giving the type or format of the data, generally given by a mime type. some values that are not mime types are special-cased for legacy reasons (for example "text"). syntax datatransfer.types; return value an array of the data formats used in the drag operation. each format is string. if the drag operation included no data, this list will be empty. if any files are included in the drag operation, then one of the types will be the string files. example this example shows the use of the types and items properties. <!doctype html> <html ...
DataTransfer - Web APIs
ursor was located when the button was pressed to initiate the drag operation. this value is null for external drags or if the caller can't access the node. datatransfer.mozusercancelled read only this property applies only to the dragend event, and is true if the user canceled the drag operation by pressing escape. it will be false in all other cases, including if the drag failed for any other reason, for instance due to a drop over an invalid location. deprecated properties datatransfer.mozitemcount read only gives the number of items in the drag operation. removed in firefox 71. methods standard methods datatransfer.cleardata() remove the data associated with a given type. the type argument is optional. if the type is empty or not specified, the data associated with all type...
DirectoryEntrySync - Web APIs
atch these cases with error callbacks and retry the deletion. void removerecursively ( ) raises (fileexception); parameter none returns void exceptions this method can raise a fileexception with the following codes: exception description not_found_err the target directory does not exist. invalid_state_err this directory is not longer valid for some reason other than being deleted. [todo: explain more ] no_modification_allowed_err one of the following is not writable: the directory, its parent directory, and some of the content in the directory. security_err the application does not have permission to access the target directory, its parent, or some of its contents. ...
Document.anchors - Web APIs
Web › API › Document › anchors
specifications specification status comment html living standardthe definition of 'document.anchors' in that specification. living standard obsoleted. document object model (dom) level 2 html spe...
Document.cookie - Web APIs
Web › API › Document › cookie
for you to use whatwg dom storage if you are going to keep "client-only" data. rfc 2965 (section 5.3, "implementation limits") specifies that there should be no maximum length of a cookie's key or value size, and encourages implementations to support arbitrarily large cookies. each browser's implementation maximum will necessarily be different, so consult individual browser documentation. ...
Document: fullscreenerror event - Web APIs
en the browser cannot switch to full-screen mode. bubbles yes cancelable no interface event event handler property onfullscreenerror as with the fullscreenchange event, two fullscreenerror events are fired; the first is sent to the element which failed to change modes, and the second is sent to the document which owns that element. for some reasons that switching into full-screen mode might fail, see the guide to the fullscreen api. examples const requestor = document.queryselector('div'); document.addeventlistener('fullscreenerror', (event) => { console.error('an error occurred changing into fullscreen'); console.log(event); }); requestor.requestfullscreen(); specifications specification status fullscree...
Document.onfullscreenerror - Web APIs
hen it fails to transition into full-screen mode after a prior call to element.requestfullscreen(). syntax targetdocument.onfullscreenerror = fullscreenerrorhandler; value an event handler for the fullscreenerror event. example this example attempts to call requestfullscreen() outside of an event handler. since requestfullscreen() can only be called in response to user action, for security reasons, this will fail, causing the fullscreenerror to be sent to the document. document.onfullscreenerror = function ( event ) { displaywarning("unable to switch into full-screen mode."); }; //.... document.documentelement.requestfullscreen(); specifications specification status comment fullscreen apithe definition of 'onfullscreenerror' in that specification. li...
Document.ononline - Web APIs
Web › API › Document › ononline
puter can be connected to a network without having internet access. you can register listeners for these events in a few familiar ways: using addeventlistener on the window, document, or document.body by setting the .ononline or .onoffline properties on document or document.body to a javascript function object. (note: using window.ononline or window.onoffline will not work for compatibility reasons.) by specifying ononline="..." or onoffline="..." attributes on the <body> tag in the html markup. example there's a simple test case that you can run to verify that the events are working. references online and offline events [en-us] whatwg web app specification ...
Document: pointerlockerror event - Web APIs
the pointerlockerror event is fired when locking the pointer failed (for technical reasons or because the permission was denied). bubbles yes cancelable no interface event event handler property onpointerlockerror examples using addeventlistener(): const para = document.queryselector('p'); document.addeventlistener('pointerlockerror', (event) => { console.log('error locking pointer'); }); using the onpointerlockerror event handler property: document.onpointerlockerror = (event) => { console.log('error locking pointer'); }; specifications specification status pointer lock candidate recommendation ...
Document: pointerout event - Web APIs
the pointerout event is fired for several reasons including: pointing device is moved out of the hit test boundaries of an element; firing the pointerup event for a device that does not support hover (see pointerup); after firing the pointercancel event (see pointercancel); when a pen stylus leaves the hover range detectable by the digitizer. bubbles yes cancelable yes interface pointerevent event handler property onpointerout examples using addeventlistener(): document.addeventlistener('pointerout', (event) => { console.log('pointer moved out'); }); using the onpointerout event handler property: document.onpointerout = (event) => { console.log('pointer moved out'); }; specifications specification status ...
Document - Web APIs
Web › API › Document
e pointer is locked/unlocked. also available via the onpointerlockchange property. pointerlockerror fired when locking the pointer failed. also available via the onpointerlockerror property. pointermove fired when a pointer changes coordinates. also available via the onpointermove property. pointerout fired when a pointer is moved out of the hit test boundaries of an element (among other reasons). also available via the onpointerout property. pointerover fired when a pointer is moved into an element's hit test boundaries. also available via the onpointerover property. pointerup fired when a pointer is no longer active. also available via the onpointerup property. selection events selectionchange fired when the current text selection on a document is changed. also available...
Using the W3C DOM Level 1 Core - Web APIs
nd of the document by appending it to // the body (which is the parent of para) para.parentnode.appendchild(newelement); } you can see this script as a complete example. how can i learn more? now that you are familiar with the basic concepts of the dom, you may want to learn about the dom level 1 fundamental methods. see also the dom level 1 core specification from the w3c. it's a reasonably clear spec, although it is formal. the main thing that's useful to authors is the description of the different dom objects and all their properties and methods. also see our other dom documentation. original document information author(s): l. david baron <dbaron at dbaron dot org> copyright information: © 1998-2005 by individual mozilla.org contributors; content available under a creat...
Element.attachShadow() - Web APIs
the element.attachshadow() method attaches a shadow dom tree to the specified element and returns a reference to its shadowroot. elements you can attach a shadow to note that you can't attach a shadow root to every type of element. there are some that can't have a shadow dom for security reasons (for example <a>), and more besides. the following is a list of elements you can attach a shadow root to: any autonomous custom element with a valid name <article> <aside> <blockquote> <body> <div> <footer> <h1> <h2> <h3> <h4> <h5> <h6> <header> <main> <nav> <p> <section> <span> syntax var shadowroot = element.attachshadow(shadowrootinit); parameters shadowrootinit a shadowrootinit dictionary, which can contain the following fields: mode a string specifying the e...
Element: fullscreenerror event - Web APIs
he browser cannot switch to full-screen mode. bubbles yes cancelable no interface event event handler property onfullscreenerror as with the fullscreenchange event, two fullscreenerror events are fired; the first is sent to the element which failed to change modes, and the second is sent to the document which contains that element. for some reasons that switching into full-screen mode might fail, see the guide to the fullscreen api. examples const requestor = document.queryselector('div'); requestor.addeventlistener('fullscreenerror', (event) => { console.error('an error occurred changing into fullscreen'); console.log(event); }); requestor.requestfullscreen(); specifications specification status fullscre...
Element.getAttribute() - Web APIs
mplement this behavior. the implementation of getattribute() in xul (gecko) actually follows the dom 3 core specification and returns an empty string. consequently, you should use element.hasattribute() to check for an attribute's existence prior to calling getattribute() if it is possible that the requested attribute does not exist on the specified element. retrieving nonce values for security reasons, csp nonces from non-script sources, such as css selectors, and .getattribute("nonce") calls are hidden. let nonce = script.getattribute('nonce'); // returns empty string instead of retrieving the nonce from the content attribute, use the nonce property: let nonce = script.nonce; specifications specification status comment domthe definition of 'getattribute()...
Element.getAttributeNS() - Web APIs
example above, where the attribute is part of the fictional "specialspace" namespace on mozilla. prior to the dom4 specification, this method was specified to return an empty string rather than null for non-existent attributes. however, most browsers instead returned null. starting with dom4, the specification now says to return null. however, some older browsers return an empty string. for that reason, you should use hasattributens() to check for an attribute's existence prior to calling getattributens() if it is possible that the requested attribute does not exist on the specified element. dom methods dealing with element's attributes: not namespace-aware, most commonly used methods namespace-aware variants (dom level 2) dom level 1 methods for dealing with attr nodes directly (seldom use...
Element.innerHTML - Web APIs
Web › API › Element › innerHTML
esult is harmless. html5 specifies that a <script> tag inserted with innerhtml should not execute. however, there are ways to execute javascript without using <script> elements, so there is still a security risk whenever you use innerhtml to set strings over which you have no control. for example: const name = "<img src='x' onerror='alert(1)'>"; el.innerhtml = name; // shows the alert for that reason, it is recommended that you do not use innerhtml when inserting plain text; instead, use node.textcontent. this doesn't parse the passed content as html, but instead inserts it as raw text. warning: if your project is one that will undergo any form of security review, using innerhtml most likely will result in your code being rejected. for example, if you use innerhtml in a browser extension an...
Event.explicitOriginalTarget - Web APIs
for example, mouse events are retargeted to their parent node when they happen over text nodes (see bug 185889), and in that case currenttarget will show the parent and explicitoriginaltarget will show the text node. explicitoriginaltarget differs from originaltarget in that it will never contain anonymous content. example this property can be used with <command> to get the event details of the original object calling the command. ...
Event.srcElement - Web APIs
Web › API › Event › srcElement
initially implemented in internet explorer, event.srcelement is a now-standard alias (defined in the dom standard but flagged as "historical") for the event.target property. it's supported in all major browser engines, but only for compatibility reasons. use event.target instead. specifications specification status comment domthe definition of 'event.srcelement' in that specification. living standard ...
EventTarget.removeEventListener() - Web APIs
notes if an eventlistener is removed from an eventtarget while it is processing an event, it will not be triggered by the current actions. an eventlistener will not be invoked for the event it was registered for after being removed. however, it can be reattached. ca...
FetchEvent.respondWith() - Web APIs
the respondwith() method of fetchevent prevents the browser's default fetch handling, and allows you to provide a promise for a response yourself. in most cases you can provide any response that the receiver understands. for example, if an <img> initiates the request, the response body needs to be image data. for security reasons, there are a few global rules: you can only return response objects of type "opaque" if the fetchevent.request object's mode is "no-cors". this prevents the leaking of private data. you can only return response objects of type "opaqueredirect" if the fetchevent.request object's mode is "manual". you cannot return response objects of type "cors" if the fetchevent.request object's mode is "same-origin". specifying the final url of a resource from firefox 59 onw...
File.fileName - Web APIs
Web › API › File › fileName
ery user. there may also be large incompatibilities between implementations and the behavior may change in the future. obsolete since gecko 7.0 (firefox 7.0 / thunderbird 7.0 / seamonkey 2.4)this feature is obsolete. although it may still work in some browsers, its use is discouraged since it could be removed at any time. try to avoid using it. returns the name of the file. for security reasons the path is excluded from this property. this property is deprecated. use file.name instead. syntax var name = instanceoffile.filename; value a string specification not part of any specification. ...
File.name - Web APIs
Web › API › File › name
syntax var name = file.name; value a string, containing the name of the file without path, such as "my resume.rtf". ...
FileException - Web APIs
by another application). path_exists_err 12 the file or directory with the same path already exists. quota_exceeded_err 10 either there's not enough remaining storage space or the storage quota was reached and the user declined to give more space to the database. security_err 2 access to the files were denied for one of the following reasons: the files might be unsafe for access within a web application. too many calls are being made on file resources. other unspecified security error code or situations. type_mismatch_err 11 the user has attempted to look up a file or directory, but the entry found is of the wrong type. for example, the app is accessing a directoryentry when the user is r...
FileSystemDirectoryEntry.getFile() - Web APIs
follows: fileerror.not_found_err the create option was not specified (or was specified as false), and the file doesn't exist. fileerror.path_exists_err the create and exclusive options were both true, indicating that the file should be created but must not already exist, but the file does in fact already exist. fileerror.security_err the request to access the file was denied for security reasons. fileerror.type_mismatch_err the path specified is not a file; it's probably a directory, but might be an unsupported file descriptor such as a pipe; this depends on the user agent to some extent. filesystemflags the options parameter is an object which is based on the filesystemflags dictionary; it provides flags which make it possible to adjust the behavior of the getfile() method. cre...
FileSystemDirectoryEntry.removeRecursively() - Web APIs
ification_allowed_err the file system's state doesn't permit modification. fileerror.not_found_err the directory represented by the filesystemdirectoryentry no longer exists. fileerror.not_readable_err the directory is not accessible; perhaps it's in use by another application or is locked at the operating system level. fileerror.security_err the directory could not be removed for security reasons. possible reasons include: the directory and/or its contents may not be safe to access from a web application. too many file system calls are being made. other security concerns as raised by the user agent or the operating system. if you try to delete a directory which contains one or more files that can't be removed, or if an error occurs while deletion of a number of files is un...
FileSystemEntry.remove() - Web APIs
callback which is called if the attempt to remove the file fails. return value undefined. errors fileerror.invalid_modification_err the specified entry was the file system's root directory, or the specified entry is a directory which isn't empty. fileerror.invalid_state_err the file system's cached state is inconsistent with its state on disk, so the file could not be deleted for safety reasons. fileerror.no_modification_allowed_err the file system's state doesn't permit removing the file or directory. fileerror.not_found_err the file or directory doesn't exist. fileerror.security_err the entry couldn't be removed due to permissions or other access constraints, or because there are too many calls being made on file resources. example this example deletes a temporary work file.
FileSystemEntrySync - Web APIs
adata about this entry. [ todo: specify what kind of metadata ] metadata getmetada () raises (fileexception); parameter none returns metadata exceptions this method can raise a fileexception with the following codes: exception description not_found_err the entry does not exist. invalid_state_err the filesystemsync is no longer valid for some reason besides being deleted. moveto() move an entry to a different location on the file system. moving a file over an existing file replaces that existing file. moving a directory over an existing empty directory replaces that directory. [todo: what if the directory is not empty? ] [todo: verify ] this is the same method for renaming files. you can keep it in the same location and then define ...
FileHandle API - Web APIs
me unique file. this is not a problem because to access the file, a lockedfile object is required and operations on such object are performed in isolation, meaning that once a lockedfile is active, all operations of this lockedfile are guaranteed to happen sequentially on the underlying file without being interleaved with operations from other lockedfile. secured write operation for performance reasons, write (and read) operations are done in memory. periodically, the results of those operation are asynchronously flushed to the device storage area. if for some reason a problem occurs before that, you can lose the results of some operations. to avoid that problem, you can force the data to be flushed by using the lockedfile.flush() method. once this method has been successfully called, you can ...
File and Directory Entries API support in Firefox - Web APIs
or more insights. this has caused a number of popular web sites not to work properly on browsers other than chrome. because of that, an attempt was made to create a spec offering the features of google's api which consensus could be reached on. the result was the file and directory entries api. this subset of the api provided by chrome is still not fully specified; however, for web compatibility reasons, it was decided to implement a subset of the api in firefox; this was introduced in firefox 50. this article describes how the firefox implementation of the file and directory entries api differs from other implementations and/or the specification. chrome deviations from the specification the largest compatibility issue still remaining is that chrome is still using older names for many of the...
FocusEvent.relatedTarget - Web APIs
ing focus the eventtarget receiving focus (if any). focus the eventtarget receiving focus the eventtarget losing focus (if any) focusin the eventtarget receiving focus the eventtarget losing focus (if any) focusout the eventtarget losing focus the eventtarget receiving focus (if any) note that many elements can't have focus, which is a common reason for relatedtarget to be null. relatedtarget may also be set to null for security reasons, like when tabbing in or out of a page. mouseevent.relatedtarget is a similar property for mouse events. syntax secondtarget = focusevent.relatedtarget specifications specification status comment ui eventsthe definition of 'focusevent.relatedtarget' in that specification. worki...
FocusEvent - Web APIs
s: all;} constructor focusevent() creates a focusevent event with the given parameters. properties this interface also inherits properties from its parent uievent, and indirectly from event. focusevent.relatedtarget is an eventtarget representing a secondary target for this event. in some cases (such as when tabbing in or out a page), this property may be set to null for security reasons. methods this interface has no specific methods. it inherits methods from its parent uievent, and indirectly from event. specifications specification status comment ui eventsthe definition of 'focusevent' in that specification. working draft document object model (dom) level 3 events specificationthe definition of 'focusevent' in that specificatio...
Fullscreen API - Web APIs
t.fullscreenelement the fullscreenelement property tells you the element that's currently being displayed in full-screen mode on the dom (or shadow dom). if this is null, the document is not in full-screen mode. document.fullscreenenabled the fullscreenenabled property tells you whether or not it is possible to engage full-screen mode. this is false if full-screen mode is not available for any reason (such as the "fullscreen" feature not being allowed, or full-screen mode not being supported). event handlers the fullscreen api defines two events which can be used to detect when full-screen mode is turned on and off, as well as when errors occur during the process of changing between full-screen and windowed modes. event handlers for these events are available on the document and element in...
Using the Gamepad API - Web APIs
of the performancetiming interface. values are monotonically increasing, meaning that they can be compared to determine the ordering of updates, as newer values will always be greater than or equal to older values. note that this property is not currently supported in firefox. note: the gamepad object is available on the gamepadconnected event rather than the window object itself, for security reasons. once we have a reference to it, we can query its properties for information about the current state of the gamepad. behind the scenes, this object will be updated every time the gamepad's state changes. using button information let's look at a simple example that displays connection information for one gamepad (it ignores subsequent gamepad connections) and allows you to move a ball around t...
Geolocation - Web APIs
the geolocation interface represents an object able to programmatically obtain the position of the device. it gives web content access to the location of the device. this allows a web site or app to offer customized results based on the user's location. an object with this interface is obtained using the navigator.geolocation property implemented by the navigator object. note: for security reasons, when a web page tries to access location information, the user is notified and asked to grant permission. be aware that each browser has its own policies and methods for requesting this permission. properties the geolocation interface neither implements, nor inherits any property. methods the geolocation interface doesn't inherit any method. geolocation.getcurrentposition() secure conte...
GeolocationPositionError - Web APIs
properties the geolocationpositionerror interface doesn't inherit any property. geolocationpositionerror.code read only secure context returns an unsigned short representing the error code. the following values are possible: value associated constant description 1 permission_denied the acquisition of the geolocation information failed because the page didn't have the permission to do it. 2 position_unavailable the acquisition of the geolocation failed because at least one internal source of position returned an internal error. ...
Geolocation API - Web APIs
webextensions that wish to use the geolocation object must add the "geolocation" permission to their manifest. the user's operating system will prompt the user to allow location access the first time it is requested. concepts and usage you will often want to retrieve a user's location information in your web app, for example to plot their location on a map, or display personalized information relevant to their location. ...
GlobalEventHandlers.onabort - Web APIs
thandlers mixin is the eventhandler for processing abort events sent to the window. while the standard for aborting a document load is defined, html issue #3525 suggests that browsers should not currently fire the abort event on a window that would trigger onabort to be called. todo: define what "abort" is. closing the window via window manager? stopping the load of the page? by which means and reasons (user, network/server)? at which stages would it fire / be caught? for ie, onabort is only available with <img> tags. syntax window.onabort = functionref; value functionref is a function name or a function expression. example window.onabort = function() { alert('load aborted.'); } specification specification status comment html living standardthe definition of ...
HTMLCollection - Web APIs
an htmlcollection in the html dom is live; it is automatically updated when the underlying document is changed. ...
HTMLElement: pointerout event - Web APIs
the pointerout event is fired for several reasons including: pointing device is moved out of the hit test boundaries of an element; firing the pointerup event for a device that does not support hover (see pointerup); after firing the pointercancel event (see pointercancel); when a pen stylus leaves the hover range detectable by the digitizer. bubbles yes cancelable yes interface pointerevent event handler property onpointerout examples using addeventlistener(): const para = document.queryselector('p'); para.addeventlistener('pointerout', (event) => { console.log('pointer moved out'); }); using the onpointerout event handler property: const para = document.queryselector('p'); para.onpointerout = (event) => { console.log('pointer m...
HTMLElement - Web APIs
ants. also available via the onpointerenter property. pointerleave fired when a pointer is moved out of the hit test boundaries of an element. also available via the onpointerleave property. pointermove fired when a pointer changes coordinates. also available via the onpointermove property. pointerout fired when a pointer is moved out of the hit test boundaries of an element (among other reasons). also available via the onpointerout property. pointerover fired when a pointer is moved into an element's hit test boundaries. also available via the onpointerover property. pointerup fired when a pointer is no longer active. also available via the onpointerup property. transition events transitioncancel fired when a css transition is canceled. also available via the ontransition...
HTMLFormElement.elements - Web APIs
ge. the form controls in the returned collection are in the same order in which they appear in the form by following a preorder, depth-first traversal of the tree. this is called tree order. the elements included by htmlformelement.elements and htmlformelement.length are the following: <button> <fieldset> <input> (with the exception that any whose type is "image" are omitted for historical reasons) <object> <output> <select> <textarea> no other elements are included in the list returned by elements, which makes it an excellent way to get at the elements most important when processing forms. example quick syntax example in this example, we see how to obtain the list of form controls as well as how to access its members by index and by name or id. <form id="my-form"> <input type...
HTMLFormElement.length - Web APIs
controls using the elements property. this includes both elements that are descendents of the <form> element as well as elements that are made members of the form using their form property. the elements included by htmlformelement.elements and htmlformelement.length are the following: <button> <fieldset> <input> (with the exception that any whose type is "image" are omitted for historical reasons) <object> <output> <select> <textarea> no other elements are included in the list returned by elements, which makes it an excellent way to get at the elements most important when processing forms. syntax numcontrols = form.length; value numcontrols is the number of form controls within the <form>. this is the same as the number of the elements in the htmlformcontrolscollection returne...
HTMLFormElement - Web APIs
en an element name and a form property. never use "elements" as an element name. if you are not using javascript, this will not cause a problem. elements that are considered form controls the elements included by htmlformelement.elements and htmlformelement.length are the following: <button> <fieldset> <input> (with the exception that any whose type is "image" are omitted for historical reasons) <object> <output> <select> <textarea> no other elements are included in the list returned by elements, which makes it an excellent way to get at the elements most important when processing 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 ...
HTMLImageElement.border - Web APIs
the border. the border property or its longhand properties to not only set the thickness of the border but to potentially apply a wide variety of other styling options to it. the width, specifically, is controlled using the writing-mode aware border-block-start-width, border-block-end-width, border-inline-start-width, and border-inline-end-width properties. for compatibility (or perhaps other) reasons, you can use the older properties instead (or in addition): border-top-width, border-right-width, border-bottom-width, and border-left-width. syntax htmlimageelement.border = thickness; let thickness = htmlimageelement.border; value a domstring containing an integer value specifying the thickness of the border that should surround the image, in css pixels. a value of 0, or an empty string, ...
HTMLImageElement.isMap - Web APIs
use a client-side image map instead. syntax htmlimageelement.ismap = true|false; let ismap = htmlimageelement.ismap; value a boolean value which is true if the image is being used for a server-side image map; otherwise, the value is false. ...
Using microtasks in JavaScript with queueMicrotask() - Web APIs
oes not return a value. when to use microtasks in this section, we'll take a look at scenarios in which microtasks are particularly useful. generally, it's about capturing or checking results, or performing cleanup, after the main body of a javascript execution context exits, but before any event handlers, timeouts and intervals, or other callbacks are processed. when is that useful? the main reason to use microtasks is simply that: to ensure consistent ordering of tasks, even when results or data is available synchronously, but while simultaneously reducing the risk of user-discernible delays in operations. ensuring ordering on conditional use of promises one situation in which microtasks can be used to ensure that the ordering of execution is always consistent is when promises are used i...
Drag Operations - Web APIs
ect property has the value none during a dragend, then the drag was cancelled. otherwise, the effect specifies which operation was performed. the source can use this information after a move operation to remove the dragged item from the old location. the mozusercancelled property will be set to true if the user cancelled the drag (by pressing escape), and false if the drag was cancelled for other reasons such as an invalid drop target, or if it was successful. a drop can occur inside the same window or over another application. the dragend event will always fire regardless. the event's screenx and screeny properties will be set to the screen coordinates where the drop occurred. after the dragend event has finished propagating, the drag and drop operation is complete. [1]: in gecko, dragend is...
Headers.append() - Web APIs
Web › API › Headers › append
rs interface appends a new value onto an existing header inside a headers object, or adds the header if it does not already exist. the difference between set() and append() is that if the specified header already exists and accepts multiple values, set() will overwrite the existing value with the new one, whereas append() will append the new value onto the end of the set of values. for security reasons, some headers can only be controlled by the user agent. these headers include the forbidden header names and forbidden response header names. syntax myheaders.append(name, value); parameters name the name of the http header you want to add to the headers object. value the value of the http header you want to add. returns void. example creating an empty headers object is simple: va...
Headers.get() - Web APIs
Web › API › Headers › get
these headers include the forbidden header names and forbidden response header names. syntax myheaders.get(name); parameters name the name of the http header whose values you want to retrieve from the headers object. ...
Headers.getAll() - Web APIs
Web › API › Headers › getAll
. the getall() method of the headers interface used to return an array of all the values of a header within a headers object with a given name; in newer versions of the fetch spec, it has been deleted, and headers.get() has been updated to fetch all header values instead of only the first one. if the requested header doesn't exist in the headers object, it returns an empty array. for security reasons, some headers can only be controller by the user agent. these headers include the forbidden header names and forbidden response header names. syntax myheaders.getall(name); parameters name the name of the http header whose values you want to retrieve from the headers object. if the given name is not the name of an http header, this method throws a typeerror. returns an array containin...
Headers.has() - Web APIs
Web › API › Headers › has
these headers include the forbidden header names and forbidden response header names. syntax myheaders.has(name); parameters name the name of the http header you want to test for. if the given name is not a valid http header name, this method throws a typeerror. returns a boolean. ...
Headers.set() - Web APIs
Web › API › Headers › set
ders interface sets a new value for an existing header inside a headers object, or adds the header if it does not already exist. the difference between set() and headers.append is that if the specified header already exists and accepts multiple values, set() overwrites the existing value with the new one, whereas headers.append appends the new value to the end of the set of values. for security reasons, some headers can only be controller by the user agent. these headers include the forbidden header names and forbidden response header names. syntax myheaders.set(name, value); parameters name the name of the http header you want to set to a new value. if the given name is not the name of an http header, this method throws a typeerror. value the new value you want to set. returns voi...
Headers - Web APIs
Web › API › Headers
include retrieving, setting, adding to, and removing headers from the list of the request's headers. a headers object has an associated header list, which is initially empty and consists of zero or more name and value pairs. you can add to this using methods like append() (see examples.) in all methods of this interface, header names are matched by case-insensitive byte sequence. for security reasons, some headers can only be controlled by the user agent. these headers include the forbidden header names and forbidden response header names. a headers object also has an associated guard, which takes a value of immutable, request, request-no-cors, response, or none. this affects whether the set(), delete(), and append() methods will mutate the header. for more information see guard. you can ...
HmacImportParams - Web APIs
e can take a value of sha-256, sha-384, or sha-512. warning: although you can technically pass sha-1 here, this is strongly discouraged as it is considered vulnerable. length optional a number representing the length in bits of the key. if this is omitted the length of the key is equal to the length of the digest generated by the digest function you have chosen. unless you have a good reason to use a different length, omit this property and use the default. examples see the examples for subtlecrypto.importkey(). specifications specification status comment web cryptography apithe definition of 'subtlecrypto.hmacimportparams' in that specification. recommendation ...
HmacKeyGenParams - Web APIs
name a domstring. this should be set to hmac. hash a domstring representing the name of the digest function to use. you can pass any of sha-1, sha-256, sha-384, or sha-512 here. length optional a number — the length in bits of the key. if this is omitted the length of the key is equal to the length of the digest generated by the digest function you have chosen. unless you have a good reason to use a different length, omit this property and use the default. examples see the examples for subtlecrypto.generatekey(). specifications specification status comment web cryptography apithe definition of 'subtlecrypto.hmackeygenparams' in that specification. recommendation ...
IDBDatabase.transaction() - Web APIs
isk. the complete event may thus be delivered quicker than before, however, there exists a small chance that the entire transaction will be lost if the os crashes or there is a loss of system power before the data is flushed to disk. since such catastrophic events are rare most consumers should not need to concern themselves further. note: in firefox, if you wish to ensure durability for some reason (e.g. you're storing critical data that cannot be recomputed later) you can force a transaction to flush to disk before delivering the complete event by creating a transaction using the experimental (non-standard) readwriteflush mode (see idbdatabase.transaction.) this is currently experimental, and can only be used if the dom.indexeddb.experimental pref is set to true in about:config. detai...
IDBDatabaseException - Web APIs
an object store did not exist but was being opened. quota_err 11 either there's not enough remaining storage space or the storage quota was reached and the user declined to give more space to the database. read_only_err 9 a mutation operation was attempted in a read_only transaction. timeout_err 10 a lock for the transaction could not be obtained in a reasonable time. transaction_inactive_err 7 a request was made against a transaction that is either not currently active or is already finished. unknown_err 1 the operation failed for reasons unrelated to the database itself, and it is not covered by any other error code--for example, a failure due to disk io errors. ver_err 12 a request to open a database wi...
IDBRequest.error - Web APIs
Web › API › IDBRequest › error
r. constrainterror if you insert data that doesn't conform to a constraint. it's an exception type for creating stores and indexes. you get this error, for example, if you try to add a new key that already exists in the record. quotaexceedederror if you run out of disk quota and the user declined to grant you more space. unknownerror if the operation failed for reasons unrelated to the database itself. a failure due to disk io errors is such an example. noerror if the request succeeds. versionerror if you try to open a database with a version lower than the one it already has. in addition to the error codes sent to the idbrequest object, asynchronous operations can also raise exceptions. the list describes problems that could occ...
IDBTransaction: abort event - Web APIs
the abort event is fired when an indexeddb transaction is aborted. bubbles yes cancelable no interface event event handler property onabort this can happen for any of the following reasons: bad requests, (for example, trying to add the same key twice, or put the same index key when the key has a uniqueness constraint), an explicit abort() call an uncaught exception in the request's success/error handler, an i/o error (an actual failure to write to disk, for example disk detached, or other os/hardware failure) quota exceeded. 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. // open th...
IDBTransaction.oncomplete - Web APIs
ntially before that data has actually been flushed to disk. the complete event may thus be delivered quicker than before, however, there exists a small chance that the entire transaction will be lost if the os crashes or there is a loss of system power before the data is flushed to disk. note: this feature is available in web workers. note: in firefox, if you wish to ensure durability for some reason (e.g. you're storing critical data that cannot be recomputed later) you can force a transaction to flush to disk before delivering the complete event by creating a transaction using the experimental (non-standard) readwriteflush mode (see idbdatabase.transaction.) this is currently experimental, and can only be used if the dom.indexeddb.experimental pref is set to true in about:config. syntax ...
IIRFilterNode - Web APIs
the parameters of the filter response be specified, so that it can be tuned as needed. number of inputs 1 number of outputs 1 channel count mode "max" channel count same as on the input channel interpretation "speakers" typically, it's best to use the biquadfilternode interface to implement higher-order filters. there are several reasons why: biquad filters are typically less sensitive to numeric quirks. the filter parameters of biquad filters can be automated. all even-ordered iir filters can be created using biquadfilternode. however, if you need to create an odd-ordered iir filter, you'll need to use iirfilternode. you may also find this interface useful if you don't need automation, or for other reasons. once the no...
Basic concepts - Web APIs
hed to disk. the event may thus be delivered quicker than before, however, there exists a small chance that the entire transaction will be lost if the os crashes or there is a loss of system power before the data is flushed to disk. since such catastrophic events are rare, most consumers should not need to concern themselves further. note: in firefox, if you wish to ensure durability for some reason (e.g. you're storing critical data that cannot be recomputed later) you can force a transaction to flush to disk before delivering the complete event by creating a transaction using the experimental (non-standard) readwriteflush mode (see idbdatabase.transaction.) this is currently experimental, and can only be used if the dom.indexeddb.experimental pref is set to true in about:config. objec...
Checking when a deadline is due - Web APIs
he current time and date. if they do, we want to let the user know with some kind of notification. this would be easy if we were just comparing two date objects, but of course humans don't want to enter deadline information in the same format javascript understands. human-readable dates are quite different, with a number of different representations. recording the date information to provide a reasonable user experience on mobile devices, and to cut down on ambiguities, i decided to create an html form with: a text input for entering a title for your to-do list. this is the least avoidable bit of user typing. number inputs for the hour and minute parts of the deadline. on browsers that support type="number", you get a nice little up and down arrow number picker. on mobile platforms you ...
Using IndexedDB - Web APIs
ctually been flushed to disk. the complete event may thus be delivered quicker than before, however, there exists a small chance that the entire transaction will be lost if the os crashes or there is a loss of system power before the data is flushed to disk. since such catastrophic events are rare most consumers should not need to concern themselves further. if you must ensure durability for some reason (e.g. you're storing critical data that cannot be recomputed later) you can force a transaction to flush to disk before delivering the complete event by creating a transaction using the experimental (non-standard) readwriteflush mode (see idbdatabase.transaction. you can speed up data access by using the right scope and mode in the transaction. here are a couple of tips: when defining the sc...
Timing element visibility with the Intersection Observer API - Web APIs
new one. although many aspects of this example will not match real world usage (in particular, the articles all have the same text and aren't loaded from a database, and there are just a handful of simple text-only ads that are selected from an array), this should provide enough understanding of the api to quickly learn how to apply the intersection observer api to your own site. there's a good reason why the notion of tracking visibility of ads is being used in this example. it turns out that one of the most common uses of flash or other script in advertising on the web is to record how long each ad is visible, for the purpose of billing and payment of revenues. without the intersection observer api, this winds up being done using intervals and timeouts for each individual ad, or other techni...
Intersection Observer API - Web APIs
port. historically, detecting visibility of an element, or the relative visibility of two elements in relation to each other, has been a difficult task for which solutions have been unreliable and prone to causing the browser and the sites the user is accessing to become sluggish. as the web has matured, the need for this kind of information has grown. intersection information is needed for many reasons, such as: lazy-loading of images or other content as a page is scrolled. implementing "infinite scrolling" web sites, where more and more content is loaded and rendered as you scroll, so that the user doesn't have to flip through pages. reporting of visibility of advertisements in order to calculate ad revenues. deciding whether or not to perform tasks or animation processes based on wheth...
InterventionReportBody - Web APIs
the interventionreportbody interface of the reporting api represents the body of an intervention report (the return value of its report.body property). an intervention report is generated when usage of a feature in a web document has been blocked by the browser for reasons such as security, performance, or user annoyance. so for example, a script was been stopped because it was significantly slowing down the browser, or the browser's autoplay policy blocked audio from playing without a user gesture to trigger it. properties id a string representing the intervention that generated the report. this can be used to group reports by deprecated feature. message a string containing a human-readable description of the intervention, including information such how the intervention could...
KeyboardEvent: code values - Web APIs
these tables show those variations when known. code values code values on windows this table shows the windows scan codes representing keys and the keyboardevent.code values which correspond to those hardware keys. only keys which generate scan codes on windows are listed. ...
LocalMediaStream - Web APIs
his interface has been removed from the specification. warning: this interface is no longer available in any mainstream browser. do not use localmediastream; you need to update any code that does use it as soon as possible or your content or application will stop working. see stopping a video stream in mediastreamtrack to learn how. all other functionality is found in mediastream. the primary reason for this interface to exist was to add a stop() method to its mediastream parent interface. however, control over playback of media has been moved to the individual mediastreamtrack objects, so this is no longer necessary. instead, media is stopped by calling mediastreamtrack.stop() on each track that needs to be stopped. the example for mediastreamtrack.stop() demonstrates how to stop a multi-tr...
LockedFile.flush() - Web APIs
Web › API › LockedFile › flush
non-standard this feature is non-standard and is not on a standards track. do not use it on production sites facing the web: it will not work for every user. there may also be large incompatibilities between implementations and the behavior may change in the future. summary the flush method is used to ensure any change made to a file is properly written on disk. for performance reasons, a lockedfile object buffers all its operation in memory. this allows fast writing and reading operations. periodically, the data are written onto disk. however, if something goes wrong before that, some operations can be lost. to avoid that, it's possible to force a write onto the disk by calling the flush method. syntax var request = instanceoflockedfile.flush(); return a filerequest objec...
MSCandidateWindowUpdate - Web APIs
. syntax event property object.oncandidatewindowupdate = handler; addeventlistener method object.addeventlistener("mscandidatewindowupdate", handler, usecapture) parameters pevtobj [in] type: ihtmleventobj pointer to an ihtmleventobj interface for the current event. tan ime candidate window may be identified as needing to change size for any of the following reasons: as a result of displaying new / changed alternatives or predictions web applications need only register for this event once per element (the handler will remain valid for the lifetime of the element). see also microsoft api extensions ime handling guide for gecko ...
MediaDeviceInfo.label - Web APIs
the label readonlyinline property of the mediadeviceinfo interface returns a domstring, that is a label describing this device (for example "external usb webcam"). only available during active mediastream use, or when persistent permissions have been granted. syntax var label = mediadeviceinfo.label; value a domstring which describes the media device. for security reasons, the label is always an empty string ("") if the user has not obtained permission to use at least one media device, either by starting a stream from the microphone or camera, or by persistent permissions being granted. specifications specification status comment media capture and streamsthe definition of 'label' in that specification. candidate recommendation initial definition. ...
MediaDeviceInfo - Web APIs
group identifier if they belong to the same physical device — for example a monitor with both a built-in camera and a microphone. mediadeviceinfo.kindread only returns an enumerated value that is either "videoinput", "audioinput" or "audiooutput". mediadeviceinfo.labelread only returns a domstring that is a label describing this device (for example "external usb webcam"). for security reasons, the label field is always blank unless an active media stream exists or the user has granted persistent permission for media device access. the set of device labels could otherwise be used as part of a fingerprinting mechanism to identify a user. methods none. example here's an example that uses enumeratedevices() to get a list of devices. if (!navigator.mediadevices || !navigator.mediade...
MediaDevices.getDisplayMedia() - Web APIs
ted. typeerror the specified constraints include constraints which are not permitted when calling getdisplaymedia(). these unsupported constraints are advanced and any constraints which in turn have a member named min or exact. usage notes privacy and security because getdisplaymedia() could be used in nefarious ways, it can be a source of significant privacy and security concerns. for that reason, the specification details measures browsers are required to take in order to fully support getdisplaymedia(). the specified constraints can't be used to limit the options available to the user. instead, they must be applied after the user chooses a source, in order to generate output that matches the constraints. the go-ahead permission to use getdisplaymedia() cannot be persisted for reuse.
MediaRecorder: dataavailable event - Web APIs
examples using addeventlistener to listen for dataavailable events: ... ...
MediaSessionActionDetails - Web APIs
possible method to seek the media. fastseek is not included on the final action in the seek sequence in this situation. seekoffset optional if the action is either seekforward or seekbackward and this property is present, it is a floating point value which indicates the number of seconds to move the play position forward or backward. if this property isn't present, those actions should choose a reasonable default distance to skip forward or backward (such as 7 or 10 seconds). seektime optional if the action is seekto, this property must be present and must be a floating-point value indicating the absolute time within the media to move the playback position to, where 0 indicates the beginning of the media. this property is not present for other action types. media action types a media sess...
MediaStreamTrack.onended - Web APIs
syntax mediastreamtrack.onended = function; value a function to serve as an eventhandler for the ended event. ...
Using the MediaStream Recording API - Web APIs
pped in a test that checks whether getusermedia is supported before running anything else. next, we call getusermedia() and inside it define: the constraints: only audio is to be captured for our dictaphone. the success callback: this code is run once the getusermedia call has been completed successfully. the error/failure callback: the code is run if the getusermedia call fails for whatever reason. note: all of the code below is placed inside the getusermedia success callback. capturing the media stream once getusermedia has created a media stream successfully, you create a new media recorder instance with the mediarecorder() constructor and pass it the stream directly. this is your entry point into using the mediarecorder api — the stream is now ready to be captured into a blob, i...
MediaTrackSettings.latency - Web APIs
fied in seconds) of the mediastreamtrack as currently configured. this lets you determine what value was selected to comply with your specified constraints for this property's value as described in the mediatrackconstraints.latency property you provided when calling either getusermedia() or mediastreamtrack.applyconstraints(). this is, of course, an approximation, since latency can vary for many reasons including cpu, transmission, and storage overhead. if needed, you can determine whether or not this constraint is supported by checking the value of mediatracksupportedconstraints.latency as returned by a call to mediadevices.getsupportedconstraints(). however, typically this is unnecessary since browsers will simply ignore any constraints they're unfamiliar with. because rtp doesn't include t...
Using the Media Capabilities API - Web APIs
d ? '' : 'not ') + 'supported, ' + (result.smooth ? '' : 'not ') + 'smooth, and ' + (result.powerefficient ? '' : 'not ') + 'power efficient.') }); the response provided is defined by the mediacapabilitiesinfo interface. handling errors in our video decoding example, a typeerror would be raised if the media configuration passed to the decodinginfo() method was invalid. there are a few reasons why an error might occur, including: the specified type isn't one of the two permtited values: file or media-source the contenttype given is the error can be due to the type not being one of the two possible values, the contenttype not being a valid codec mime type, or invalid or omitted definitions required in the videoconfiguration. navigator.mediacapabilities.decodinginfo(videoconfigur...
Transcoding assets for Media Source Extensions - Web APIs
eferences. see the building instructions for more details. the prebuilt file is here. put the contents of the bin directory in the same place as ffmpeg. python2 — bento4 uses it. get these installed successfully before moving to the next step. sample media should be placed in the bento4 utils directory and worked here. note: the prebuilt ffmpeg does not include libfdk_aac due to licensing reasons. bento4 uses this by default, so you need to compile ffmpeg if necessary. if you don't need it, add --audio-codec=aac to the mp4-dash-encode.py command line. container and codec support as specified in section 1.1 of the mse spec: goals, mse is designed not to require support for any particular media format or codec. while this is true on paper, browser support varies for specific container/...
MutationEvent - Web APIs
e the mutation events have been marked as deprecated in the dom events specification, as the api's design is flawed (see details in the "dom mutation events replacement: the story so far / existing points of consensus" post to public-webapps). mutation observers are the proposed replacement for mutation events in dom4. they are expected to be included in firefox 14 and chrome 18. the practical reasons to avoid the mutation events are performance issues and cross-browser support. performance adding dom mutation listeners to a document profoundly degrades the performance of further dom modifications to that document (making them 1.5 - 7 times slower!). moreover, removing the listeners does not reverse the damage. the performance effect is limited to the documents that have the mutation event...
Navigator.geolocation - Web APIs
the navigator.geolocation read-only property returns a geolocation object that gives web content access to the location of the device. this allows a web site or app to offer customized results based on the user's location. note: for security reasons, when a web page tries to access location information, the user is notified and asked to grant permission. be aware that each browser has its own policies and methods for requesting this permission. syntax geo = navigator.geolocation specifications specification status comment geolocation apithe definition of 'navigator.geolocation' in that specification. recommendation initial definition ...
Navigator.registerContentHandler() - Web APIs
syntax navigator.registercontenthandler(mimetype, uri, title); mimetype is the desired mime type as a string. uri is the uri to the handler as a string. title is the title of the handler presented to the user as a string. ...
Navigator.registerProtocolHandler() - Web APIs
is invalid, such as a scheme the browser handles itself (https:, about:, etc.) the handler url’s origin does not match the origin of the page calling this api. the browser requires that this function is called from a secure context. the browser requires that the handler's url be over https. syntaxerror the %s placeholder is missing from the handler url. permitted schemes for security reasons, registerprotocolhandler() restricts which schemes can be registered. a custom scheme may be registered as long as: the custom scheme's name begins with web+ the custom scheme's name includes at least 1 letter after the web+ prefix the custom scheme has only lowercase ascii letters in its name. for example, web+burger, as shown in the example below. otherwise, the scheme must be one of ...
Online and offline events - Web APIs
eports a change in network connectivity on windows, linux, and os x. you can register listeners for these events in a few familiar ways: using addeventlistener on the window, document, or document.body by setting the .ononline or .onoffline properties on document or document.body to a javascript function object. (note: using window.ononline or window.onoffline will not work for compatibility reasons.) by specifying ononline="..." or onoffline="..." attributes on the <body> tag in the html markup. example there's a simple test case that you can run to verify that the events are working (does not work in chrome due to attaching the event listener to document.body). here's the javascript part: window.addeventlistener('load', function() { var status = document.getelementbyid("status"); ...
Node.rootNode - Web APIs
Web › API › Node › rootNode
the node.rootnode read-only property returns a node object representing the topmost node in the tree, or the current node if it's the topmost node in the tree. this is found by walking backward along node.parentnode until the top is reached. syntax rootnode = node.rootnode; value a node object representing the topmost node in the tree. example running the following line in supporting browsers should return a reference to the html/document node: console.log(document.body.rootnode); notes gecko-based browsers insert text nodes into a document to represent whitespace in the source markup. ...
Using the Notifications API - Web APIs
rm or by the user, the close steps for it must be run." notification events there are four events that are triggered on the notification instance: click triggered when the user clicks on the notification. close triggered once the notification is closed. error triggered if something goes wrong with the notification; this is usually because the notification couldn't be displayed for some reason. show triggered when the notification is displayed to the user. these events can be tracked using the onclick, onclose, onerror, and onshow handlers. because notification also inherits from eventtarget, it's possible to use the addeventlistener() method on it. replacing existing notifications it is usually undesirable for a user to receive a lot of notifications in a short space of time —...
OfflineAudioCompletionEvent.OfflineAudioCompletionEvent() - Web APIs
syntax var offlineaudiocompletionevent = new offlineaudiocompletionevent(type, init) parameters type optional a domstring representing the type of object to create. ...
OfflineAudioCompletionEvent - Web APIs
the web audio api offlineaudiocompletionevent interface represents events that occur when the processing of an offlineaudiocontext is terminated. the complete event implements this interface. note: this interface is marked as deprecated; it is still supported for legacy reasons, but it will soon be superseded when the promise version of offlineaudiocontext.startrendering is supported in browsers, which will no longer need it. constructor offlineaudiocompletionevent.offlineaudiocompletionevent creates a new offlineaudiocompletionevent object instance. properties also inherits properties from its parent, event. offlineaudiocompletionevent.renderedbuffer read only an audiobuffer containing the result of processing an offlineaudiocontext. methods inherits methods from its parent,...
OfflineAudioContext.startRendering() - Web APIs
e complete event (of type offlineaudiocompletionevent) is raised when the rendering is finished, containing the resulting audiobuffer in its renderedbuffer property. browsers currently support two versions of the startrendering() method — an older event-based version and a newer promise-based version. the former will eventually be removed, but currently both mechanisms are provided for legacy reasons. 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. returns void. example in this simple example, we declare both an audiocontext and an off...
OfflineAudioContext.suspend() - Web APIs
ules a suspension of the time progression in the audio context at the specified time and returns a promise. this is generally useful at the time of manipulating the audio graph synchronously on offlineaudiocontext. note that the maximum precision of suspension is the size of the render quantum and the specified suspension time will be rounded down to the nearest render quantum boundary. for this reason, it is not allowed to schedule multiple suspends at the same quantized frame. also scheduling should be done while the context is not running to ensure the precise suspension. syntax offlineaudiocontext.suspend(suspendtime).then(function() { ... }); parameters suspendtime a double specifying the suspend time, in seconds. returns a promise resolving to void. exceptions the promise is r...
PaymentRequest: shippingaddresschange event - Web APIs
hange event is sent to the paymentrequest object when the user selects a shipping address or changes details of their shipping address. bubbles no cancelable no interface paymentrequestupdateevent event handler property onshippingaddresschange usage notes depending on the browser, the shipping address information may be redacted for privacy reasons. that is, the paymentaddress which contains the shipping address may have some portions of its content altered, obscured, or left out entirely in order to prevent identifying the user without their consent (since if they choose to have you ship products to them, you'll need their address). example in this example, a handler for the shippingaddresschange event is set up to validate that the add...
PaymentResponse.complete() - Web APIs
candidate recommendation initial definition. browser compatibility the compatibility ...
PaymentResponse.retry() - Web APIs
essages for any of the fields in the shipping address that failed validation. return value a promise which is resolved when the payment is successfully completed. the promise is rejected with an appropriate exception value if the payment fails again. 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. the loop exits only when the user either cancels the payment request or the request is successful. see the example below for a thorough example, but the basic concept, in outline form, is: create a new paymentrequest (new paymentrequest()) display the payment r...
PointerEvent - Web APIs
fired when a pointer changes coordinates. pointerrawupdate this event is fired when any of a pointer's properties change. pointerup this event is fired when a pointer is no longer active. pointercancel a browser fires this event if it concludes the pointer will no longer be able to generate events (for example the related device is deactived). pointerout this event is fired for several reasons including: pointing device is moved out of the hit test boundaries of an element; firing the pointerup event for a device that does not support hover (see pointerup); after firing the pointercancel event (see pointercancel); when a pen stylus leaves the hover range detectable by the digitizer. pointerleave this event is fired when a pointing device is moved out of the hit test boundaries of an...
Pointer events - Web APIs
change in pointer state can not be reported by other events. pointerup onpointerup fired when a pointer is no longer active buttons state. pointercancel onpointercancel a browser fires this event if it concludes the pointer will no longer be able to generate events (for example the related device is deactived). pointerout onpointerout fired for several reasons including: pointer is moved out of the hit test boundaries of an element; firing the pointerup event for a device that does not support hover (see pointerup); after firing the pointercancel event (see pointercancel); when a pen stylus leaves the hover range detectable by the digitizer. pointerleave onpointerleave fired when a pointer is moved out of the hit test boundaries of an e...
PushSubscription.endpoint - Web APIs
the endpoint read-only property of the pushsubscription interface returns a usvstring containing the endpoint associated with the push subscription. the endpoint takes the form of a custom url pointing to a push server, which can be used to send a push message to the particular service worker instance that subscribed to the push service. for this reason, it is a good idea to keep your endpoint a secret, so others do not hijack it and abuse the push functionality. syntax var myend = pushsubscription.endpoint; value a usvstring. 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 // endp...
RTCConfiguration.iceTransportPolicy - Web APIs
portpolicy; value a domstring which indicates what ice candidate policy the ice agent should use during the negotiation process, per the jsep standard. the permitted values are: all the ice agent is permitted to use any kind of candidate, including both local and relay candidates. the agent—or the browser itself—may still perform some form of ip filtering on the incoming candidates for reasons including privacy and security, as well as to simply limit the number of candidates. this is the default. relay the ice agent only considers media relay candidates when evaluating candidates. this includes, for example, those candidates relayed by a stun or turn server. this can be used to prevent the remote endpoint from receiving the user's ip addresses, which may be important in some se...
RTCDTMFSender - Web APIs
peerconnection. you gain access to the connection's rtcdtmfsender through the rtcrtpsender.dtmf property on the audio track you wish to send dtmf with. the primary purpose for webrtc's dtmf support is to allow webrtc-based communication clients to be connected to a public-switched telephone network (pstn) or other legacy telephone service, including extant voice over ip (voip) services. for that reason, dtmf can't be used between two webrtc-based devices, because there is no mechanism provided by webrtc for receiving dtmf codes. <div id="interfacediagram" style="display: inline-block; position: relative; width: 100%; padding-bottom: 11.666666666666666%; vertical-align: middle; overflow: hidden;"><svg style="display: inline-block; position: absolute; top: 0; left: 0;" viewbox="-50 0 600 70"...
RTCDtlsTransport - Web APIs
ype of media (audio, video, or data channel). thus, a connection that has any number of audio and video channels will always have exactly one dtls transport for audio and one for video communications. because transports are established early in the negotiation process, it's likely that it won't be known until after they're created whether or not the remote peer supports bundling or not. 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 r...
RTCIceCandidate.relatedPort - Web APIs
didate. for relay candidates, the related address and port provide the mapped address selected by the turn server. for host candidates, relatedport is null, meaning the field is not included in the candidate's a-line. usage notes the related address and port are not used by ice itself, and are only present for diagnostic and quality-of-service purposes. they may in fact be omitted for security reasons, but if present can be a useful tool during debugging. see the example, which shows a bit of this. here's an sdp attribute line (a-line) describing an ice candidate discovered by the stun server: a=candidate:4234997325 1 udp 2043278322 192.168.0.56 6502 typ srflx raddr 192.168.2.77 rport 32768 generation 0 the remote port, relatedport, is the number immediately following the "rport" label on ...
RTCIceCandidate.usernameFragment - Web APIs
usage notes ice uses the usernamefragment and password to ensure message integrity. this avoids crosstalk among multiple ongoing ice sessions, but, more importantly, helps secure ice transactions (and all of webrtc by extension) against attacks that might try to inject themselves into an ice exchange. note: there is no api to obtain the ice password, for what should be fairly obvious security reasons. the usernamefragment and password both change every time an ice restart occurs. example although the webrtc infrastructure will filter out obsolete candidates for you after an ice restart, you can do it yourself if you're trying to absolutely minimize the number of messages going back and forth. to do so, you can compare the value of usernamefragment to the current usernamefragment being u...
RTCIceCandidatePairStats.state - Web APIs
re no checks ongoing which block the pair from being analyzed, it is unfrozen and moves into the waiting state. this may happen immediately upon being added to the check list. each time a candidate pair is done being checked, the next-highest priority candidate pair remaining on the check list moves from the waiting state to the in-progress state, and its check begins. if the check fails for any reason, the pair moves into its final state, failed. if the check succeeds, the pair ends up in the succeeded state. the ice check list state for any given pair of ice candidates can be found in the corresponding the state property. specifications specification status comment identifiers for webrtc's statistics apithe definition of 'rtcicecandidatepairstats.state' in that ...
RTCIceCandidateStats.networkType - Web APIs
max the described connection uses a wimax network. vpn the connection uses a virtual private network (vpn). the vpn obscures the underlying network type, which is not discernible. unknown the user's browser is unable or unwilling to identify the underlying connection technology used by the described connection. this may be because the browser isn't able to determine the network type for some reason or it may be intentionally getting obscured for security reasons, such as to avoid device fingerprinting. note: keep in mind that the specified value only reflects the initial connection between the local peer and the next hop along the network toward reaching the remote peer. for example, if the networktype is wifi but the user is connected using a cellular hotspot, the connection will be bot...
RTCInboundRtpStreamStats.bytesReceived - Web APIs
tats.bytesreceived; value an unsigned integer value indicating the total number of bytes received so far on this rtp stream, not including header and padding bytes. this value can be used to calculate an approximation of the average media data rate: avgdatarate = rtcinboundrtpstreamstats.bytesreceived / elapsedtime; this value gets reset to zero if the sender's ssrc identifier changes for any reason. specifications specification status comment identifiers for webrtc's statistics apithe definition of 'rtcinboundrtpstreamstats.bytesreceived' in that specification. candidate recommendation initial definition. ...
RTCNetworkType - Web APIs
max the described connection uses a wimax network. vpn the connection uses a virtual private network (vpn). the vpn obscures the underlying network type, which is not discernible. unknown the user's browser is unable or unwilling to identify the underlying connection technology used by the described connection. this may be because the browser isn't able to determine the network type for some reason or it may be intentionally getting obscured for security reasons, such as to avoid device fingerprinting. note: keep in mind that the specified value only reflects the initial connection between the local peer and the next hop along the network toward reaching the remote peer. for example, if the networktype is wifi but the user is connected using a cellular hotspot, the connection will be bot...
RTCOutboundRtpStreamStats - Web APIs
has notified this rtcrtpsender that some amount of encoded video data for one or more frames has been lost, using picture loss indication (pli) packets. only available for video streams. qpsum a 64-bit value containing the sum of the qp values for every frame encoded by this rtcrtpsender. valid only for video streams. qualitylimitationdurations a record mapping each of the quality limitation reasons in the rtcremoteinboundrtpstreamstats enumeration to a floating-point value indicating the number of seconds the stream has spent with its quality limited for that reason. qualitylimitationreason a value from the rtcqualitylimitationreason enumerated type explaining why the resolution and/or frame rate is being limited for this rtp stream. valid only for video streams. remoteid a string whic...
RTCPeerConnection.createAnswer() - Web APIs
ck an rtcpeerconnectionerrorcallback which will be passed a single domexception object explaining why the request to create an answer failed. options optional an optional rtcofferoptions object providing options requested for the answer. exceptions notreadableerror the identity provider wasn't able to provide an identity assertion. operationerror generation of the sdp failed for some reason; this is a general failure catch-all exception. return value a promise whose fulfillment handler is called with an object conforming to the rtcsessiondescriptioninit dictionary which contains the sdp answer to be delivered to the other peer. example here is a segment of code taken from the code that goes with the article signaling and video calling. this code comes from the handler for the m...
RTCPeerConnection: icecandidate event - Web APIs
rtcpeerconnection.setlocaldescription(). the event handler should transmit the candidate to the remote peer over the signaling channel so the remote peer can add it to its set of remote candidates. bubbles no cancelable no interface rtcpeerconnectioniceevent event handler property rtcpeerconnection.onicecandidate description there are three reasons why the icecandidate event is fired on an rtcpeerconnection. sharing a new candidate the majority of icecandidate events are fired to indicate that a new candidate has been gathered. this candidate needs to be delivered to the remote peer over the signaling channel your code manages. rtcpeerconnection.onicecandidate = (event) => { if (event.candidate) { sendcandidatetoremotepeer(event.c...
RTCPeerConnection.onicegatheringstatechange - Web APIs
the rtcpeerconnection.onicegatheringstatechange property is an eventhandler which specifies a function to be called when the icegatheringstatechange event is sent to an rtcpeerconnection instance. this happens when the ice gathering state—that is, whether or not the ice agent is actively gathering candidates—changes. you don't need to watch for this event unless you have specific reasons to want to closely monitor the state of ice gathering. syntax rtcpeerconnection.onicegatheringstatechange = eventhandler; value a function you provide which is passed a single parameter: an event object containing the icegatheringstatechange event. you can determine the new state of ice gathering by looking at the value of the rtcpeerconnection.icegatheringstate property. example this example upda...
RTCPeerConnection.setConfiguration() - Web APIs
s in which this might be done: the rtcpeerconnection was instantiated without specifying any ice servers. 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. renegotiation of the connection is needed, and a different set of ice servers needs to be used for some reason. perhaps the user has moved into a new region, so using new regional ice servers is necessary, for example. in this situation, one might call setconfiguration() to switch to new regional ice servers, then initiate an ice restart. you cannot change the identity information for a connection once it's already been set. syntax rtcpeerconnection.setconfiguration(configuration); parameters co...
RTCPeerConnection.setLocalDescription() - Web APIs
riptioninit, which is a serialized version of a rtcsessiondescription browser object. 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. return value a promise which is fulfilled once the value of rtcpeerconnection.localdescription is successfully changed or rejected if the change cannot be applied (for example, if the specified description is incompatible with one or both of the peers on the connection). the promise's fulfillment handler receives no input parameters. the...
RTCPeerConnectionIceErrorEvent - Web APIs
nly an unsigned integer value stating the numeric stun error code returned by the stun or turn server. if no host candidate can reach the server, this property is set to the number 701, which is outside the range of valid stun error codes. the 701 error is fired only once per server url, and only while the is icegatheringstate is gathering. errortext read only a domstring containing the stun reason text returned by the stun or turn server. if communication with the stun or turn server couldn't be established at all, this string will be a browser-specific string explaining the error. port read only an unsigned integer value giving the port number over which communication with the stun or turn server is taking place, using the ip address given in address. null if the connection hasn't been...
RTCRtpReceiver.getCapabilities() static function - Web APIs
is loaded, fetched, or otherwise prepared. it's simply a means of determining what might be usable before starting to try to access media. because the set of capabilities available tend to be stable for a length of time (people don't install and uninstall codecs and the like very often), the media capabilities can in whole or in part provide a cross-origin method for identifying a user. for that reason, in privacy-sensitive contexts, the browser may choose to obscure the capabilities; this might be done, for example, by leaving out rarely-used codec configurations. example the function below returns a boolean indicating whether or not the device supports receiving h.264 video on a webrtc connection. since rtcrtpreceiver.getcapabilities() actually only indicates probable support, attempting ...
RTCRtpSender.getCapabilities() static function - Web APIs
is loaded, fetched, or otherwise prepared. it's simply a means of determining what might be usable before starting to try to access media. because the set of capabilities available tend to be stable for a length of time (people don't install and uninstall codecs and the like very often), the media capabilities can in whole or in part provide a cross-origin method for identifying a user. for that reason, in privacy-sensitive contexts, the browser may choose to obscure the capabilities; this might be done, for example, by leaving out rarely-used codec configurations. example the function below returns a boolean indicating whether or not the device supports sending h.264 video on an rtcrtpsender. since rtcrtpsender.getcapabilities() actually only indicates probable support, h.264 support might...
RTCRtpSender.replaceTrack() - Web APIs
ck); parameters newtrack optional a mediastreamtrack specifying the track with which to replace the rtcrtpsender's current source track. the new track's kind must be the same as the current track's, or the replace track request will fail. return value a promise which is fulfilled once the track has been successfully replaced. the promise is rejected if the track cannot be replaced for any reason; this is commonly because the change would require renegotiation of the codec, which is not allowed (see things that require negotiation). if newtrack was omitted or was null, replacetrack() simply stops the sender. no negotiation is required in this case. when the promise is fulfilled, the fulfillment handler receives a value of undefined. exceptions if the returned promise is rejected, one ...
RTCRtpTransceiver.stopped - Web APIs
the read-only stopped property on the rtcrtptransceiver interface indicates whether or not the transceiver's associated sender and receiver have both been stopped. the transceiver is stopped if the stop() method has been called or if a change to either the local or the remote description has caused the transceiver to be stopped for some reason. syntax var isstopped = rtcrtptransceiver.stopped; value a boolean value which is true if the transceiver's sender will no longer send data, and its receiver will no longer receive data. if either or both are still at work, the result is false. usage notes this property is deprecated and will be removed in the future. instead, look at the value of currentdirection. its value is stopped if the transceiver has stopped. note: currently only firefo...
Range.createContextualFragment() - Web APIs
tecontextualfragment() method returns a documentfragment by invoking the html fragment parsing algorithm or the xml fragment parsing algorithm with the start of the range (the parent of the selected node) as the context node. the html fragment parsing algorithm is used if the range belongs to a document whose htmlness bit is set. in the html case, if the context node would be html, for historical reasons the fragment parsing algorithm is invoked with body as the context instead. syntax documentfragment = range.createcontextualfragment(tagstring) parameters tagstring text that contains text and tags to be converted to a document fragment. example var tagstring = "<div>i am a div node</div>"; var range = document.createrange(); // make the parent of the first div in the document become...
ReadableByteStreamController.close() - Web APIs
e closes the associated stream. note: readers will still be able to read any previously-enqueued chunks from the stream, but once those are read, the stream will become closed. syntax readablebytestreamcontroller.close(); parameters none. return value undefined. exceptions typeerror the source object is not a readablebytestreamcontroller, or the stream is not readable for some other reason. examples tbd. specifications specification status comment streamsthe definition of 'close()' in that specification. living standard initial definition. ...
ReadableByteStreamController.enqueue() - Web APIs
the enqueue() method of the readablebytestreamcontroller interface enqueues a given chunk in the associated stream. syntax readablebytestreamcontroller.enqueue(chunk); parameters chunk the chunk to enqueue. return value undefined. exceptions typeerror the source object is not a readablebytestreamcontroller, or the stream cannot be read for some other reason, or the chunk is not an object, or the chunk's internal array buffer is non-existant or detached. examples tbd. specifications specification status comment streamsthe definition of 'enqueue()' in that specification. living standard initial definition. ...
ReadableByteStreamController.error() - Web APIs
or() method of the readablebytestreamcontroller interface causes any future interactions with the associated stream to error. syntax readablebytestreamcontroller.error(e); parameters e the error you want future interactions to fail with. return value undefined. exceptions typeerror the source object is not a readablebytestreamcontroller, or the stream is not readable for some other reason. examples tbd. specifications specification status comment streamsthe definition of 'error()' in that specification. living standard initial definition. ...
ReadableStream.cancel() - Web APIs
the cancel() method of the readablestream interface cancels the associated stream. the supplied reason parameter will be given to the underlying source, which may or may not use it. cancel is used when you've completely finished with the stream and don't need any more data from it, even if there are chunks enqueued waiting to be read. that data is lost after cancel is called, and the stream is not readable any more. to read those chunks still and not completely get rid of the stream, you'd use readablestreamdefaultcontroller.close(). syntax var promise = readablestream.cancel(reason); parameters reason a domstring providing a human-readable reason for the cancellation. return value a promise, which fulfills with the value given in the reason parameter. exceptions typeerror the s...
ReadableStream - Web APIs
y property of a response object. constructor readablestream() creates and returns a readable stream object from the given handlers. properties readablestream.locked read only the locked getter returns whether or not the readable stream is locked to a reader. methods readablestream.cancel() cancels the stream, signaling a loss of interest in the stream by a consumer. the supplied reason argument will be given to the underlying source, which may or may not use it. readablestream.getiterator() creates a readablestream async iterator instance and locks the stream to it. while the stream is locked, no other reader can be acquired until this one is released. readablestream.getreader() creates a reader and locks the stream to it. while the stream is locked, no other reader c...
ReadableStreamBYOBReader.cancel() - Web APIs
the cancel() method of the readablestreambyobreader interface cancels the stream, signaling a loss of interest in the stream by a consumer. the supplied reason parameter will be given to the underlying source, which may or may not use it. note: if the reader is active, the cancel() method behaves the same as that for the associated stream (readablestream.cancel()). syntax var promise = readablestreambyobreader.cancel(reason); parameters reason a domstring providing a human-readable reason for the cancellation. return value a promise, which fulfills with the value given in the reason parameter. exceptions typeerror the source object is not a readablestreambyobreader, or the stream has no owner. examples tbd. specifications specification status comment ...
ReadableStreamBYOBReader - Web APIs
properties readablestreambyobreader.closed read only allows you to write code that responds to an end to the streaming process. returns a promise that fulfills if the stream becomes closed or the reader's lock is released, or rejects if the stream errors. methods readablestreambyobreader.cancel() cancels the stream, signaling a loss of interest in the stream by a consumer. the supplied reason argument will be given to the underlying source, which may or may not use it. readablestreambyobreader.read() returns a promise providing access to the next chunk in the stream's internal queue. readablestreambyobreader.releaselock() releases the reader's lock on the stream. examples tbd. specifications specification status comment streamsthe definition of 'readab...
ReadableStreamDefaultController.close() - Web APIs
a readablestreamdefaultcontroller. examples in the following simple example, a custom readablestream is created using a constructor (see our simple random stream example for the full code). the start() function generates a random string of text every second and enqueues it into the stream. a cancel() function is also provided to stop the generation if readablestream.cancel() is called for any reason. when a button is pressed, the generation is stopped, the stream is closed using readablestreamdefaultcontroller.close(), and another function is run, which reads the data back out of the stream. const stream = new readablestream({ start(controller) { interval = setinterval(() => { let string = randomchars(); // add the string to the stream controller.enqueue(string); ...
ReadableStreamDefaultController.enqueue() - Web APIs
examples in the following simple example, a custom readablestream is created using a constructor (see our simple random stream example for the full code). the start() function generates a random string of text every second and enqueues it into the stream — see controller.enqueue(string). a cancel() function is also provided to stop the generation if readablestream.cancel() is called for any reason. when a button is pressed, the generation is stopped, the stream is closed using readablestreamdefaultcontroller.close(), and another function is run, which reads the data back out of the stream. const stream = new readablestream({ start(controller) { interval = setinterval(() => { let string = randomchars(); // add the string to the stream controller.enqueue(string); ...
ReadableStreamDefaultController.error() - Web APIs
to error. note: the error() method can be called more than once, and can be called when the stream is not readable. syntax readablestreamdefaultcontroller.error(e); parameters e the error you want future interactions to fail with. return value undefined. exceptions typeerror the source object is not a readablestreamdefaultcontroller, or the stream is not readable for some other reason. examples the a readable stream with an underlying push source and backpressure support example in the spec provides a good example of using readablestreamdefaultcontroller.desiredsize to manually detect when the stream is full and apply backpressure, and also of using error() to manually trigger a stream error if another part of the system it relies on fails. specifications specifi...
ReadableStreamDefaultController - Web APIs
ith the associated stream to error. examples in the following simple example, a custom readablestream is created using a constructor (see our simple random stream example for the full code). the start() function generates a random string of text every second and enqueues it into the stream. a cancel() function is also provided to stop the generation if readablestream.cancel() is called for any reason. note that a readablestreamdefaultcontroller object is provided as the parameter of the start() and pull() functions. when a button is pressed, the generation is stopped, the stream is closed using readablestreamdefaultcontroller.close(), and another function is run, which reads the data back out of the stream. const stream = new readablestream({ start(controller) { interval = setinterva...
ReadableStreamDefaultReader - Web APIs
ties readablestreamdefaultreader.closed read only allows you to write code that responds to an end to the streaming process. returns a promise that fulfills if the stream becomes closed or the reader's lock is released, or rejects if the stream errors. methods readablestreamdefaultreader.cancel() cancels the stream, signaling a loss of interest in the stream by a consumer. the supplied reason argument will be given to the underlying source, which may or may not use it. readablestreamdefaultreader.read() returns a promise providing access to the next chunk in the stream's internal queue. readablestreamdefaultreader.releaselock() releases the reader's lock on the stream. examples in the following example, an artifical response is created to stream html fragments fetched from anot...
Reporting API - Web APIs
ec defines the following report types: deprecation report indicates that a webapi or other browser feature being used in the website is expected to stop working in a future release. indicated by a report.body property with a deprecationreportbody return value. intervention report indicates that a request made by the website has been denied by the browser, e.g. for security or user annoyance reasons. indicated by a report.body property with a interventionreportbody return value. crash report indicates that the website stopped running due to a browser crash. indicated by a report.body property with a crashreportbody return value. 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 = ...
Request.clone() - Web APIs
Web › API › Request › clone
syntax var newrequest = request.clone(); parameters none. return value a request object, which is an exact copy of the request that clone() was called on. ...
ResizeObserverEntry.contentRect - Web APIs
read-only property of the resizeobserverentry interface returns a domrectreadonly object containing the new size of the observed element when the callback is run. note that this is better supported than resizeobserverentry.borderboxsize or resizeobserverentry.contentboxsize, but it is left over from an earlier implementation of the resize observer api, is still included in the spec for web compat reasons, and may be deprecated in future versions. syntax var contentrect = resizeobserverentry.contentrect; value a domrectreadonly object containing the new size of the element indicated by the target property. if the target is an html element, the returned contentrect is the element's content box. if the target is an svgelement, the returned contentrect is the svg's bounding box. examples the ...
ResizeObserverEntry - Web APIs
ontent box size of the observed element when the callback is run. resizeobserverentry.contentrect read only a domrectreadonly object containing the new size of the observed element when the callback is run. note that this is better supported than the above two properties, but it is left over from an earlier implementation of the resize observer api, is still included in the spec for web compat reasons, and may be deprecated in future versions. resizeobserverentry.target read only a reference to the element or svgelement being observed. note: the content box is the box in which content can be placed, meaning the border box minus the padding and border width. the border box encompasses the content, padding, and border. see the box model for further explanation. methods none. examples ...
Response.clone() - Web APIs
Web › API › Response › clone
value a response object. ...
RsaHashedKeyGenParams - Web APIs
domstring. this should be set to rsassa-pkcs1-v1_5, rsa-pss, or rsa-oaep, depending on the algorithm you want to use. moduluslength a number. the length in bits of the rsa modulus. this should be at least 2048: see for example see nist sp 800-131a rev. 1. some organizations are now recommending that it should be 4096. publicexponent a uint8array. the public exponent. unless you have a good reason to use something else, specify 65537 here ([0x01, 0x00, 0x01]). hash a domstring representing the name of the digest function to use. you can pass any of sha-256, sha-384, or sha-512 here. warning: although you can technically pass sha-1 as a value here, this is strongly discouraged as sha-1 is considered vulnerable. examples see the examples for subtlecrypto.generatekey(). spec...
Screen.colorDepth - Web APIs
Web › API › Screen › colorDepth
see the browser compatibility section for those that don't. ...
Screen.pixelDepth - Web APIs
Web › API › Screen › pixelDepth
see the browser compatibility section for those that don't. ...
Service Worker API - Web APIs
hen the network is not available). a service worker is run in a worker context: it therefore has no dom access, and runs on a different thread to the main javascript that powers your app, so it is non-blocking. it is designed to be fully async; as a consequence, apis such as synchronous xhr and localstorage can't be used inside a service worker. service workers only run over https, for security reasons. having modified network requests, wide open to man in the middle attacks would be really bad. in firefox, service worker apis are also hidden and cannot be used when the user is in private browsing mode. 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 ...
SpeechRecognitionError.error - Web APIs
ror types are: no-speech no speech was detected. aborted speech input was aborted in some manner, perhaps by some user-agent-specific behavior like a button the user can press to cancel speech input. audio-capture audio capture failed. network network communication required for completing the recognition failed. not-allowed the user agent disallowed any speech input from occurring for reasons of security, privacy or user preference. service-not-allowed the user agent disallowed the requested speech recognition service, either because the user agent doesn't support it or because of reasons of security, privacy or user preference. in this case it would allow another more suitable speech recognition service to be used instead. bad-grammar there was an error in the speech recognition...
SpeechRecognitionErrorEvent.error - Web APIs
ror types are: no-speech no speech was detected. aborted speech input was aborted in some manner, perhaps by some user-agent-specific behavior like a button the user can press to cancel speech input. audio-capture audio capture failed. network network communication required for completing the recognition failed. not-allowed the user agent disallowed any speech input from occurring for reasons of security, privacy or user preference. service-not-allowed the user agent disallowed the requested speech recognition service, either because the user agent doesn't support it or because of reasons of security, privacy or user preference. in this case it would allow another more suitable speech recognition service to be used instead. bad-grammar there was an error in the speech recognition...
StorageEstimate - Web APIs
see the individual property pages for details. ...
StorageManager.estimate() - Web APIs
ate(); parameters none. return value a promise that resolves to an object which conforms to the storageestimate dictionary. this dictionary contains estimates of how much space is available to the origin in storageestimate.quota, as well as how much is currently used in storageestimate.usage. the returned values are not exact; between compression, deduplication, and obfuscation for security reasons, they will be imprecise. you may find that the quota varies from origin to origin. this variance is based on factors such as: how often the user visits public site popularity data user engagement signals like bookmarking, adding to homescreen, or accepting push notifications example in this example, we obtain the usage estimates and present the percentage of storage capacity currently ...
Storage Access API - Web APIs
tes. the storage access api is intended to solve this problem; embedded cross-origin content can request unrestricted access to its first-party storage on a site-by-site basis via the document.requeststorageaccess() method, and check whether it already has access via the document.hasstorageaccess() method. in addition, sandboxed <iframe>s cannot be granted storage access by default for security reasons. the api therefore also adds the allow-storage-access-by-user-activation sandbox token. the embedding website needs to add this to allow storage access requests to be successful, along with allow-scripts and allow-same-origin to allow it to call the api, and execute in an origin that can have cookies: <iframe sandbox="allow-storage-access-by-user-activation allow-scripts ...
SubtleCrypto.decrypt() - Web APIs
ulfills with an arraybuffer containing the plaintext. exceptions the promise is rejected when the following exceptions are encountered: invalidaccesserror raised when the requested operation is not valid for the provided key (e.g. invalid encryption algorithm, or invalid key for the specified encryption algorithm). operationerror raised when the operation failed for an operation-specific reason (e.g. algorithm parameters of invalid sizes, or there was an error decrypting the ciphertext). supported algorithms the decrypt() method supports the same algorithms as the encrypt() method. examples note: you can try the working examples on github. rsa-oaep this code decrypts ciphertext using rsa-oaep. see the complete code on github. function decryptmessage(privatekey, ciphertext) { ...
TouchEvent - Web APIs
also sent if the values of the radius, rotation angle, or force attributes of a touch point change. note: the rate at which touchmove events is sent is browser-specific, and may also vary depending on the capability of the user's hardware. you must not rely on a specific granularity of these events. touchcancel sent when a touch point has been disrupted in some way. there are several possible reasons why this might happen (and the exact reasons will vary from device to device, as well as browser to browser): an event of some kind occurred that canceled the touch; this might happen if a modal alert pops up during the interaction. the touch point has left the document window and moved into the browser's ui area, a plug-in, or other external content. the user has placed more touch points o...
Multi-touch interaction - Web APIs
of two, and so on. ev.preventdefault(); // cache the touch points for later processing of 2-touch pinch/zoom if (ev.targettouches.length == 2) { for (var i=0; i < ev.targettouches.length; i++) { tpcache.push(ev.targettouches[i]); } } if (logevents) log("touchstart", ev, true); update_background(ev); } touch move handler the touchmove handler calls preventdefault() for the same reason mentioned above, and invokes the pinch/zoom handler. function move_handler(ev) { // note: if the user makes more than one "simultaneous" touches, most browsers // fire at least one touchmove event and some will fire several touchmoves. // consequently, an application might want to "ignore" some touchmoves. // // this function sets the target element's border to "dashed" to visually // indi...
ValidityState - Web APIs
the validitystate interface represents the validity states that an element can be in, with respect to constraint validation. together, they help explain why an element's value fails to validate, if it's not valid. properties for each of these boolean properties, a value of true indicates that the specified reason validation may have failed is true, with the exception of the valid property, which is true if the element's value obeys all constraints. badinput read only a boolean that is true if the user has provided input that the browser is unable to convert. customerror read only a boolean indicating whether the element's custom validity message has been set to a non-empty string by calling the element's setcustomvalidity() method. patternmismatch read only a boolean that is true i...
WakeLock.request() - Web APIs
Web › API › WakeLock › request
se: document is not allowed to use screen wake lock due to screen-wake-lock policy. document is not fully active. document is hidden. user agent could not acquire platform's wake lock. examples the following asynchronous function requests a wakelocksentinel object. the request() method is wrapped in a try...catch statement to account for if the browser refuses the request for any reason. const requestwakelock = async () => { try { const wakelock = await navigator.wakelock.request('screen'); } catch (err) { // the wake lock request fails - usually system related, such low as battery console.log(`${err.name}, ${err.message}`); } } requestwakelock(); specifications specification status comment screen wake lock apithe definition of '...
WakeLock - Web APIs
Web › API › WakeLock
lock is exposed through the global navigator.wakelock property. methods request requests a wakelocksentinel object, which returns a promise that resolves with a wakelocksentinel object. examples the following asynchronous function requests a wakelocksentinel object. the wakelock.request method is wrapped in a try...catch statement to account for if the browser refuses the request for any reason. const requestwakelock = async () => { try { const wakelock = await navigator.wakelock.request('screen'); } catch (err) { // the wake lock request fails - usually system related, such low as battery console.log(`${err.name}, ${err.message}`); } } requestwakelock(); specifications specification status comment screen wake lock apithe definition of '...
WebGLRenderingContext.isContextLost() - Web APIs
the webglrenderingcontext.iscontextlost() method returns a boolean indicating whether or not the webgl context has been lost and must be re-established before rendering can resume. syntax let islost = gl.iscontextlost(); return value a boolean which is true if the context is lost, or false if not. usage notes there are several reasons why a webgl context may be lost, making it necessary to re-establish the context before resuming rendering. 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. the user's computer has multiple graphics processors (such as a laptop with both mobile and desktop class gpus, the former ...
Basic scissoring - Web APIs
ified rectangular area to be updated. this is a good opportunity to talk about the difference between pixels and fragments. a pixel is a picture element (in practice, a point) on the screen, or a single element of the drawing buffer, that area in memory that holds your pixel data (such as rgba color components). a fragment refers to the pixel while it is being handled by the webgl pipeline. the reason for this distinction is that fragment color (and other fragment values, such as depth) may be manipulated and changed several times during graphics operations before finally being written to the screen. we have already seen how fragment color changes during graphics operations, by applying color masking. in other cases, the fragments may be discarded altogether (so the pixel value is not updated)...
WebRTC connectivity - Web APIs
process, we find that localdescription and remotedescription, the properties which return these two descriptions, aren't as simple as they look. because during renegotiation, an offer might be rejected because it proposes an incompatible format, it's necessary that each endpoint have the ability to propose a new format but not actually switch to it until it's accepted by the other peer. for that reason, webrtc uses pending and current descriptions. the current description (which is returned by the rtcpeerconnection.currentlocaldescription and rtcpeerconnection.currentremotedescription properties) represents the description currently in actual use by the connection. this is the most recent connection that both sides have fully agreed to use. the pending description (returned by rtcpeerconnecti...
Introduction to WebRTC protocols - Web APIs
it needs to bypass firewalls that would prevent opening connections, give you a unique address if like most situations your device doesn’t have a public ip address, and relay data through a server if your router doesn’t allow you to directly connect with peers. ...
Signaling and video calling - Web APIs
ibute, then calls the stream's gettracks() method to get an array of the stream's tracks. if the array's length is zero, meaning there are no tracks left in the stream, we end the call by calling closevideocall(). this cleanly restores our app to a state in which it's ready to start or receive another call. see ending the call to learn how closevideocall() works. ending the call there are many reasons why calls may end. a call might have completed, with one or both sides having hung up. perhaps a network failure has occurred, or one user might have quit their browser, or had a system crash. in any case, all good things must come to an end. hanging up when the user clicks the "hang up" button to end the call, the hangupcall() function is called: function hangupcall() { closevideocall(); ...
WebSocket.close() - Web APIs
Web › API › WebSocket › close
ebsocket connection or connection attempt, if any. if the connection is already closed, this method does nothing. syntax websocket.close(); parameters code optional a numeric value indicating the status code explaining why the connection is being closed. if this parameter is not specified, a default value of 1005 is assumed. see the list of status codes of closeevent for permitted values. reason optional a human-readable string explaining why the connection is closing. this string must be no longer than 123 bytes of utf-8 text (not characters). exceptions thrown invalid_access_err an invalid code was specified. syntax_err the reason string is too long or contains unpaired surrogates. note: in gecko, this method didn't support any parameters prior to gecko 8.0 (firefox 8.0 / t...
WebSocket - Web APIs
Web › API › WebSocket
an event listener to be called when a message is received from the server. websocket.onopen an event listener to be called when the connection is opened. websocket.protocol read only the sub-protocol selected by the server. websocket.readystate read only the current state of the connection. websocket.url read only the absolute url of the websocket. methods websocket.close([code[, reason]]) closes the connection. websocket.send(data) enqueues data to be transmitted. events listen to these events using addeventlistener() or by assigning an event listener to the oneventname property of this interface. close fired when a connection with a websocket is closed. also available via the onclose property error fired when a connection with a websocket has been closed because o...
Viewpoints and viewers: Simulating cameras in WebXR - Web APIs
facing direction vector, the vector needs to include the w component. the value of w is always 0 for vectors, so the aforementioned vector can also be represented using [3, 1, -2, 0] or: [31-20]\left [ \begin{matrix} 3 \\ 1 \\ -2 \\ 0 \end{matrix} \right ] webxr automatically normalizes vectors to have a length of 1 meter; however, you may find that it makes sense to do it yourself for various reasons, such as to improve performance of calculations by not having to repeatedly perform normalization. once you've determined the matrix representing the combination of movements you wish the camera to make, you need to reverse it, because you're not moving the camera. since you're actually moving everything except the camera, take the inverse of the transform matrix to get an inverse transform mat...
Geometry and reference spaces in WebXR - Web APIs
n degrees by π/180. the following code snippet shows two simple functions, degreestoradians() and radianstodegrees(), which convert back and forth between the two units for measuring angles. const radians_per_degree = math.pi / 180.0; let degreestoradians = (deg) => deg * radians_per_degree; let radianstodegrees = (rad) => rad / radians_per_degree; times and durations note that for security reasons, domhighrestimestamp usually introduces a small amount of imprecision to the clock in order to prevent it from being used in fingerprinting and timing-based attacks. all times and durations in webxr are measured using the domhighrestimestamp type, which is a double-precision floating-point value specifying the time in milliseconds relative to the starting time. since the value is a floating-poi...
Example and tutorial: Simple synth keyboard - Web APIs
essed() function is used as the event handler for these events. function notepressed(event) { if (event.buttons & 1) { let dataset = event.target.dataset; if (!dataset["pressed"]) { osclist[dataset["octave"][dataset["note"]]] = playtone(dataset["frequency"]); dataset["pressed"] = "yes"; } } } we start by checking whether the primary mouse button is pressed, for two reasons. first, we want to only allow the primary mouse button to trigger notes playing. second, and more importantly, we are using this to handle mouseover for cases where the user is dragging from note to note, and we only want to start playing the note if the mouse is pressed when it enters the element. if the mouse button is in fact down, we get the pressed key's dataset attribute; this makes it ea...
Background audio processing using AudioWorklet - Web APIs
shut down your processor node if it deems it appropriate to do so. if the api determines that your node is no longer needed, process() will not be called again. note: at this time, unfortunately, chrome does not implement this algorithm in a manner that matches the current standard. instead, it keeps the node alive if you return true and shuts it down if you return false. thus for compatibility reasons you must always return true from process(), at least on chrome. however, once this chrome issue is fixed, you will want to change this behavior if possible as it may have a slight negative impact on performance. creating an audio processor worklet node to create an audio node that pumps blocks of audio data through an audioworkletprocessor, you need to follow these simple steps: load and i...
Web Audio API - Web APIs
neration, processing, and analysis of audio data directly using javascript in a worklet thread rather than on the main thread. obsolete: script processor nodes before audio worklets were defined, the web audio api used the scriptprocessornode for javascript-based audio processing. because the code runs in the main thread, they have bad performance. the scriptprocessornode is kept for historic reasons but is marked as deprecated and will be removed in a future version of the specification. scriptprocessornode the scriptprocessornode interface allows the generation, processing, or analyzing of audio using javascript. it is an audionode audio-processing module that is linked to two buffers, one containing the current input, one containing the output. an event, implementing the audioproces...
Web Authentication API - Web APIs
ed 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. options publickeycredentialcreationoptions the options passed to credentialscontainer.create(). publickeycredentialrequestoptions the options passed to credentialscontainer.get(). examples for security reasons, web authentication calls (create() and get()) are cancelled if the browser window loses focus while the call is pending. // sample arguments for registration var createcredentialdefaultargs = { publickey: { // relying party (a.k.a. - service): rp: { name: "acme" }, // user: user: { id: new uint8array(16), name: "...
Using Web Workers - Web APIs
actually very hard to cause concurrency problems. there's no access to non-threadsafe components or the dom. and you have to pass specific data in and out of a thread through serialized objects. so you have to work really hard to cause problems in your code. content security policy workers are considered to have their own execution context, distinct from the document that created them. for this reason they are, in general, not governed by the content security policy of the document (or parent worker) that created them. so for example, suppose a document is served with the following header: content-security-policy: script-src 'self' among other things, this will prevent any scripts it includes from using eval(). however, if the script constructs a worker, code running in the worker's context ...
Window.alert() - Web APIs
Web › API › Window › alert
notes the alert dialog should be used for messages which do not require any response on the part of the user, other than the acknowledgement of the message. the following text is shared between this article, dom:window.prompt and dom:window.confirm dialog boxes are modal windows - they prevent the user from accessing the rest of the program's interface until the dialog box is closed. for this reason, you should not overuse any function that creates a dialog box (or modal window). specification specification status comment html living standardthe definition of 'alert()' in that specification. living standard ...
Window.close() - Web APIs
Web › API › Window › close
indow() { openedwindow = window.open('moreinfo.htm'); } function closeopenedwindow() { openedwindow.close(); } closing the current window in the past, when you called the window object's close() method directly, rather than calling close() on a window instance, the browser closed the frontmost window, whether your script created that window or not. this is no longer the case; for security reasons, scripts are no longer allowed to close windows they didn't open. (firefox 46.0.1: scripts can not close windows, they had not opened) function closecurrentwindow() { window.close(); } specification specification status comment html living standardthe definition of 'window.close()' in that specification. living standard html5the definition of 'window...
Window.confirm() - Web APIs
Web › API › Window › confirm
is always false. example if (window.confirm("do you really want to leave?")) { window.open("exit.html", "thanks for visiting!"); } produces: notes the following text is shared between this article, dom:window.prompt and dom:window.alert dialog boxes are modal windows — they prevent the user from accessing the rest of the program's interface until the dialog box is closed. for this reason, you should not overuse any function that creates a dialog box (or modal window). regardless, there are good reasons to avoid using dialog boxes for confirmation. specification specification status comment html living standardthe definition of 'confirm()' in that specification. living standard ...
Window.history - Web APIs
Web › API › Window › history
state() and replacestate() methods that you should be aware of before using them. example history.back(); // equivalent to clicking back button history.go(-1); // equivalent to history.back(); notes for top-level pages you can see the list of pages in the session history, accessible via the history object, in the browser's dropdowns next to the back and forward buttons. for security reasons the history object doesn't allow the non-privileged code to access the urls of other pages in the session history, but it does allow it to navigate the session history. there is no way to clear the session history or to disable the back/forward navigation from unprivileged code. the closest available solution is the location.replace() method, which replaces the current item of the session histo...
Privileged features - Web APIs
he new window is said to be modal. the user cannot return to the main window until the modal window is closed. a typical modal window is created by the alert() function. the exact behavior of modal windows depends on the platform and on the mozilla release version. note: as of gecko 1.9, the internet explorer equivalent to this feature is the window.showmodaldialog() method. for compatibility reasons, it's now supported in firefox. note also that starting in gecko 2.0, you can use window.showmodaldialog() without universalbrowserwrite privileges. titlebar by default, all new secondary windows have a titlebar. if set to no or 0, this feature removes the titlebar from the new secondary window. mozilla and firefox users can force new windows to always render the titlebar by setting dom.
Window.pkcs11 - Web APIs
Web › API › Window › pkcs11
d be removed at any time. try to avoid using it. summary returns the pkcs11 object, which is used to install drivers and other software associated with the pkcs11 protocol. if pkcs11 isn't supported, this property returns null. note: this property has been returned null since gecko 1.9.0.14 (firefox 3.0.14) and removed in gecko 29.0 (firefox 29 / thunderbird 29 / seamonkey 2.26)) for security reasons. for more information on installing pkcs11 modules, see installing pkcs11 modules. see bug 326628 for details on why the property was removed. syntax objref = window.pkcs11 example window.pkcs11.addmodule(smod, secpath, 0, 0); notes see nsidompkcs11 for more information about how to manipulate pkcs11 objects. specification not part of specification. ...
Window.prompt() - Web APIs
Web › API › Window › prompt
tes a prompt dialog contains a single-line textbox, a cancel button, and an ok button, and returns the (possibly empty) text the user entered into that textbox. the following text is shared between this article, dom:window.confirm and dom:window.alert dialog boxes are modal windows; they prevent the user from accessing the rest of the program's interface until the dialog box is closed. for this reason, you should not overuse any function that creates a dialog box (or modal window). please note that result is a string. that means you should sometimes cast the value given by the user. for example, if their answer should be a number, you should cast the value to number. const anumber = number(window.prompt("type a number", "")); specification specification status comment ...
Window: rejectionhandled event - Web APIs
cy, in tandem with the unhandledrejection event, which is sent when a promise is rejected but there is no hander for the rejection. bubbles no cancelable no interface promiserejectionevent event handler property onrejectionhandled example you can use the rejectionhandled event to log promises that get rejected to the console, along with the reasons why they were rejected: window.addeventlistener("rejectionhandled", event => { console.log("promise rejected; reason: " + event.reason); }, false); specifications specification status comment html living standardthe definition of 'rejectionhandled' in that specification. living standard initial definition. ...
Window.resizeBy() - Web APIs
Web › API › Window › resizeBy
lta) parameters xdelta is the number of pixels to grow the window horizontally. ydelta is the number of pixels to grow the window vertically. example // shrink the window window.resizeby(-200, -200); notes this method resizes the window relative to its current size. to resize the window in absolute terms, use window.resizeto(). creating and resizing an external window for security reasons, it's no longer possible in firefox for a website to change the default size of a window in a browser if the window wasn’t created by window.open(), or contains more than one tab. see the compatability table for details on the change. even if you create window by window.open() it is not resizable by default. to make the window resizable, you must open it with the "resizable" feature. // cr...
Window.window - Web APIs
Web › API › Window › window
ithout having to type window. prefix: settimeout("alert('hi!')", 50); // equivalent to using window.settimeout. alert(window === window.window); // displays "true" the point of having the window property refer to the object itself, was likely to make it easy to refer to the global object. otherwise, you'd have to do a manual var window = this; assignment at the top of your script. another reason, is that without this property you wouldn't be able to write, for example, "window.open('http://google.com/')". you'd have to use "open('http://google.com/')" instead. yet another reason to use this property, is for libraries which wish to offer oop-versions, and non-oop versions (especially javascript modules). for example, if we refer to "this.window.location.href", a javascript module could d...
Window - Web APIs
Web › API › Window
om reference. in a tabbed browser, each tab is represented by its own window object; the global window seen by javascript code running within a given tab always represents the tab in which the code is running. that said, even in a tabbed browser, some properties and methods still apply to the overall window that contains the tab, such as resizeto() and innerheight. generally, anything that can't reasonably pertain to a tab pertains to the window instead. <div id="interfacediagram" style="display: inline-block; position: relative; width: 100%; padding-bottom: 11.666666666666666%; vertical-align: middle; overflow: hidden;"><svg style="display: inline-block; position: absolute; top: 0; left: 0;" viewbox="-50 0 600 70" preserveaspectratio="xminymin meet"><a xlink:href="/docs/web/api/window" ta...
WindowEventHandlers.onrejectionhandled - Web APIs
the onrejectionhandled property of the windoweventhandlers mixin is the eventhandler for processing rejectionhandled events. these events are raised when promises are rejected. syntax window.addeventlistener("rejectionhandled", function(event) { ... }); window.onrejectionhandled = function(event) { ...}; example window.onrejectionhandled = function(e) { console.log(e.reason); } specifications specification status comment html living standardthe definition of 'onrejectionhandled' in that specification. living standard initial definition. ...
WindowEventHandlers.onunhandledrejection - Web APIs
for processing unhandledrejection events. these events are raised for unhandled promise rejections. syntax window.onunhandledrejection = function; value function is an eventhandler or function to call when unhandledrejection events are received by the window. the event handler receives as an input parameter as a promiserejectionevent. examples this example simply logs unhandled rejections' reason values to the console. window.onunhandledrejection = function(e) { console.log(e.reason); } specifications specification status comment html living standardthe definition of 'onunhandledrejection' in that specification. living standard initial definition. ...
WritableStream.abort() - Web APIs
the abort() method of the writablestream interface aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be immediately moved to an error state, with any queued writes discarded. syntax var promise = writablestream.abort(reason); parameters reason a domstring providing a human-readable reason for the abort. return value a promise, which fulfills with the value given in the reason parameter. exceptions typeerror the stream you are trying to abort is not a writablestream, or it is locked. examples const writablestream = new writablestream({ write(chunk) { ... }, close() { ... }, abort(err) { ... } }, queuingstrategy); ... // abort the stream later on, when required writablestream.abort(); specif...
Synchronous and asynchronous requests - Web APIs
synchronous requests block the execution of code which causes "freezing" on the screen and an unresponsive user experience. asynchronous request if you use an asynchronous xmlhttprequest, you receive a callback when the data has been received. this lets the browser continue to work as normal while your request is being handled. ...
XMLHttpRequest.setRequestHeader() - Web APIs
ethod is called several times with the same header, the values are merged into one single request header. each time you call setrequestheader() after the first time you call it, the specified text is appended to the end of the existing header's content. if no accept header has been set using this, an accept header with the type "*/*" is sent with the request when send() is called. for security reasons, some headers can only be controlled by the user agent. these headers include the forbidden header names and forbidden response header names. note: for your custom fields, you may encounter a "not allowed by access-control-allow-headers in preflight response" exception when you send requests across domains. in this situation, you need to set up the access-control-allow-headers in your respons...
XMLHttpRequest - Web APIs
f the response of the request. xmlhttprequest.statustext read only returns a domstring containing the response string returned by the http server. unlike xmlhttprequest.status, this includes the entire text of the response message ("200 ok", for example). note: according to the http/2 specification (8.1.2.4 response pseudo-header fields), http/2 does not define a way to carry the version or reason phrase that is included in an http/1.1 status line. xmlhttprequest.timeout is an unsigned long representing the number of milliseconds a request can take before automatically being terminated. xmlhttprequesteventtarget.ontimeout is an eventhandler that is called whenever the request times out. xmlhttprequest.upload read only is an xmlhttprequestupload, representing the upload process.
XRReferenceSpace: reset event - Web APIs
otes the reset event indicates that the coordinate system has been reset or reconfigured by changing the reference space's origin, moving and rotating it as indicated by the event's transform property. the event is sent before any animation frame callbacks are executed to render the pending frame, to ensure that those callbacks have the updated coordinate system available. there are a number of reasons why a reset might occur. most common among them are the following: the user has manually reset the coordinate system, such as by requesting that the headset recalibrate itself to ensure that the facing direction and hand controllers are synchronized with the user's actual position and facing. this is primarily an issue for local or local-floor reference spaces. for a bounded-floor reference ...
XRSession.updateRenderState() - Web APIs
erty must not be specified for immersive sessions, so the value is null by default for immersive sessions. the default value is otherwise π * 0.5 (half of the value of pi). return value none. exceptions this method may throw any of the following exceptions. these are true exceptions, since this method does not return a promise. invalidstateerror this may occur for one of the following reasons: the xrsession has already ended, so you cannot change its render state. the baselayer specified in newstate was created by an xrsession other than the one on which updaterenderstate() was called. the inlineverticalfieldofview property was set, but the session is immersive and therefore does not allow this property to be used. examples this example creates a webgl context that is...
XRSystem: isSessionSupported() - Web APIs
onsessionstarted(xrsession); }); } else { // button is a toggle button. xrsession.end(); } } specifications specification status comment webxr device apithe definition of 'issessionsupported()' in that specification. working draft initial definition. ...
XRSystem - Web APIs
Web › API › XRSystem
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. if it's found, we know webxr is present, so we proceed by establishing a handler for the button which the user ...
XRWebGLLayer() - Web APIs
which will be used as the renderer for the session. any options specified in layerinit are used to tailor the rendering system's configuration. exceptions invalidstateerror the new xrwebgllayer could not be created due to one of a number of possible state errors: the xrsession specified by session has already been stopped. the specified webgl context, context, has been lost for any reason, such as a gpu switch or reset. the specified session is immersive but the context is not webxr compatible. operationerror the resources (including memory buffers) needed for the layer to operate could not be allocated. specifications specification status comment webxr device apithe definition of 'xrwebgllayer()' in that specification. working draft initia...
XSL Transformations in Mozilla FAQ - Web APIs
espace is http://www.w3.org/1999/xsl/transform. use the <?xml-stylesheet ?> processing instruction instead of the non-standard xml:stylesheet. the most common cause is the mime type handling. to find out which mime type your server sends, look at page info, use extensions like livehttpheaders or a download manager like wget. mozilla won't load xslt stylesheets from a different domain for security reasons. note: starting in gecko 7.0, both text/xsl and application/xslt+xml are supported mime types for xslt media stylesheets. note that firefox will override your xslt stylesheet if your xml is detected as an rss or atom feed. a known workaround is to add a sufficiently long xml comment to the beginning of your xml file in order to "push" the <feed> or <rss> tag out of the first 512 bytes, which...
ARIA live regions - Accessibility
lemented in current ats, or which. needs research. normally, only aria-live="polite" is used. any region which receives updates that are important for the user to receive, but not so rapid as to be annoying, should receive this attribute. the screen reader will speak changes whenever the user is idle. for regions which are not important, or would be annoying because of rapid updates or other reasons, silence them with aria-live="off". dropdown box updates useful onscreen information a website specializing in providing information about planets provides a dropdown box. when a planet is selected from the dropdown, a region on the page is updated with information about the selected planet. html <fieldset> <legend>planet information</legend> <label for="planetsselect">planet:</label> ...
ARIA Test Cases - Accessibility
t lands on the tabs, screen reader announces the label and role of the focused tab item, and whether it is selected. as the user presses left and right arrows to change the tabs, the newly focused tab should be announced. when navigating over the currently selected tab, the fact that this is the tab currently being active should be indicated. note that for tabs with ajax content, for performance reasons it is optional that they only load the panel only once the user presses space on the new tab. however, if there is no perf issues they can show the new content simply when the tab gets focus. if a new tab is selected via space, the now selected state should be indicated. as the user tabs into the panel, its name, role, and if present, description should be read, followed by the newly focused i...
ARIA: application role - Accessibility
e, the web author is completely responsible for handling any and all keyboard input, focus management, and other interactions and cannot assume assistive technologies would do any processing on their end. if the web application encompassed by the application role contains parts that should be treated like normal web content, a role of document or article should be used. background for historic reasons, especially on windows, screen readers and some other assistive technologies (at) have traditionally grabbed the whole web content from the browser at once after it had finished loading. the ats build their own representation of it that makes the most sense for a blind user to consume the content. this is often referred to as virtual document, browse mode, or similar terms. the document is strea...
ARIA: form role - Accessibility
to identify a group of elements on a page that provide equivalent functionality to an html form. <div role="form" id="contact-info" aria-label="contact information"> <!-- form content --> </div> this is a form that collects and saves a user's contact information. important: use an html <form> element to contain your form controls, rather than the aria form role, unless you have a very good reason. the html <form> element is sufficient to tell assistive technologies that there is a form. description a form landmark identifies a region of content that contains a collection of items and objects that, as a whole, combine to create a form when no other named landmark is appropriate (e.g. main or search). using the <form> element will automatically communicate a section of content as ...
ARIA: listbox role - Accessibility
rs use different styling for the selection when the list is not focused, e.g. a non-active selection is often shown with a lighter background colour. if the listbox is not part of another widget, it should have the aria-labelledby property set. if one or more entries are not dom children of listbox, additional aria-* properties will need to be set (see aria best practices). if there is a valid reason to expand the listbox, the combobox role may be more appropriate. specifications specification status accessible rich internet applications (wai-aria) 1.1the definition of 'aria listbox role' in that specification. recommendation wai-aria authoring practicesthe definition of 'listbox role' in that specification. working draft screen reader support tb...
An overview of accessible web applications and widgets - Accessibility
tically describe these kinds of widgets, developers typically resort to using generic elements such as <div> and <span>. while this results in a widget that looks like its desktop counterpart, there usually isn't enough semantic information in the markup to be usable by an assistive technology. the problem dynamic content on a web page can be particularly problematic for users who, for whatever reason, are unable to view the screen. stock tickers, live twitter feed updates, progress indicators, and similar content modify the dom in ways that an assistive technology (at) may not be aware of. that's where aria comes in. example 1: markup for a tabs widget built without aria labeling. there's no information in the markup to describe the widget's form and function. <!-- this is a tabs widget. ho...
Architecture - Accessibility
ed objects. however in accessibility hierarchies such as atk and iaccessible2, text is not exposed in leaf nodes as it is in a w3c dom. the text is actually exposed via a special text interface in the parent of the text nodes. it is concatenated together with all its sibling text nodes, and embedded objects between the text nodes are exposed as the unicoded embedded object character '\xfffc'. one reason for this is that there are fewer nodes to pass across process, and that improves performance. node types text content (role_text) objects are implemented by nstextaccessible. their text is actually exposed in their parent nshypertextaccessible via nsiaccessibletext. when the hierarchy is finally exposed to atk they are stripped out. they are in the nsiaccessible hierarchy to make it easy for n...
Web Accessibility: Understanding Colors and Luminance - Accessibility
tive cones, the authors note that "by population, about 64% of the cones are red-sensitive, about 32% green sensitive, and about 2% are blue sensitive." surprisingly, although cones that are blue-sensitive typically make up the fewest number of cones, they are also the most "sensitive" to color. put another way, as humans, the color blue is perceived differently than other colors, for multiple reasons. first, because the blue cones are actually the most sensitive of the three, second, we have fewer blue cones than red or green, and third, it so happens that these "blue sensitive" cones tend to be located at the rims of our eyeballs, away from the center (fovea centralis) of the back of the eyeball, where the red and green cones tend to cluster. there is software that actually takes advantage...
Operable - Accessibility
er key shortcuts note: also see the wcag description for guideline 2.1 keyboard accessible: make all functionality available from a keyboard. guideline 2.2 — enough time: provide users enough time to read and use content this guideline covers situations in which functionality may have a time limit. for example, purchases sometimes need to be completed within a time limit for security reasons. success criteria how to conform to the criteria practical resource 2.2.1 timing is adjustable (a) for functionality with time limits (e.g. completing a hotel or flight booking often has a time limit), the user should be given controls to allow them to adjust, extend or turn off the time limit. exceptions to this are activities with time limits longer th...
Understandable - Accessibility
to help people who can't read it, or provide an alternative version that is written at lower secondary level. this doesn't mean that all subject matter should be understood by everyone, but that the style of writing should be accessible by everyone. it is better to just write all content at lower secondary level, even technical documentation like programming tutorials, unless there is a good reason not to (e.g. an alternative style for poetic effect), or they have to be written in a strict style (e.g. w3c specs). 3.1.6 pronunciation (aaa) a mechanism should be provided to give users access to pronounciation of words where they are is needed to understand the content fully. the html5 <audio> element can be used to create a control that allows the reader to play ...
Understanding the Web Content Accessibility Guidelines - Accessibility
nform to the recommendations outlined in the w3c web content accessibility guidelines 2.0 or 2.1 (or just wcag, for the purposes of this writing). the wcag 2.0 and 2.1 provide a detailed set of guidelines for making web content more accessible to people with a wide variety of disabilities. it is comprehensive but incredibly detailed, and quite difficult to gain a rapid understanding of. for this reason, we have summarised the practical steps you need to take to satisfy the different recommendations, with further links to more details where required. the four principles wcag is broadly broken down into four principles — major things that web content must be to be considered accessible (see understanding the four principles of accessibility for the wcag definitions). each of the links below ...
::selection - CSS: Cascading Style Sheets
for people experiencing cognitive concerns or who are less technologically literate, unexpected changes to selection styles may hurt their understanding of the functionality. if overridden, it is important to ensure that the contrast ratio between the text and background colors of the selection is high enough that people experiencing low vision ...
Resizing background images with background-size - CSS: Cascading Style Sheets
the background-size css property lets you resize the background image of an element, overriding the default behavior of tiling the image at its full size by specifying the width and/or height of the image. by doing so, you can scale the image upward or downward as desired. tiling a large image let's consider a large image, a 2982x2808 firefox logo image. we want (for some reason likely involving horrifyingly bad site design) to tile four copies of this image into a 300x300-pixel element. to do this, we can use a fixed background-size value of 150 pixels. html <div class="tiledbackground"> </div> css .tiledbackground { background-image: url(https://www.mozilla.org/media/img/logos/firefox/logo-quantum.9c5e96634f92.png); background-size: 150px; width: 300px; height: 300px; border: ...
Using URL values for the cursor property - CSS: Cascading Style Sheets
keyword> this means that zero or more urls may be specified (comma-separated), which must be followed by one of the keywords defined in the css specification, such as auto or pointer. for example, the following value would be allowed: cursor: url(foo.cur), url(http://www.example.com/bar.gif), auto; this will first try loading foo.cur. if that file does not exist or is not valid for some other reason, bar.gif is tried, and if that can't be used either, auto will be used. support for the css 3 syntax for cursor values got added in gecko 1.8 (firefox 1.5): cursor: [ <uri> [ <x> <y> ]? , ]* <keyword> it allows specifying the coordinates of the cursor's hotspot, which will be clamped to the boundaries of the cursor image. if none are specified, the coordinates of the hotspot are read from the...
Spanning and Balancing Columns - CSS: Cascading Style Sheets
l means the item spans all of the columns. you cannot cause an item to span two out of three columns for example. things to watch out for if the spanning element is inside another element which has margins, padding and a border or a background color, it is possible to end up with the top of the box appearing above the spanner and the rest displaying below, as shown in the next example. for this reason, some care should be taken when deciding to make an element a spanner and ensure this scenario is accounted for. additionally, if a spanning element appears later in the content it can cause unexpected or unwanted behaviour when there is not enough content to create columns after the spanner. use spanning carefully and test at various breakpoints to make sure you get the intended effect. colu...
CSS Containment - CSS: Cascading Style Sheets
rs scoped to that subtree only. note: style containment is "at-risk" in the spec and may not be supported everywhere (it's not currently supported in firefox). special values there are two special values of contain: content strict we encountered the first in the example above. using contain: content turns on layout and paint containment. the specification describes this value as being "reasonably safe to apply widely". it does not apply size containment, so you would not be at risk of a box ending up zero-sized due to a reliance on the size of its children. to gain as much containment as possible use contain: strict, which behaves the same as contain: size layout paint, or perhaps the following to also add style containment in browsers that support it: contain: strict; contain: stri...
Typical use cases of Flexbox - CSS: Cascading Style Sheets
as you lay out your items you want to control the dimensions of the items in that one dimension, or control the spacing between items. these are the uses that flexbox was designed for. ...
Flow Layout and Writing Modes - CSS: Cascading Style Sheets
on includes logical versions of the properties that control margins, padding and borders as well as other mappings for things that we have typically used physical directions to specify. summary in most cases, flow layout works as you would expect it to when changing the writing mode of the document or parts of the document. this can be used to properly typeset vertical languages or for creative reasons. css is making this easier by way of introducing logical properties and values so that when working in a vertical writing mode sizing can be based on element's inline and block size. this will be useful when creating components which can work in different writing-modes. see also writing modes external resources css writing modes, jen simmons on 24 ways ...
In Flow and Out of Flow - CSS: Cascading Style Sheets
eserved however, as you can see in the example below. when you do anything to remove, or shift an item from where it would be placed in normal flow, you can expect to need to do some managing of the content and the content around it to prevent overlaps. whether that involves clearing floats, or ensuring that an element with position: absolute does not sit on top of some other content. for this reason methods which remove elements from being in-flow should be used with understanding of the effect that they have. summary in this guide we have covered the ways to take an element out of flow in order to achieve some very specific types of positioning. in the next guide we will look at a related issue, that of creating a block formatting context, in formatting contexts explained. see also le...
OpenType font features guide - CSS: Cascading Style Sheets
to change one of the individual features, you have to redefine the entire string (similar to manipulating variable fonts with font-variation-settings). discovering availability of features in fonts this is sometimes the trickiest thing to work out if you don't have any documentation that came with the fonts (many type designers and foundries will provide sample pages and css just for this very reason). but there are some sites that make it easier to figure out. you can visit wakamaifondue.com, drop your font file on the circle where instructed and in a few moments you'll have a full report on all the capabilities and features of your font. axis-praxis.org also offers a similar capability, with the ability to click on the features to turn them on or off in a given text block. why you would us...
Auto-placement in CSS Grid Layout - CSS: Cascading Style Sheets
the other two are grid items enclosed in a div, they might be auto-placed or you could place these with a positioning method onto your grid. <div class="grid"> i am a string and will become an anonymous item <div>a grid item</div> <div>a grid item</div> </div> anonymous items are always auto-placed because there is no way to target them. therefore if you have some unwrapped text for some reason in your grid, be aware that it might show up somewhere unexpected as it will be auto-placed according to the auto-placement rules. use cases for auto-placement auto-placement is useful whenever you have a collection of items. that could be items that do not have a logical order such as a gallery of photos, or product listing. in that case you might choose to use the dense packing mode to fill i...
Box alignment in CSS Grid Layout - CSS: Cascading Style Sheets
elf: center; } <div class="wrapper"> <div class="item1">item 1</div> <div class="item2">item 2</div> <div class="item3">item 3</div> <div class="item4">item 4</div> </div> items with an intrinsic aspect ratio the specification details that the default behavior in align-self is to stretch, except for items which have an intrinsic aspect ratio, in this case they behave as start. the reason for this, is that if items with an aspect ratio are set to stretch, this default would distort them. this behavior has now been clarified in the specification, with browsers yet to implement the correct behavior. until that happens, you can ensure that items do not stretch, such as images, which are direct children of the grid, by setting align-self and justify-self to start. this will mimic the...
Realizing common layouts using CSS Grid Layout - CSS: Cascading Style Sheets
direction to column. i can then use an auto margin on the .cta to push this bar down to the bottom of the box. .listing li { border: 1px solid #ffe066; border-radius: 5px; display: flex; flex-direction: column; } .listing .cta { margin-top: auto; border-top: 1px solid #ffe066; padding: 10px; text-align: center; } .listing .body { padding: 10px; } this is really one of the key reasons i would use flexbox rather than grid, if i am just aligning or distributing something in a single dimension, that’s a flexbox use case. this is all looking fairly complete now, however we sometimes have these cards which contain far more content than the others. it might be nice to cause those to span two tracks, and then they won’t be so tall. i have a class of wide on my larger item, ...
Consistent list indentation - CSS: Cascading Style Sheets
> element. we can ignore <li> altogether for these purposes. 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. set both to 1.25em, if you like -- there's no reason why you have to stick with pixel-based indentation. 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. if the parent is the body, there's a strong chance your bullets will be completely outside...
Basic concepts of Logical Properties and Values - CSS: Cascading Style Sheets
line-size, the component now works the same way no matter which writing mode it is displayed using. you can try this out in the live example below. change writing-mode from vertical-rl to horizontal-tb on .grid to see how the different properties change the layout. when working with a site in a writing mode other than a horizontal, top to bottom one, or when using writing modes for creative reasons, being able to relate to the flow of the content makes a lot of sense. block and inline dimensions a key concept of working with flow relative properties and values is the two dimensions of block and inline. as we saw above, newer css layout methods such as flexbox and grid layout use the concepts of block and inline rather than right and left/top and bottom when aligning items. the inline di...
Logical properties for margins, borders and padding - CSS: Cascading Style Sheets
block dimensions, respectively. in a horizontal writing-mode this css would apply 5px of padding to the top of the box and 10px of padding to the bottom: .box { padding-block: 5px 10px; } note: the shorthand properties padding-inline and padding-block shipped in firefox 66. as these are new properties check browser support before using. border examples the border properties are the main reason that logical properties and values seems to have so many properties, as we have the longhands for the color, width, and style of the border on each side of a box, along with the shorthand to set all three at once for each side. as with margin and padding we have a mapped version of each physical property. the demo below uses some longhands and three shorthand values. as with the other demos try ...
Stacking context example 2 - CSS: Cascading Style Sheets
ous example, but now z-index properties are assigned on both levels of the hierarchy. you can see that div #2 (z-index: 2) is above div #3 (z-index: 1), because they both belong to the same stacking context (the root one), so z-index values rule how elements are stacked. what can be considered strange is that div #2 (z-index: 2) is above div #4 (z-index: 10), despite their z-index values. the reason is that they do not belong to the same stacking context. div #4 belongs to the stacking context created by div #3, and as explained previously div #3 (and all its content) is under div #2. to better understand the situation, this is the stacking context hierarchy: root stacking context div #2 (z-index 2) div #3 (z-index 1) div #4 (z-index 10) note: it is wor...
The stacking context - CSS: Cascading Style Sheets
lement is passed for stacking in the root element with respect to its sibling's div. notes: div #4 is rendered under div #1 because div #1's z-index (5) is valid within the stacking context of the root element, while div #4's z-index (6) is valid within the stacking context of div #3. so, div #4 is under div #1, because div #4 belongs to div #3, which has a lower z-index value. for the same reason div #2 (z-index 2) is rendered under div#5 (z-index 1) because div #5 belongs to div #3, which has an higher z-index value. div #3's z-index is 4, but this value is independent from z-index of div #4, div #5 and div #6, because it belongs to a different stacking context. an easy way to figure out the rendering order of stacked elements along the z axis is to think of it as a "version number" of...
Card - CSS: Cascading Style Sheets
e content added to it. note: the various elements in separate cards do not align with each other, as each card is an independent grid. the proposed subgrid feature of grid level 2 would give a solution to this issue. useful fallbacks or alternative methods flexbox could be used to lay out the card, in which case you should make the content area grow, and other items not grow. this would be a reasonable way to lay out the card, although i have a slight preference for being able to control the tracks from the container rather than needing to add rules to the items. for the overall layout you could use flexbox, however this will result in cards stretching over the final flex row where there are fewer than can fit in the rows above. alternatively you could use css multi-col — this would caus...
Grid wrapper - CSS: Cascading Style Sheets
...
Recipe: Media objects - CSS: Cascading Style Sheets
d. the media object should clear the contents no matter which side is tallest. the recipe download this example choices made i have chosen to use grid layout for the media object as it allows me to control the layout in two dimensions when i need to. this means that when we have a footer, with short content above, the footer can be pushed down to the bottom of the media object. another reason to use grid layout is in order that i can use fit-content() for the track sizing of the image. by using fit-content with a maximum size of 200 pixels, when we have a small image such as the icon, the track only gets as large as the size of that image — the max-content size. if the image is larger, the track stops growing at 200 pixels and as the image has a max-width of 100% applied, it scales...
Using media queries - CSS: Cascading Style Sheets
yntax improvements in level 4 the media queries level 4 specification includes some syntax improvements to make media queries using features that have a "range" type, for example width or height, less verbose. level 4 adds a range context for writing such queries. for example, using the max- functionality for width we might write the following: note: the media queries level 4 specification has reasonable support in modern browsers, but some media features are not well supported. see the @media browser compatibility table for more details. @media (max-width: 30em) { ... } in media queries level 4 this can be written as: @media (width <= 30em) { ... } using min- and max- we might test for a width between two values like so: @media (min-width: 30em) and (max-width: 50em) { ... } this woul...
Using CSS custom properties (variables) - CSS: Cascading Style Sheets
o: element { --main-bg-color: brown; } note that the selector given to the ruleset defines the scope that the custom property can be used in. a common best practice is to define custom properties on the :root pseudo-class, so that it can be applied globally across your html document: :root { --main-bg-color: brown; } however, this doesn't always have to be the case: you maybe have a good reason for limiting the scope of your custom properties. note: custom property names are case sensitive — --my-color will be treated as a separate custom property to --my-color. as mentioned earlier, you use the custom property value by specifying your custom property name inside the var() function, in place of a regular property value: element { background-color: var(--main-bg-color); } firs...
Visual formatting model - CSS: Cascading Style Sheets
ck-level boxes, and block containers are all referred to as block boxes in certain places. these things are somewhat different and the term block box should only be used if there is no ambiguity. block containers a block container either contains only inline-level boxes participating in an inline formatting context, or only block-level boxes participating in a block formatting context. for this reason, we see the behavior explained above, where anonymous boxes are introduced to ensure all of the items can participate in a block or inline formatting context. an element is a block container only if it contains block-level or inline-level boxes. inline-level and block-level boxes these are the boxes contained inside the block container that are participating in inline or block layout, respectiv...
appearance (-moz-appearance, -webkit-appearance) - CSS: Cascading Style Sheets
lement using platform-native styling, based on the operating system's theme. the -moz-appearance and -webkit-appearance properties are non-standard versions of this propery, used (respectively) by gecko (firefox) and by webkit-based (e.g., safari) and blink-based (e.g., chrome, opera) browsers to achieve the same thing. note that firefox and edge also support -webkit-appearance, for compatibility reasons. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. the -moz-appearance property was used in xul stylesheets to design custom widgets with platform-appropriate styling. it was also used in the xbl implementations of the w...
break-after - CSS: Cascading Style Sheets
or a left right in a right-to-left spread.) column break values avoid-column avoids any column break right after the principal box. column forces a column break right after the principal box. region break values avoid-region avoids any region break right after the principal box. region forces a region break right after the principal box. page break aliases for compatibility reasons, the legacy page-break-after property should be treated by browsers as an alias of break-after. this ensures that sites using page-break-after continue to work as designed. a subset of values should be aliased as follows: page-break-after break-after auto auto left left right right avoid avoid always page the al...
break-before - CSS: Cascading Style Sheets
left right in a right-to-left spread.) column break values avoid-column avoids any column break right before the principal box. column forces a column break right before the principal box. region break values avoid-region avoids any region break right before the principal box. region forces a region break right before the principal box. page break aliases for compatibility reasons, the legacy page-break-before property should be treated by browsers as an alias of break-before. this ensures that sites using page-break-before continue to work as designed. a subset of values should be aliased as follows: page-break-before break-before auto auto left left right right avoid avoid always page t...
break-inside - CSS: Cascading Style Sheets
(page, column, or region) to be be inserted within the principal box. avoid avoids any break (page, column, or region) from being inserted within the principal box. avoid-page avoids any page break within the principal box. avoid-column avoids any column break within the principal box. avoid-region avoids any region break within the principal box. page break aliases for compatibility reasons, the legacy page-break-inside property should be treated by browsers as an alias of break-inside. this ensures that sites using page-break-inside continue to work as designed. a subset of values should be aliased as follows: page-break-inside break-inside auto auto avoid avoid formal definition initial valueautoapplies toblock-level elementsinheri...
conic-gradient() - CSS: Cascading Style Sheets
referred ratio. its concrete size will match the size of the element it applies to, or size of the <image> is set to something other than the element size. to create a conic gradient that repeats so as to fill a 360 degree rotation, use the repeating-conic-gradient() function instead. because <gradient>s belong to the <image> data type, they can only be used where <image>s can be used. for this reason, conic-gradient() won't work on background-color and other properties that use the <color> data type. why is it called a "conic" gradient? if the color stops are much lighter on one side than the other, it can look like a cone from above. composition of a conic gradient the conic-gradient syntax is similar to the radial-gradient syntax, but the color-stops are placed around a gradient arc, t...
font-size-adjust - CSS: Cascading Style Sheets
just, it is specified as a number that the font-size property is multiplied by. this means the value specified for the property should generally be the aspect ratio of the first choice font. for example, a style sheet that specifies: font-size: 14px; font-size-adjust: 0.5; ... is really specifying that the lowercase letters of the font should be 7px high (0.5 × 14px). this will still produce reasonable results in browsers that do not support font-size-adjust, where a 14px font will be used. syntax values none choose the size of the font based only on the font-size property. <number> choose the size of the font so that its lowercase letters (as determined by the x-height of the font) are the specified number times the font-size. the number specified should generally be the aspec...
<length> - CSS: Cascading Style Sheets
Web › CSS › length
gh-dpi devices, inches (in), centimeters (cm), and millimeters (mm) are the same as their physical counterparts. therefore, the px unit is defined relative to them (1/96 of 1 inch). note: many users increase their user agent's default font size to make text more legible. absolute lengths can cause accessibility problems, since they are fixed and do not scale according to user settings. for this reason, prefer relative lengths (such as em or rem) when setting font-size. px one pixel. for screen displays, it traditionally represents one device pixel (dot). however, for printers and high-resolution screens, one css pixel implies multiple device pixels. 1px = 1/96th of 1in. cm one centimeter. 1cm = 96px/2.54. mm one millimeter. 1mm = 1/10th of 1cm. q one quarter of a millimeter. 1q = ...
linear-gradient() - CSS: Cascading Style Sheets
as no intrinsic dimensions; i.e., it has no natural or preferred size, nor a preferred ratio. its concrete size will match the size of the element it applies to. to create a linear gradient that repeats so as to fill its container, use the repeating-linear-gradient() function instead. because <gradient>s belong to the <image> data type, they can only be used where <image>s can be used. for this reason, linear-gradient() won't work on background-color and other properties that use the <color> data type. composition of a linear gradient a linear gradient is defined by an axis—the gradient line—and two or more color-stop points. each point on the axis is a distinct color; to create a smooth gradient, the linear-gradient() function draws a series of colored lines perpendicular to the gradien...
list-style-type - CSS: Cascading Style Sheets
obal values */ list-style-type: inherit; list-style-type: initial; list-style-type: unset; the list-style-type property may be defined as any one of: a <custom-ident> value a symbols() value a <string> value the keyword none. note that: some types require a suitable font installed to display as expected. the cjk-ideographic is identical to trad-chinese-informal; it exists for legacy reasons. values <custom-ident> a identifier matching the value of a @counter-style or one of the predefined styles: symbols() defines an anonymous style of the list. <string> the specified string will be used as the item's marker. none no item marker is shown. disc a filled circle (default value) circle a hollow circle square a filled square decimal ...
overflow - CSS: Cascading Style Sheets
Web › CSS › overflow
his feature is behind a feature preference setting. in about:config, set layout.css.overflow.moz-scrollbars.enabled to true description overflow options include clipping, showing scrollbars, or displaying the content flowing out of its container into the surrounding area. specifying a value other than visible (the default) creates a new block formatting context. this is necessary for technical reasons — if a float intersected with the scrolling element it would forcibly rewrap the content after each scroll step, leading to a slow scrolling experience. in order for overflow to have an effect, the block-level container must have either a set height (height or max-height) or white-space set to nowrap. setting one axis to visible (the default) while setting the other to a different value resu...
page-break-after - CSS: Cascading Style Sheets
d as a right page. 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 aliases the page-break-after property is now a legacy property, replaced by break-after. for compatibility reasons, page-break-after should be treated by browsers as an alias of break-after. this ensures that sites using page-break-after continue to work as designed. a subset of values should be aliased as follows: page-break-after break-after auto auto left left right right avoid avoid always page formal definition initial ...
page-break-before - CSS: Cascading Style Sheets
as a right page. 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 aliases the page-break-before property is now a legacy property, replaced by break-before. for compatibility reasons, page-break-before should be treated by browsers as an alias of break-before. this ensures that sites using page-break-before continue to work as designed. a subset of values should be aliased as follows: page-break-before break-before auto auto left left right right avoid avoid always page formal definition ini...
page-break-inside - CSS: Cascading Style Sheets
auto; page-break-inside: avoid; /* global values */ page-break-inside: inherit; page-break-inside: initial; page-break-inside: unset; syntax values auto initial value. automatic page breaks (neither forced nor forbidden). avoid avoid page breaks inside the element. page break aliases the page-break-inside property is now a legacy property, replaced by break-inside. for compatibility reasons, page-break-inside should be treated by browsers as an alias of break-inside. this ensures that sites using page-break-inside continue to work as designed. a subset of values should be aliased as follows: page-break-inside break-inside auto auto avoid avoid formal definition initial valueautoapplies toblock-level elements in the normal flow of the...
radial-gradient() - CSS: Cascading Style Sheets
as no intrinsic dimensions; i.e., it has no natural or preferred size, nor a preferred ratio. its concrete size will match the size of the element it applies to. to create a radial gradient that repeats so as to fill its container, use the repeating-radial-gradient() function instead. because <gradient>s belong to the <image> data type, they can only be used where <image>s can be used. for this reason, radial-gradient() won't work on background-color and other properties that use the <color> data type. composition of a radial gradient a radial gradient is defined by a center point, an ending shape, and two or more color-stop points. to create a smooth gradient, the radial-gradient() function draws a series of concentric shapes radiating out from the center to the ending shape (and potential...
repeating-conic-gradient() - CSS: Cascading Style Sheets
dient, a repeating-conic gradient has no intrinsic dimensions; i.e., it has no natural or preferred size, nor a preferred ratio. its concrete size will match the size of the element it applies to, or the size the <image> is set to if it's set to something other than the element's size. because <gradient>s belong to the <image> data type, they can only be used where <image>s can be used. for this reason, repeating-conic-gradient() won't work on background-color and other properties that use the <color> data type. to create a conic gradient that doe not repeat, make the gradient a full 360 degree rotation, or use the conic-gradient() function instead. understanding repeating conic gradients the repeating-conic-gradient syntax is similar to the conic-gradient() and repeating-radial-gradient(...
repeating-linear-gradient() - CSS: Cascading Style Sheets
s can be altered with repeating the first color again as the last color. as with any gradient, a repeating linear gradient has no intrinsic dimensions; i.e., it has no natural or preferred size, nor a preferred ratio. its concrete size will match the size of the element it applies to. because <gradient>s belong to the <image> data type, they can only be used where <image>s can be used. for this reason, repeating-linear-gradient() won't work on background-color and other properties that use the <color> data type. syntax /* a repeating gradient tilted 45 degrees, starting blue and finishing red, repeating 3 times */ repeating-linear-gradient(45deg, blue, red 33.3%); /* a repeating gradient going from the bottom right to the top left, starting blue and finishing red, repeating every 20px...
repeating-radial-gradient() - CSS: Cascading Style Sheets
, which can be mitigated by repeating the first color as the last color. as with any gradient, a repeating radial gradient has no intrinsic dimensions; i.e., it has no natural or preferred size, nor a preferred ratio. its concrete size will match the size of the element it applies to. because <gradient>s belong to the <image> data type, they can only be used where <image>s can be used. for this reason, repeating-radial-gradient() won't work on background-color and other properties that use the <color> data type. syntax /* a gradient at the center of its container, starting red, changing to blue, and finishing green, with the colors repeating every 30px */ repeating-radial-gradient(circle at center, red 0, blue, green 30px); /* an elliptical gradient near the top left of its container,...
text-justify - CSS: Cascading Style Sheets
t-justify: inter-word; text-justify: inter-character; text-justify: distribute; /* deprecated value */ syntax the text-justify property is specified as a single keyword chosen from the list of values below. values none the text justification is turned off. this has the same effect as not setting text-align at all, although it is useful if you need to turn justification on and off for some reason. auto the browser chooses the best type of justification for the current situation based on a balance between performance and quality, but also on what is most appropriate for the language of the text (e.g., english, cjk languages, etc.). this is the default justification used if text-justify is not set at all. inter-word the text is justified by adding space between words (effectively varyin...
WAI ARIA Live Regions/API Support - Developer guides
ge occured, etc. this is a potential area for innovation in screen readers. most recent occurance user input? key presses yes mouse clicks yes mouse hovers no page load events no everything else, including focus changes, timer callbacks, xmlhttprequest callbacks, etc. are neutral. they are only counted as user input if the original reason they happened was because of user input. what should screen readers present? please read the live region section of the wai-aria screen reader implementor's guide. ...
Cross-browser audio basics - Developer guides
ill <a href="audiofile.mp3">download the music</a>.</p> </audio> note: you can also use an mp4 file instead of mp3. mp4 files typically contain aac encoded audio. you can use type="audio/mp4". (currently, browsers that support mp3 also support mp4 audio). here we define an <audio> element with multiple sources — we do this as not all browsers support the same audio formats. to ensure reasonable coverage, we should specify at least two different formats. the two formats that will give maximum coverage are mp3 and ogg vorbis. we do this using the <source> element, which takes the attributes src and type. src contains the path to the audio file to be loaded (relative or absolute). type is used to inform the browser of the file type. if omitted, most browsers will attempt to g...
Setting up adaptive streaming media sources - Developer guides
here are other details such as byte-ranges in there too - it is an xml document and in many cases will be generated for you. there are a few profiles we can use. we're going to take a look at ondemand profile for video on demand (vod) and the live profile. for live services streaming, the live profile is a requirement. the stream switching capabilities are identical between the profiles. ...
Creating a cross-browser video player - Developer guides
on>&copy; blender foundation | <a href="http://mango.blender.org">mango.blender.org</a></figcaption> </figure> even though this player will define its own custom control set, the controls attribute is still added to the <video> element, and the player's default control set is switched off later with javascript. doing things this way still allows users who have javascript turned off (for whatever reason) to still have access to the browser's native controls. a poster image is defined for the video, and the preload attribute is set to metadata, which informs the browser that it should initially only attempt to load the metadata from the video file rather than the entire video file. this provides the player with data such as video duration and format. note: ie9 behaves differently than most oth...
Challenge solutions - Developer guides
tion 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. color three-digit color codes challenge in your css file, change all the color names to 3-digit color codes without affecting the result. solution the following values are reasonable approximations of the named colors: strong { color: #f00; /* red */ background-color: #ddf; /* pale blue */ font: 200% serif; } .carrot { color: #fa0; /* orange */ } .spinach { color: #080; /* dark green */ } p { color: #00f; /* blue */ } content add an image challenge add a one rule to your stylesheet so that it displays the image at the start of each line. solutio...
DOM onevent handlers - Developer guides
(the html specification names these: onblur, onerror, onfocus, onload, and onscroll.) event handler's parameters, this binding, and the return value when the event handler is specified as an html attribute, the specified code is wrapped into a function with the following ...
Media events - Developer guides
s. seeked sent when a seek operation completes. seeking sent when a seek operation begins. stalled sent when the user agent is trying to fetch media data, but data is unexpectedly not forthcoming. suspend sent when loading of the media is suspended; this may happen either because the download has completed or because it has been paused for any other reason. timeupdate the time indicated by the element's currenttime attribute has changed. volumechange sent when the audio volume changes (both when the volume is set and when the muted attribute is changed). waiting sent when the requested operation (such as playback) is delayed pending the completion of another operation (such as a seek). you can easily watch...
Mutation events - Developer guides
e the mutation events have been marked as deprecated in the dom events specification, as the api's design is flawed (see details in the "dom mutation events replacement: the story so far / existing points of consensus" post to public-webapps). mutation observers are the proposed replacement for mutation events in dom4. they are expected to be included in firefox 14 and chrome 18. the practical reasons to avoid the mutation events are performance issues and cross-browser support. performance adding dom mutation listeners to a document profoundly degrades the performance of further dom modifications to that document (making them 1.5 - 7 times slower!). moreover, removing the listeners does not reverse the damage. the performance effect is limited to the documents that have the mutation event...
Making content editable - Developer guides
, firefox supports the non-standard argument, br, for defaultparagraphseparator since firefox 55. this is useful if your web application expects the older firefox behavior, and you don't want to or don't have the time to update it to use the new behavior. you can use the older firefox behavior with this line: document.execcommand("defaultparagraphseparator", false, "br"); security for security reasons, firefox doesn't let javascript code use clipboard related features (copy, paste, etc.) by default. you can enable them by setting the preferences shown below using about:config: user_pref("capability.policy.policynames", "allowclipboard"); user_pref("capability.policy.allowclipboard.sites", "https://www.mozilla.org"); user_pref("capability.policy.allowclipboard.clipboard.cutcopy", "allaccess")...
HTML5 Parser - Developer guides
Web › Guide › HTML › HTML5 › HTML5 Parser
elopers: if you omit the closing tag for <title>, <style>, <textarea>, or <xmp>, the page will fail to be parsed. ie already fails to parse documents with a missing </title> tag, so if you test with ie, you probably don't have that problem. if you forget to close a comment, the page will most likely fail to be parsed. however, unclosed comments often already break in existing browsers for one reason or another, so it's unlikely that you have this issue in sites that are tested in multiple browsers. in an inline script, in order to use the literal strings <script, </script>, and <!--, you should prevent them from being parsed literally by expressing them as \u003cscript,\u003c/script>, and \u003c!--. the older practice of escaping the string </script> by surrounding it with comment markers,...
Separate sites for mobile and desktop - Developer guides
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. this is because you have the option of sending completely separate html, javascript, and css to phones and pcs. another case where you may be forced to use this approach is if you cannot, for whatever reason, modify your existing desktop site, and need to have a 100% separate mobile site. though it’s not ideal, at least you have this option. examples most of the major web applications you see in the wild have chosen this path, including facebook, youtube, digg, and flickr. in fact, mozilla picked this strategy for the mobile versions of addons.mozilla.org (amo) and support.mozilla.org (sumo). if yo...
Applying color to HTML elements using CSS - HTML: Hypertext Markup Language
lected our base color, we need to build out our palette. we decide to use paletton to come up with the other colors we need. upon opening paletton, we see: next, we enter our color's hex code (d79c7a) into the "base rgb" box at the bottom-left corner of the tool: we now see a monochromatic palette based on the color we picked from the mars photo. if you need a lot of related colors for some reason, those are likely to be good ones. but what we really want is an accent color. something that will pop along side the base color. to find that, we click the "add complementary" toggle underneath the menu that lets you select the palette type (currently "monochromatic"). paletton computes an appropriate accent color; clicking on the accent color down in the bottom-right corner tells us that this c...
HTML attribute: pattern - HTML: Hypertext Markup Language
a pattern attribute, the title attribute, if used, must describe the pattern. relying on the title attribute for the visual display of text content is generally discouraged as many user agents do not expose the attribute in an accessible manner. some browsers show a tooltip when an element with a title is hovered, but that leaves out keyboard-only and touch-only users. this is one of the several reasons you must include information informing users how to fill out the the control to match the requirements. while titles are used by some browsers to populate error messaging, because browsers sometimes also show the title as text on hover, it therefore shows in non-error situations, so be careful not to word titles as if an error has occurred. specifications specification status c...
HTML attribute: required - HTML: Hypertext Markup Language
ired pseudo-class also applies to it. conversely, inputs that support the required attribute but don't have the attribute set match the :optional pseudo-class. in the case of a same named group of radio buttons, if a single radio button in the group has the required attribute, a radio button in that group must be check, though it doesn't have to be the one with the attribute is applied. for this reason, to improve code maintenance, it is recommened to either include the required attribute in every same-named radio button in the group or none. in the case of a same named group of checkbox input types, only the checkboxes with the required attribute are required. note: setting aria-required="true" tells a screen reader that an element (any element) is required, but has no bearing on the option...
HTML attribute reference - HTML: Hypertext Markup Language
er types such as unsigned long, urls, booleans, etc. unfortunately, there are no clear rules and the way idl attributes behave in conjunction with their corresponding content attributes depends on the attribute. most of the time, it will follow the rules laid out in the specification, but sometimes it doesn't. html specifications try to make this as developer-friendly as possible, but for various reasons (mostly historical), some attributes behave oddly (select.size, for example) and you should read the specifications to understand how exactly they behave. boolean attributes some content attributes (e.g. required, readonly, disabled) are called boolean attributes. if a boolean attribute is present, its value is true, and if it’s absent, its value is false. html5 defines restrictions on the ...
<input type="checkbox"> - HTML: Hypertext Markup Language
Web › HTML › Element › input › checkbox
ding a bigger hit area for your checkboxes in the above examples, you may have noticed that you can toggle a checkbox by clicking on its associated <label> element as well as on the checkbox itself. this is a really useful feature of html form labels that makes it easier to click the option you want, especially on small-screen devices like smartphones. beyond accessibility, this is another good reason to properly set up <label> elements on your forms. indeterminate state checkboxes in addition to the checked and unchecked states, there is a third state a checkbox can be in: indeterminate. this is a state in which it's impossible to say whether the item is toggled on or off. this is set using the htmlinputelement object's indeterminate property via javascript (it cannot be set using an html a...
<input type="datetime-local"> - HTML: Hypertext Markup Language
sn't support form control sizing attributes such as size. you'll have to resort to css for customizing the sizes of these elements. setting timezones one thing the datetime-local input type doesn't provide is a way to set the time zone and/or locale of the date/time control. this was available in the datetime input type, but this type is now obsolete, having been removed from the spec. the main reasons why this was removed are a lack of implementation in browsers, and concerns over the user interface/experience. it is easier to just have a control (or controls) for setting the date/time and then deal with the locale in a separate control. for example, if you are creating a system where the user is likely to already be logged in, with their locale already set, you could provide the timezone in...
<input type="file"> - HTML: Hypertext Markup Language
Web › HTML › Element › input › file
y appropriate server-side validation. notes you cannot set the value of a file picker from a script — doing something like the following has no effect: const input = document.queryselector("input[type=file]"); input.value = "foo"; when a file is chosen using an <input type="file">, the real path to the source file is not shown in the input's value attribute for obvious security reasons. instead, the filename is shown, with c:\fakepath\ appended to the beginning of it. there are some historical reasons for this quirk, but it is supported across all modern browsers, and in fact is defined in the spec. examples in this example, we'll present a slightly more advanced file chooser that takes advantage of the file information available in the htmlinputelement.files property, as...
<input type="image"> - HTML: Hypertext Markup Language
Web › HTML › Element › input › image
alt="login" src="/static/external/62/62ac2ecddbec0e0b540098c28451e57203e5cab46dfed7ab0115d5a659fcfb7b.png"> the src attribute is used to specify the path to the image you want to display in the button. the alt attribute provides alt text for the image, so screen reader users can get a better idea of what the button is used for. it will also display if the image can't be shown for any reason (for example if the path is misspelled). if possible, use text which matches the label you'd use if you were using a standard submit button. the width and height attributes are used to specify the width and height the image should be shown at, in pixels. the button is the same size as the image; if you need the button's hit area to be bigger than the image, you will need to use css (e.g. padding...
<input type="radio"> - HTML: Hypertext Markup Language
Web › HTML › Element › input › radio
for your radio buttons in the above examples, you may have noticed that you can select a radio button by clicking on its associated <label> element, as well as on the radio button itself. this is a really useful feature of html form labels that makes it easier for users to click the option they want, especially on small-screen devices like smartphones. beyond accessibility, this is another good reason to properly set up <label> elements on your forms. validation radio buttons don't participate in constraint validation; they have no real value to be constrained. styling radio inputs the following example shows a slightly more thorough version of the example we've seen throughout the article, with some additional styling, and with better semantics established through use of specialized eleme...
<input type="submit"> - HTML: Hypertext Markup Language
Web › HTML › Element › input › submit
javascript this looks like btn.disabled = true or btn.disabled = false. see the <input type="button"> page for more ideas about enabling and disabling buttons. validation submit buttons don't participate in constraint validation; they have no real value to be constrained. examples we've included simple examples above. there isn't really anything more to say about submit buttons. there's a reason this kind of control is sometimes called a "simple button." specifications specification status comments html living standardthe definition of '<input type="submit">' in that specification. living standard html5the definition of '<input type="submit">' in that specification. recommendation ...
<input type="tel"> - HTML: Hypertext Markup Language
Web › HTML › Element › input › tel
pattern is obviously only useful for certain locales — in a real application you'd probably have to vary the pattern used depending on the locale of the user. examples in this example, we present a simple interface with a <select> element that lets the user choose which country they're in, and a set of <input type="tel"> elements to let them enter each part of their phone number; there is no reason why you can't have multiple tel inputs. each input has a placeholder attribute to show a hint to sighted users about what to enter into it, a pattern to enforce a specific number of characters for the desired section, and an aria-label attribute to contain a hint to be read out to screenreader users about what to enter into it. <form> <div> <label for="country">choose your country:</label...
<link>: The External Resource Link element - HTML: Hypertext Markup Language
Web › HTML › Element › link
, but is actually now recommended practice. it is also used on rel="preload" link types, to make sure the browser only downloads file types that it supports. non-standard attributes methods the value of this attribute provides information about the functions that might be performed on an object. the values generally are given by the http protocol when it is used, but it might (for similar reasons as for the title attribute) be useful to include advisory information in advance in the link. for example, the browser might choose a different rendering of a link as a function of the methods specified; something that is searchable might get a different icon, or an outside link might render with an indication of leaving the current site. this attribute is not well understood nor supported, even...
<style>: The Style Information element - HTML: Hypertext Markup Language
Web › HTML › Element › style
heets to your document depending on media features such as viewport width. attributes this element includes the global attributes. type this attribute defines the styling language as a mime type (charset should not be specified). this attribute is optional and defaults to text/css if it is not specified; values other than the empty string or text/css are not used. note: there is very little reason to include this attribute in modern web documents. media this attribute defines which media the style should be applied to. its value is a media query, which defaults to all if the attribute is missing. nonce a cryptographic nonce (number used once) used to whitelist inline styles in a style-src content-security-policy. the server must generate a unique nonce value each time it transmits a po...
<wbr> - HTML: Hypertext Markup Language
Web › HTML › Element › wbr
interface htmlelement attributes this element only includes the global attributes. notes on utf-8 encoded pages, <wbr> behaves like the u+200b zero-width space code point. in particular, it behaves like a unicode bidi bn code point, meaning it has no effect on bidi-ordering: <div dir=rtl>123,<wbr>456</div> displays, when not broken on two lines, 123,456 and not 456,123. for the same reason, the <wbr> element does not introduce a hyphen at the line break point. to make a hyphen appear only at the end of a line, use the soft hyphen character entity (&shy;) instead. this element was first implemented in internet explorer 5.5 and was officially defined in html5. example the yahoo style guide recommends breaking a url before punctuation, to avoid leaving a punctuation mark a...
hidden - HTML: Hypertext Markup Language
ndants of a hidden element are still active, which means that script elements can still execute and form elements can still submit. elements and scripts may, however, refer to elements that are hidden in other contexts. for example, it would be incorrect to use the href attribute to link to a section marked with the hidden attribute. if the content is not applicable or relevant, then there is no reason to link to it. it would be fine, however, to use the aria aria-describedby attribute to refer to descriptions that are themselves hidden. while hiding the descriptions implies that they are not useful on their own, they could be written in such a way that they are useful in the specific context of being referenced from the element that they describe. similarly, a canvas element with the hidden ...
Preloading content with rel="preload" - HTML: Hypertext Markup Language
reloading content can be combined with the philosophy of progressive enhancement. cross-origin fetches if you've got your sites' cors settings worked out properly, you can successfully preload cross-origin resources as long as you set a crossorigin attribute on your <link> element. one interesting case where this applies, even if the fetch is not cross-origin, is font files. because of various reasons, these have to be fetched using anonymous mode cors (see font fetching requirements). let's use this case as an example. you can see the full example source code on github (also see it live): <head> <meta charset="utf-8"> <title>web font example</title> <link rel="preload" href="fonts/cicle_fina-webfont.woff2" as="font" type="font/woff2" crossorigin> <link rel="preload" href="fonts/za...
Quirks Mode and Standards Mode - HTML: Hypertext Markup Language
eta charset=utf-8> <title>hello world!</title> </head> <body> </body> </html> the doctype shown in the example, <!doctype html>, is the simplest possible, and the one recommended by html5. earlier versions of the html standard recommended other variants, but all existing browsers today will use full standards mode for this doctype, even the dated internet explorer 6. there are no valid reasons to use a more complicated doctype. if you do use another doctype, you may risk choosing one which triggers almost standards mode or quirks mode. make sure you put the doctype right at the beginning of your html document. anything before the doctype, like a comment or an xml declaration will trigger quirks mode in internet explorer 9 and older. in html5, the only purpose of the doctype is to ac...
Using the application cache - HTML: Hypertext Markup Language
ache, network, and fallback, discussed below). in the example above, there is no section header, so all data lines are assumed to be in the explicit (cache) section, meaning that the browser should cache all the listed resources in the application cache. resources can be specified using either absolute or relative urls (e.g., index.html). the "v1" comment in the example above is there for a good reason. browsers only update an application cache when the manifest file changes, byte for byte. if you change a cached resource (for example, you update the header.png image with new content), you must also change the content of the manifest file in order to let browsers know that they need to refresh the cache. you can make any change you want to the manifest file, but revising a version number is the...
HTTP authentication - HTTP
in firefox, it is checked if the site actually requires authentication and if not, firefox will warn the user with a prompt "you are about to log in to the site “www.example.com” with the username “username”, but the website does not require authentication. this may be an attempt to trick you." ...
Large-Allocation - HTTP
or the "noopener" feature being set. these windows must remain in the same process as their opener, as they can communicate, meaning that we cannot allow them to switch processes. the document with the large-allocation header has opened another window with window.open(), <a target="_blank"> or other similar methods without rel="noopener" or the "noopener" feature being set. this is for the same reason as above, namely that they can communicate and thus we cannot allow them to switch processes. a large-allocation header was ignored due to the document not being loaded out of process. firefox has moved to a multiprocess architecture, and this architecture is required in order to support the large-allocation header. some legacy addons can prevent firefox from using this new, faster, multipr...
Public-Key-Pins - HTTP
184000; includesubdomains; report-uri="https://www.example.org/hpkp-report" in this example, pin-sha256="cupctazwkaasuywhhnedttwpy3obake3h2+sozs7sws=" pins the server's public key used in production. the second pin declaration pin-sha256="m8hztczm3eluxkcjr2s5p4hhybnf6lhkmjahkhpgpwe=" also pins the backup key. max-age=5184000 tells the client to store this information for two months, which is a reasonable time limit according to the ietf rfc. this key pinning is also valid for all subdomains, which is told by the includesubdomains declaration. finally, report-uri="https://www.example.org/hpkp-report" explains where to report pin validation failures. specifications specification title rfc 7469, section 2.1: public-key-pins public key pinning extension for http ...
Save-Data - HTTP
a value of on indicates explicit user opt-in into a reduced data usage mode on the client, and when communicated to origins allows them to deliver alternative content to reduce the data downloaded such as smaller image and video resources, different markup and styling, disabled polling and automatic updates, and so on. note: disabling http/2 server push (rfc 7540, section 8.2: server push) might be desirable too for reducing data downloads. ...
SameSite cookies - HTTP
request initiated by third party website. this is the default value in modern browsers. strict cookies will only be sent in a first-party context and not be sent along with requests initiated by third party websites. none cookies will be sent in all contexts, i.e sending cross-origin is allowed. none used to be the default value, but recent browser versions made lax the default value to have reasonably robust defense against some classes of cross-site request forgery (csrf) attacks. none requires the secure attribute in latest browser versions. see below for more information. fixing common warnings samesite=none requires secure the following warning might appear in your console: some cookies are misusing the “samesite“ attribute, so it won’t work as expected. cookie “mycookie...
Upgrade - HTTP
Web › HTTP › Headers › Upgrade
ocols, in descending preference order. for example, the client might send a get request as shown, listing the preferred protocols to switch to (in this case "example/1" and "foo/2"): get /index.html http/1.1 host: www.example.com connection: upgrade upgrade: example/1, foo/2 note: connection: upgrade must be set whenever upgrade is sent. the server can choose to ignore the request, for any reason, in which case it should just respond as though the upgrade header had not been sent (for example, with a  200 ok). if the server decides to upgrade the connection, it must: send back a 101 switching protocols response status with an upgrade header that specifies the protocol(s) being switched to. for example: http/1.1 101 switching protocols upgrade: foo/2 connection: upgrade send a r...
Firefox user agent string reference - HTTP
.1.1", or "seamonkey/2.7.1". firefox/firefoxversion is an optional compatibility token that some gecko-based browsers may choose to incorporate, to achieve maximum compatibility with websites that expect firefox. firefoxversion will generally represent the equivalent firefox release corresponding to the given gecko version. some gecko-based browsers may not opt into using this token; for this reason, sniffers should be looking for gecko — not firefox! whether this token appears is controlled by the "general.useragent.compatmode.firefox" boolean pref. mobile and tablet indicators only from firefox 11 onwards. the platform part of the ua string indicates if firefox is running on a phone-sized or tablet device. when firefox runs on a device that has the phone form factor, there is a m...
User-Agent - HTTP
s; sub-product information, for example. firefox ua string for more on firefox- and gecko-based user agent strings, see the firefox user agent string reference. the ua string of firefox is broken down into 4 components: mozilla/5.0 (platform; rv:geckoversion) gecko/geckotrail firefox/firefoxversion mozilla/5.0 is the general token that says the browser is mozilla-compatible. for historical reasons, almost every browser today sends it. platform describes the native platform the browser is running on (windows, mac, linux, android, etc.), and if it's a mobile phone. firefox os phones simply say mobile — the web is the platform. note that platform can consist of multiple "; "-separated tokens. see below for further details and examples. rv:geckoversion indicates the release version of gec...
POST - HTTP
Web › HTTP › Methods › POST
ent type is selected by putting the adequate string in the enctype attribute of the <form> element or the formenctype attribute of the <input> or <button> elements: application/x-www-form-urlencoded: the keys and values are encoded in key-value tuples separated by '&', with a '=' between the key and the value. non-alphanumeric characters in both keys and values are percent encoded: this is the reason why this type is not suitable to use with binary data (use multipart/form-data instead) multipart/form-data: each value is sent as a block of data ("body part"), with a user agent-defined delimiter ("boundary") separating each part. the keys are given in the content-disposition header of each part. text/plain when the post request is sent via a method other than an html form — like via an x...
An overview of HTTP - HTTP
Web › HTTP › Overview
er privacy invasions, web browsers enforce strict separation between web sites. only pages from the same origin can access all the information of a web page. though such constraint is a burden to the server, http headers can relax this strict separation on the server side, allowing a document to become a patchwork of information sourced from different domains; there could even be security-related reasons to do so. authentication some pages may be protected so that only specific users can access them. basic authentication may be provided by http, either using the www-authenticate and similar headers, or by setting a specific session using http cookies. proxy and tunneling servers or clients are often located on intranets and hide their true ip address from other computers. http requests the...
HTTP Public Key Pinning (HPKP) - HTTP
184000; includesubdomains; report-uri="https://www.example.org/hpkp-report" in this example, pin-sha256="cupctazwkaasuywhhnedttwpy3obake3h2+sozs7sws=" pins the server's public key used in production. the second pin declaration pin-sha256="m8hztczm3eluxkcjr2s5p4hhybnf6lhkmjahkhpgpwe=" also pins the backup key. max-age=5184000 tells the client to store this information for two months, which is a reasonable time limit according to the ietf rfc. this key pinning is also valid for all subdomains, which is told by the includesubdomains declaration. finally, report-uri="https://www.example.net/hpkp-report" explains where to report pin validation failures. report-only header instead of using a public-key-pins header you can also use a public-key-pins-report-only header. this header only sends repor...
416 Range Not Satisfiable - HTTP
Web › HTTP › Status › 416
the 416 response message contains a content-range indicating an unsatisfied range (that is a '*') followed by a '/' and the current length of the resource. e.g. ...
HTTP response status codes - HTTP
Web › HTTP › Status
modified the state on the server, leading to a conflict. 429 too many requests the user has sent too many requests in a given amount of time ("rate limiting"). 431 request header fields too large the server is unwilling to process the request because its header fields are too large. the request may be resubmitted after reducing the size of the request header fields. 451 unavailable for legal reasons the user-agent requested a resource that cannot legally be provided, such as a web page censored by a government. server error responses 500 internal server error the server has encountered a situation it doesn't know how to handle. 501 not implemented the request method is not supported by the server and cannot be handled. the only methods that servers are required to support (and ther...
A re-introduction to JavaScript (JS tutorial) - JavaScript
rules: false, 0, empty strings (""), nan, null, and undefined all become false. all other values become true. you can perform this conversion explicitly using the boolean() function: boolean(''); // false boolean(234); // true however, this is rarely necessary, as javascript will silently perform this conversion when it expects a boolean, such as in an if statement (see below). for this reason, we sometimes speak simply of "true values" and "false values," meaning values that become true and false, respectively, when converted to booleans. alternatively, such values can be called "truthy" and "falsy", respectively. boolean operations such as && (logical and), || (logical or), and ! (logical not) are supported; see below. variables new variables in javascript are declared using one o...
Functions - JavaScript
mple: a function (a) contains a function (b), which itself contains a function (c). both functions b and c form closures here. so, b can access a, and c can access b. in addition, since c can access b which can access a, c can also access a. thus, the closures can contain multiple scopes; they recursively contain the scope of the functions containing it. this is called scope chaining. (the reason it is called "chaining" is explained later.) consider the following example: function a(x) { function b(y) { function c(z) { console.log(x + y + z); } c(3); } b(2); } a(1); // logs 6 (1 + 2 + 3) in this example, c accesses b's y and a's x. this can be done because: b forms a closure including a (i.e. b can access a's arguments and variables). c forms a closure inc...
Introduction - JavaScript
rver can respond to custom requests from code written in the browser. javascript and java javascript and java are similar in some ways but fundamentally different in some others. the javascript language resembles java but does not have java's static typing and strong type checking. javascript follows most java expression syntax, naming conventions and basic control-flow constructs which was the reason why it was renamed from livescript to javascript. in contrast to java's compile-time system of classes built by declarations, javascript supports a runtime system based on a small number of data types representing numeric, boolean, and string values. javascript has a prototype-based object model instead of the more common class-based object model. the prototype-based model provides dynamic inher...
JavaScript modules - JavaScript
) — writes a square's area to a specific report list, given its length. reportperimeter() — writes a square's perimeter to a specific report list, given its length. aside — .mjs versus .js throughout this article, we've used .js extensions for our module files, but in other resources you may see the .mjs extension used instead. v8's documentation recommends this, for example. the reasons given are: it is good for clarity, i.e. it makes it clear which files are modules, and which are regular javascript. it ensures that your module files are parsed as a module by runtimes such as node.js, and build tools such as babel. however, we decided to keep to using .js, at least for the moment. to get modules to work correctly in a browser, you need to make sure that your server is se...
Regular expressions - JavaScript
n advanced searching with flags.) 5 source the text of the pattern. updated at the time that the regular expression is created, not executed. 'd(b+)d' as shown in the second form of this example, you can use a regular expression created with an object initializer without assigning it to a variable. if you do, however, every occurrence is a new regular expression. for this reason, if you use this form without assigning it to a variable, you cannot subsequently access the properties of that regular expression. for example, assume you have this script: var myre = /d(b+)d/g; var myarray = myre.exec('cdbbdbsbz'); console.log('the value of lastindex is ' + myre.lastindex); // "the value of lastindex is 5" however, if you have this script: var myarray = /d(b+)d/g.exec('cdb...
Working with objects - JavaScript
property is also an object with its own properties. var myhonda = {color: 'red', wheels: 4, engine: {cylinders: 4, size: 2.2}}; you can also use object initializers to create arrays. see array literals. using a constructor function alternatively, you can create an object with these two steps: define the object type by writing a constructor function. there is a strong convention, with good reason, to use a capital initial letter. create an instance of the object with new. to define an object type, create a function for the object type that specifies its name, properties, and methods. for example, suppose you want to create an object type for cars. you want this type of object to be called car, and you want it to have properties for make, model, and year. to do this, you would write the...
Inheritance and the prototype chain - JavaScript
is undefined. the property might very well exist, but its value just happens to be set to undefined. bad practice: extension of native prototypes one misfeature that is often used is to extend object.prototype or one of the other built-in prototypes. this technique is called monkey patching and breaks encapsulation. while used by popular frameworks such as prototype.js, there is still no good reason for cluttering built-in types with additional non-standard functionality. the only good reason for extending a built-in prototype is to backport the features of newer javascript engines, like array.foreach. summary of methods for extending the prototype chain here are all 4 ways and their pros/cons. all of the examples listed below create exactly the same resulting inst object (thus logging th...
arguments.callee - JavaScript
ecmascript (es5) forbids use of arguments.callee() in strict mode. avoid using arguments.callee() by either giving function expressions a name or use a function declaration where a function must call itself. why was arguments.callee removed from es5 strict mode? (adapted from a stack overflow answer by olliej) early versions of javascript did not allow named function expressions, and for this reason you could not make a recursive function expression. for example, this syntax worked: function factorial (n) { return !(n > 1) ? 1 : factorial(n - 1) * n; } [1, 2, 3, 4, 5].map(factorial); but: [1, 2, 3, 4, 5].map(function(n) { return !(n > 1) ? 1 : /* what goes here? */ (n - 1) * n; }); did not. to get around this arguments.callee was added so you could do [1, 2, 3, 4, 5].map(funct...
Array.prototype.values() - JavaScript
see iteration protocols. value: there are no values stored in the array iterator object; instead it stores the address of the array used in its creation and so depends on the values stored in that array. var arr = ['a', 'b', 'c', 'd', 'e']; var iterator = arr.values(); console.log(iterator); // array iterator { } ite...
BigInt - JavaScript
d object in the specified radix (base). overrides the object.prototype.tostring() method. bigint.prototype.valueof() returns the primitive value of the specified object. overrides the object.prototype.valueof() method. usage recommendations coercion because coercing between number and bigint can lead to loss of precision, it is recommended to only use bigint when values greater than 253 are reasonably expected and not to coerce between the two types. cryptography the operations supported on bigints are not constant time. bigint is therefore unsuitable for use in cryptography. use within json using json.stringify() with any bigint value will raise a typeerror as bigint values aren't serialized in json by default. however, you can implement your own tojson method if needed: bigint.proto...
Date.prototype.toLocaleString() - JavaScript
t of the time, the formatting returned by tolocalestring() is consistent. however, this might change in the future, and isn't guaranteed for all languages; output variations are by design, and allowed by the specification. most notably, the ie and edge browsers insert bidirectional control characters around dates, so the output text will flow properly when concatenated with other text. for this reason, you cannot expect to be able to compare the results of tolocalestring() to a static value: "1/1/2019, 01:00:00" === new date("2019-01-01t01:00:00z").tolocalestring("en-us"); // true in firefox and others // false in ie and edge note: see also this stackoverflow thread for more details and examples. specifications specification ecmascript (ecma-262)the definition of 'd...
Function.caller - JavaScript
p level code, the value of f.caller is null, otherwise it's the function that called f. it's also null for strict, async function and generator function callers. this property replaces the obsolete arguments.caller property of the arguments object. the special property __caller__, which returned the activation object of the caller thus allowing to reconstruct the stack, was removed for security reasons. notes note that in case of recursion, you can't reconstruct the call stack using this property. consider: function f(n) { g(n - 1); } function g(n) { if (n > 0) { f(n); } else { stop(); } } f(2); at the moment stop() is called the call stack will be: f(2) -> g(1) -> f(1) -> g(0) -> stop() the following is true: stop.caller === g && f.caller === g && g.caller === f so if you tried to ...
Intl.DateTimeFormat.prototype.format() - JavaScript
most of the time, the formatting returned by format() is consistent. however, this might change in the future and isn't guaranteed for all the languages — output variations are by design and allowed by the specification. most notably, the ie and edge browsers insert bidirectional control characters around dates, so the output text will flow properly when concatenated with other text. ...
Map - JavaScript
tics of the === operator. in the current ecmascript specification, -0 and +0 are considered equal, although this was not so in earlier drafts. see "value equality for -0 and 0" in the browser compatibility table for details. objects vs. maps object is similar to map—both let you set keys to values, retrieve those values, delete keys, and detect whether something is stored at a key. for this reason (and because there were no built-in alternatives), objects have been used as maps historically. however, there are important differences that make map preferable in certain cases: map object accidental keys a map does not contain any keys by default. it only contains what is explicitly put into it. an object has a prototype, so it contains default keys th...
Math.atan() - JavaScript
a constructor). examples using math.atan() math.atan(1); // 0.7853981633974483 math.atan(0); // 0 math.atan(-0); // -0 math.atan(infinity); // 1.5707963267948966 math.atan(-infinity); // -1.5707963267948966 // the angle that the line [(0,0);(x,y)] forms with the x-axis in a cartesian coordinate system math.atan(y / x); note that you may want to avoid using ±infinity for stylistic reasons. in this case, math.atan2() with 0 as the second argument may be a better solution. specifications specification ecmascript (ecma-262)the definition of 'math.atan' in that specification. ...
Math.clz32() - JavaScript
true performance masterpiece. situations like these are exactly what asm.js was designed for. var counttrailsmethods = (function(stdlib, foreign, heap) { "use asm"; var clz = stdlib.math.clz32; function ctrz(integer) { // count trailing zeros integer = integer | 0; // coerce to an integer // 1. fill in all the higher bits after the first one // asmjs for some reason does not allow ^=,&=, or |= integer = integer | (integer << 16); integer = integer | (integer << 8); integer = integer | (integer << 4); integer = integer | (integer << 2); integer = integer | (integer << 1); // 2. now, inversing the bits reveals the lowest bits return 32 - clz(~integer) |0; } function ctron(integer) { // count trail...
Math.imul() - JavaScript
ath, you always use it as math.imul(), rather than as a method of a math object you created (math is not a constructor). if you use normal javascript floating point numbers in imul, you will experience a degrade in performance. 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. the reason imul exists is because it is faster in only one (so far) circumstance: asmjs. asmjs allows for jist-optimizers to more easily implement internal integers in javascript. multiplying two numbers stored internally as integers (which is only possible with asmjs) with imul is the only potential circumstance where math.imul may prove performant in current browsers. polyfill this can be emulated with...
Number.MAX_SAFE_INTEGER - JavaScript
ject, please clone https://github.com/mdn/interactive-examples and send us a pull request. property attributes of number.max_safe_integer writable no enumerable no configurable no description the max_safe_integer constant has a value of 9007199254740991 (9,007,199,254,740,991 or ~9 quadrillion). the reasoning behind that number is that javascript uses double-precision floating-point format numbers as specified in ieee 754 and can only safely represent numbers between -(253 - 1) and 253 - 1. safe in this context refers to the ability to represent integers exactly and to correctly compare them. for example, number.max_safe_integer + 1 === number.max_safe_integer + 2 will evaluate to true, which is m...
Number.MIN_SAFE_INTEGER - JavaScript
ease clone https://github.com/mdn/interactive-examples and send us a pull request. property attributes of number.min_safe_integer writable no enumerable no configurable no description the min_safe_integer constant has a value of -9007199254740991 (-9,007,199,254,740,991 or about -9 quadrillion). the reasoning behind that number is that javascript uses double-precision floating-point format numbers as specified in ieee 754 and can only safely represent numbers between -(253 - 1) and 253 - 1. see number.issafeinteger() for more information. because min_safe_integer is a static property of number, you always use it as number.min_safe_integer, rather than as a property of a number object you created.
Object.freeze() - JavaScript
comparison to object.seal() objects sealed with object.seal() can have their existing properties changed. existing properties in objects frozen with object.freeze() are made immutable. examples freezing objects var obj = { prop: function() {}, foo: 'bar' }; // before freezing: new properties may be added, // and existing properties may be chan...
Promise.reject() - JavaScript
the promise.reject() method returns a promise object that is rejected with a given reason. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax promise.reject(reason); parameters reason reason why this promise rejected. return value a promise that is rejected with the given reason. description the static promise.reject function returns a promise that is rejected. for debugging purposes and selective error catching, it is useful to make reason an instanceof error. examples using the static promise.reject() method promise.reject(new error('fail')).then(function() { // not called }, function(error) { ...
String.fromCharCode() - JavaScript
xd83c, 0xdf03) and \ud83c\udf03 return code point u+1f303 "night with stars". while there is a mathematical relationship between the supplementary code point value (e.g. 0x1f303) and both surrogate values that represent it (e.g., 0xd83c and 0xdf03), it does require an extra step to either calculate or look up the surrogate pair values every time a supplementary code point is to be used. for this reason, it's more convenient to use string.fromcodepoint() (part of the es2015 standard), which allows for returning supplementary characters based on their actual code point value. for example, string.fromcodepoint(0x1f303) returns code point u+1f303 "night with stars". examples using fromcharcode() bmp characters, in utf-16, use a single code unit: string.fromcharcode(65, 66, 67); // returns "a...
String.prototype.matchAll() - JavaScript
ypeerror matchall internally makes a clone of the regexp—so, unlike regexp.exec(), lastindex does not change as the string is scanned. const regexp = regexp('[a-c]','g'); regexp.lastindex = 1; const str = 'abc'; array.from(str.matchall(regexp), m => `${regexp.lastindex} ${m[0]}`); // array [ "1 b", "1 c" ] better access to capturing groups (than string.prototype.match()) another compelling reason for matchall is the improved access to capture groups. capture groups are ignored when using match() with the global /g flag: let regexp = /t(e)(st(\d?))/g; let str = 'test1test2'; str.match(regexp); // array ['test1', 'test2'] using matchall, you can access capture groups easily: let array = [...str.matchall(regexp)]; array[0]; // ['test1', 'e', 'st1', '1', index: 0, input: 'test1test2', l...
String.prototype.trimEnd() - JavaScript
g representing the calling string stripped of whitespace from its (right) end. description the trimend() / trimright() methods return the string stripped of whitespace from its right end. trimend() or trimright() do not affect the value of the string itself. aliasing for consistency with functions like string.prototype.padend the standard method name is trimend. however, for web compatibility reasons, trimright remains as an alias to trimend. in some engines this means: string.prototype.trimright.name === "trimend"; examples using trimend() the following example displays the lowercase string ' foo': var str = ' foo '; console.log(str.length); // 8 str = str.trimend(); console.log(str.length); // 6 console.log(str); // ' foo' specifications specification ...
String.prototype.trimStart() - JavaScript
the calling string stripped of whitespace from its beginning (left end). description the trimstart() / trimleft() methods return the string stripped of whitespace from its left end. trimleft() or trimstart() do not affect the value of the string itself. aliasing for consistency with functions like string.prototype.padstart the standard method name is trimstart. however, for web compatibility reasons, trimleft remains as an alias to trimstart. in some engines this means: string.prototype.trimleft.name === "trimstart"; polyfill //https://github.com/fabiovergani/js-polyfill_string-trimstart (function(w){ var string=w.string, proto=string.prototype; (function(o,p){ if(p in o?o[p]?false:true:true){ var r=/^\s+/; o[p]=o.trimleft||function(){ ...
String - JavaScript
ng eval(). primitives passed to eval are treated as source code; string objects are treated as all other objects are, by returning the object. for example: let s1 = '2 + 2' // creates a string primitive let s2 = new string('2 + 2') // creates a string object console.log(eval(s1)) // returns the number 4 console.log(eval(s2)) // returns the string "2 + 2" for these reasons, the code may break when it encounters string objects when it expects a primitive string instead, although generally, authors need not worry about the distinction. a string object can always be converted to its primitive counterpart with the valueof() method. console.log(eval(s2.valueof())) // returns the number 4 escape notation special characters can be encoded using escape notation: ...
WebAssembly.Table.prototype.grow() - JavaScript
the grow() prototype method of the webassembly.table object increases the size of the table instance by a specified number of elements. syntax table.grow(number); parameters number the number of elements you want to grow the table by. return value the previous length of the table. exceptions if the grow() operation fails for whatever reason, a rangeerror is thrown. examples using grow the following example creates a new webassembly table instance with an initial size of 2 and a maximum size of 10. 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 specificati...
isNaN() - JavaScript
// parsing this as a number fails and returns nan useful special-case behavior there is a more usage oriented way to think of isnan(): if isnan(x) returns false, you can use x in an arithmetic expression not making the expression return nan. if it returns true, x will make every...
null - JavaScript
alized: foo; //referenceerror: foo is not defined // foo is known to exist now but it has no type or value: var foo = null; foo; //null examples difference between null and undefined when checking for null or undefined, beware of the differences between equality (==) and identity (===) operators, as the former performs type-conversion. typeof null // "object" (not "null" for legacy reasons) typeof undefined // "undefined" null === undefined // false null == undefined // true null === null // true null == null // true !null // true isnan(1 + null) // false isnan(1 + undefined) // true specifications specification ecmascript (ecma-262)the definition of 'null value' in that specification. ...
parseInt() - JavaScript
x" (a zero, followed by lowercase or uppercase x), radix is assumed to be 16 and the rest of the string is parsed as a hexidecimal number. if the input string begins with "0" (a zero), radix is assumed to be 8 (octal) or 10 (decimal). exactly which radix is chosen is implementation-dependent. ecmascript 5 clarifies that 10 (decimal) should be used, but not all browsers support this yet. for this reason, always specify a radix when using parseint. if the input string begins with any other value, the radix is 10 (decimal). if the first character cannot be converted to a number, parseint returns nan. for arithmetic purposes, the nan value is not a number in any radix. you can call the isnan function to determine if the result of parseint is nan. if nan is passed on to arithmetic operations, th...
undefined - JavaScript
operator (as opposed to the standard equality operator) must be used here, because x == undefined also checks whether x is null, while strict equality doesn't. this is because null is not equivalent to undefined. see comparison operators for details. typeof operator and undefined alternatively, typeof can be used: var x; if (typeof x === 'undefined') { // these statements execute } one reason to use typeof is that it does not throw an error if the variable has not been declared. // x has not been declared before if (typeof x === 'undefined') { // evaluates to true without errors // these statements execute } if (x === undefined) { // throws a referenceerror } however, there is another alternative. javascript is a statically scoped language, so knowing if a variable is decl...
import - JavaScript
{ if (somethingistrue) { const { default: mydefault, foo, bar } = await import('/modules/my-module.js'); } })(); dynamic imports the standard import syntax is static and will always result in all code in the imported module being evaluated at load time. in situations where you wish to load a module conditionally or on demand, you can use a dynamic import instead. the following are some reasons why you might need to use dynamic import: when importing statically significantly slows the loading of your code and there is a low likelihood that you will need the code you are importing, or you will not need it until a later time. when importing statically significantly increases your program's memory usage and there is a low likelihood that you will need the code you are importing. when...
var - JavaScript
any code is executed, declaring a variable anywhere in the code is equivalent to declaring it at the top. this also means that a variable can appear to be used before it's declared. this behavior is called "hoisting", as it appears that the variable declaration is moved to the top of the function or global code. bla = 2; var bla; // ...is implicitly understood as: var bla; bla = 2; for that reason, it is recommended to always declare variables at the top of their scope (the top of global code and the top of function code) so it's clear which variables are function scoped (local) and which are resolved on the scope chain. it's important to point out that the hoisting will affect the variable declaration, but not its value's initialization. the value will be indeed assigned when the assignm...
Strict mode - JavaScript
); third, arguments for strict mode functions no longer provide access to the corresponding function call's variables. in some old ecmascript implementations arguments.caller was an object whose properties aliased variables in that function. this is a security hazard because it breaks the ability to hide privileged values via function abstraction; it also precludes most optimizations. for these reasons no recent browsers implement it. yet because of its historical functionality, arguments.caller for a strict mode function is also a non-deletable property which throws when set or retrieved: 'use strict'; function fun(a, b) { 'use strict'; var v = 12; return arguments.caller; // throws a typeerror } fun(1, 2); // doesn't expose v (or a or b) paving the way for future ecmascript versions...
Authoring MathML - MathML
th/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. see this github repository to get woff fonts and sample css stylesheets to use on your web site and check its test page. mathml in xml documents (xhtml, epub, etc) if for some reason you need to use mathml in xml documents, be sure to satisfy the usual requirements: well-formed document, use of correct mime type, mathml namespace "http://www.w3.org/1998/math/mathml" on <math> roots. for example, the xhtml version of the previous example looks like this: <?xml version="1.0" encoding="utf-8"?> <!doctype html public "-//w3c//dtd xhtml 1.1 plus mathml 2.0//en" "http://www.w...
Digital audio concepts - Web media technologies
ate is used for compact disc (cd) audio. cds provide uncompressed 16-bit stereo sound at 44.1 khz. computer audio also frequently uses this frequency by default. 48000 hz the audio on dvd is recorded at 48 khz. this is also often used for computer audio. 96000 hz high-resolution audio. 192000 hz ultra-high resolution audio. not commonly used yet, but this will change over time. there is a reason why 44.1 khz is considered the minimum "high fidelity" sampling rate. the nyquist-shannon sampling theorem dictates that to reproduce a sound accurately, it must be sampled at twice the rate of the sound's frequency. since the range of human hearing is from around 20 hz to 20,000 hz, reproducing the highest-pitched sounds people can generally hear requires a sample rate of more than 40,000 hz. t...
Media container formats (file types) - Web media technologies
on slow networks, consider providing a version of your media in a 3gp container with appropriate compression. if you have any specific encoding requirements, make sure the container you choose supports the appropriate codecs. if you want your media to be in a non-proprietary, open format, consider using one of the open container formats such as flac (for audio) or webm (for video). if for any reason you are only able to provide media in a single format, choose a format that's available on the broadest selection of devices and browsers, such as mp3 (for audio) or mp4 (for video and/or audio). if your media is audio-only, choosing an audio-only container format likely makes sense. now that the patents have all expired, mp3 is a widely supported and good choice. wave is good but uncompressed, ...
Handling media support issues in web content - Web media technologies
the availability of choices is good for the user, in that they can choose the format that suits their needs best. there is a drawback, however: because there are so many to choose from, with so many different kinds of licenses and design principles involved, each web browser developer is left to its own devices when deciding which media file types and codecs to support. this places a small, but reasonably easily overcome, burden on the web developer: to properly handle the situation when the user's browser can't handle a particular type of media. this guide covers techniques you can use to develop web content that meets your media needs while providing the most broadly compatible experience possible. topics we will examine fallbacks, baseline media formats, and error handling practices that wi...
Mapping the width and height attributes of media container elements to their aspect-ratio - Web media technologies
when the image finally loads, the same jank will occur as the page layout is shifted to make space for it. a new way of sizing images before loading completes recognizing the problem, a wicg community group formed to propose an intrinsicsize attribute. folks from mozilla then expanded on this thinking, working on a proposal in the css box sizing level 4 draft to de...
Animation performance and frame rate - Web Performance
rview compared with the version that uses margin, we're seeing a lot less green and a lot more pink, which could be either layout or style recalculation. frame rate compared with the version that uses margin, this is looking pretty good. we're averaging nearly 60fps, and apart from one dip near the start, we're getting a consistently high frame rate. waterfall the timeline view shows the reason for the improved frame rate. compared with the version that uses margin, we're not spending any time time in layout or (more importantly in this case) in paint: in this case, using transform significantly improved the site's performance, and the performance tools were able to show how and why it did. ...
Recommended Web Performance Timings: How long is too long? - Web Performance
ser interaction, and ensuring smooth animations: idling goal browsers are single threaded (though background threads are supported for web workers). this means that user interaction, painting, and script execution are all on the same thread. if the thread is busy doing complex javascript execution, the main thread will not be available to react to user input, such as pressing a button. for this reason, script execution should be limited in scope, divided into chunks of code that can be executed in 50ms or less. this makes the thread available for user interactions. animation goal for scrolling and other animations to look smooth and feel responsive, the content repaints should occur at 60 frames per second (60fps), which is once every 16.7ms. the 16.7 milliseconds includes scripting, reflow,...
Optimizing startup performance - Web Performance
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. this will prevent the app, browser, and/or device from appearing to have locked up. why is it important to be asynchronous? other than the reasons suggested above, consider the impact of a non-responsive page or user interface. the user is unable to cancel if they launched your app by mistake. if the app is being run in a browser, it's possible the user may get an "unresponsive app" or "slow script" notification. you should present some kind of interface, such as a progress bar, so that the user knows how much longer they'll need to wait w...
Privacy, permissions, and information security
t from another site inside your own, especially if the document you load into the frame has its own permission needs to consider. while specifications for these technologies either state or recommend tactics for handling situations like this, browsers may offer different solutions to improve security even further or to try new features, or try to reduce complexity for users, among other possible reasons. <--- allow attribute, feature policy, and permissions api stuff ---> a specific user experience issue that often arises is a document that's loaded with permission to access a resource and the document contains an <iframe> with the allow attribute to delegate that permission to the contents of the frame. in this case, it's possible for the user to wind up being prompted repeatedly for that sa...
How to make PWAs re-engageable using Notifications and Push - Progressive web apps (PWAs)
explained in the making pwas work offline with service workers article. inside the service worker, a push service subscription mechanism is created. registration.pushmanager.getsubscription() .then( /* ... */ ); once the user is subscribed, they can receive push notifications from the server. from the server-side, the whole process has to be encrypted with public and private keys for security reasons — allowing everyone to send push messages unsecured using your app would be a terrible idea. see the web push data encryption test page for detailed information about securing the server. the server stores all the information received when the user subscribed, so the messages can be sent later on when needed. to receive push messages, we can listen to the push event in the service worker file...
patternTransform - SVG: Scalable Vector Graphics
pply the transformed pattern tile --> <rect x="10" y="10" width="80" height="80" fill="url(#p1)" /> </svg> pattern for <pattern>, patterntransform defines a list of transform definitions that are applied to a pattern tile. note: as of svg2, it is also allowed to use the css transform property. however, the current state of implementation isn't very good. for backward compatibility reason, it is highly suggested to keep using the patterntransform attribute. value <transform-list> default value identity transform animatable yes transform functions to know more about the definition of transform functions, see the transform attribute definition. specifications specification status comment scalable vector graph...
requiredFeatures - SVG: Scalable Vector Graphics
face. in some cases the feature strings map directly to a set of attributes, properties or elements, in others they represent some functionality of the browser. note that the format and naming for feature strings changed from svg 1.0 to svg 1.1. the svg 1.0 feature strings are not listed here but can be found in the svg specification. some browser support svg 1.0 feature strings for compatibility reasons. however, the svg 1.0 feature strings are considered deprecated. http://www.w3.org/tr/svg11/feature#svg at least one of the following feature is supported: http://www.w3.org/tr/svg11/feature#svg-static http://www.w3.org/tr/svg11/feature#svg-animation http://www.w3.org/tr/svg11/feature#svg-dynamic http://www.w3.org/tr/svg11/feature#svgdom http://www.w3.org/tr/svg11/feature#s...
Content type - SVG: Scalable Vector Graphics
specify the element whose id is "lamppost" within file somedrawing.svg: http://example.com/somedrawing.svg#lamppost iris are used in the xlink:href attribute. some attributes allow both iris and text strings as content. to disambiguate a text string from a relative iri, the functional notation <funciri> is used. this is simply an iri delimited with a functional notation. note: for historical reasons, the delimiters are "url(" and ")", for compatibility with the css specifications. the funciri form is used in presentation attributes . svg makes extensive use of iri references, both absolute and relative, to other objects. 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">...</...
<use> - SVG: Scalable Vector Graphics
Web › SVG › Element › use
set on the referenced element. however, any other attributes not set on the referenced element will be applied to the use element. since the cloned nodes are not exposed, care must be taken when using css to style a use element and its cloned descendants. css properties are not guaranteed to be inherited by the cloned dom unless you explicitly request them using css inheritance. for security reasons, browsers may apply the same-origin policy on use elements and may refuse to load a cross-origin url in the href attribute. there is currently no defined way to set a cross-origin policy for use elements. since svg 2, the xlink:href attribute is deprecated in favor of href. see xlink:href page for more information. however, xlink:href can still be required in practice for cross-browser compati...
Specification Deviations - SVG: Scalable Vector Graphics
the 'class' and 'style' attributes unlike html and mathml, the svg specification does not specify the 'style' and 'class' attributes on all svg elements. nevertheless, to allow mozilla to more cleanly share internal 'class' and 'style' related code, we will implement these attributes on all svg elements as of firefox 3. ...
Basic shapes - SVG: Scalable Vector Graphics
, 1 2, 2. the drawing then closes the path, so a final straight line would be drawn from (2,2) to (0,0). path a <path> is the most general shape that can be used in svg. using a path element, you can draw rectangles (with or without rounded corners), circles, ellipses, polylines, and polygons. basically any of the other types of shapes, bezier curves, quadratic curves, and many more. for this reason, the next section in this tutorial will be focused on paths. but for now, note that there is a single parameter used to control its shape. <path d="m20,230 q40,205 50,230 t90,230" fill="none" stroke="blue" stroke-width="5"/> d a list of points and other information about how to draw the path. see the paths section for more information. « previousnext » ...
Filter effects - SVG: Scalable Vector Graphics
filters are svg's mechanism to create sophisticated effects. a basic example is to add a blur effect to svg content. while basic blurs can be achieved with the help of gradients, the blur filter is needed to do anything beyond. example filters are defined by <filter> element, which should be put in the <defs> section of your svg file. ...
Getting started - SVG: Scalable Vector Graphics
ok at the http response headers. if you find that your server is not sending the headers with the values given above, then you should contact your web host. if you have problems convincing them to correctly configure their servers for svg, there may be ways to do it yourself. see the server configuration page on the w3.org for a range of simple solutions. server misconfiguration is a very common reason for svg failing to load, so make sure you check yours. 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. « previousnext » ...
Patterns - SVG: Scalable Vector Graphics
Web › SVG › Tutorial › Patterns
and one circle. the confusing thing about patterns is defining a unit system and their size. in the example above, we've defined a width and height attribute on the pattern element to describe how far the pattern should go before it begins repeating itself again. there are also x and y attributes available if you want to offset the start point of this rectangle somewhere within your drawing. the reason they've been used here is described below. as with the gradientunits attribute used above, patterns also have an attribute, patternunits, which specifies the units that these attributes will take. it defaults to "objectboundingbox" as it did above, so a value of 1 is scaled to the width/height of the object you're applying the pattern to. since, in this case, we wanted the pattern to repeat 4 ti...
SVG In HTML Introduction - SVG: Scalable Vector Graphics
flow. the style attribute pins the svg element to the background of the form. ...
SVG fonts - SVG: Scalable Vector Graphics
<!-- outline of exclam. pt. glyph --></glyph> <glyph unicode="@"><!-- outline of @ glyph --></glyph> <!-- more glyphs --> </font> we start with the <font> element. this bears an id attribute, to enable it to be referenced via a uri (see below). the horiz-adv-x attribute determines how wide a character is on average compared to the path definitions of the single glyphs. the value 1000 sets a reasonable value to work with. there are several accompanying attributes that help further define the basic glyph-box layout. the <font-face> element is the svg equivalent of the css @font-face declaration. it defines basic properties of the final font such as weight, style, etc. in the example above the first and most important to be defined is font-family, the value of which can then be referenced in...
mimeTypes.rdf corruption - SVG: Scalable Vector Graphics
this page explains a problem that can cause svg to stop working in mozilla due to the way mozilla maps filename extensions to media types. symptoms previously you were able to open and display svg content with mozilla, but for no apparent reason its behaviour changes and now it always pops up the "open or save file" dialog when you try to open local svg files, and displays the "additional plugins are required to display all the media on this page" bar when you try to view html with embedded svg. note: the "additional plugins are required" bar can appear for legitimate reasons when the svg or its embedding html is broken or served incorrectly over the network (see the svg faq). if the blue square with the white cross displays when you load this scripting across embed demo, then you are...
Information Security Basics - Web security
these articles can help you learn what you need to know. with this information, you can be aware of the role and importance of security throughout the web development cycle and beyond into deployment of your content. ...
Same-origin policy - Web security
tocol, port (if specified), and host are the same for both. you may see this referenced as the "scheme/host/port tuple", or just "tuple". ...
Transport Layer Security - Web security
.0 and 1.1 support will be removed from all major browsers in q1 2020. you'll need to make sure your web server supports tls 1.2 or 1.3 going forward. from version 74 onwards, firefox will return a secure connection failed error when connecting to servers using the older tls versions (bug 1606734). tls handshake timeout values if the tls handshake starts to become slow or unresponsive for some reason, the user's experience can be affected significantly. to mitigate this problem, modern browsers have implemented handshake timeouts: since version 58, firefox implements a tls handshake timeout with a default value of 30 seconds. the timeout value can be varied by editing the network.http.tls-handshake-timeout pref in about:config. ...
Web security
on these pages will be blocked by default. consequently, your website may appear broken to users (if iframes or plugins don't load, etc.). passive mixed content is displayed by default, but users can set a preference to block this type of content, as well. this page explains what you should be aware of as a web developer. secure contexts a secure context is a window or worker for which there is reasonable confidence that the content has been delivered securely (via https/tls), and for which the potential for communication with contexts that are not secure is limited. many web apis and features are accessible only in a secure context. the primary goal of secure contexts is to prevent man-in-the-middle attackers from accessing powerful apis that could further compromise the victim of an attack. ...
XPath
ead of relying on the document.getelementbyid() or parentnode.queryselectorall() methods, the node.childnodes properties, and other dom core features. xpath uses a path notation (as in urls) for navigating through the hierarchical structure of an xml document. it uses a non-xml syntax so that it can be used in uris and xml attribute values. note: support for xpath varies widely; it's supported reasonably well in firefox (although there are no plans to improve support further), while other browsers implement it to a lesser extent, if at all. if you need a polyfill, you may consider js-xpath or wicked-good-xpath. documentation introduction to using xpath in javascript describes a non-xslt use of xpath. xpath:axes list and definition of the axes defined in the xpath specification. axes...
WebAssembly Concepts - WebAssembly
ws and workers (via postmessage()). a module declares imports and exports just like an es2015module. memory: a resizable arraybuffer that contains the linear array of bytes read and written by webassembly’s low-level memory access instructions. table: a resizable typed array of references (e.g. to functions) that could not otherwise be stored as raw bytes in memory (for safety and portability reasons). instance: a module paired with all the state it uses at runtime including a memory, table, and set of imported values. an instance is like an es2015 module that has been loaded into a particular global with a particular set of imports. the javascript api provides developers with the ability to create modules, memories, tables, and instances. given a webassembly instance, javascript code can...
Understanding WebAssembly text format - WebAssembly
all instruction to achieve this, so we gave it call_indirect, which takes a dynamic function operand. the problem is that the only types we have to give operands in webassembly are (currently) i32/i64/f32/f64. webassembly could add an anyfunc type ("any" because the type could hold functions of any signature), but unfortunately this anyfunc type couldn’t be stored in linear memory for security reasons. linear memory exposes the raw contents of stored values as bytes and this would allow wasm content to arbitrarily observe and corrupt raw function addresses, which is something that cannot be allowed on the web. the solution was to store function references in a table and pass around table indices instead, which are just i32 values. call_indirect’s operand can therefore simply be an i32 inde...