Search completed in 1.10 seconds.
755 results for "finish":
Your results are loading. Please wait...
Animation.onfinish - Web APIs
the animation interface's onfinish property (from the web animations api) is the event handler for the finish event. this event is sent when the animation finishes playing. the finish event occurs when the animation completes naturally, as well as when the animation.finish() method is called to immediately cause the animation to finish up. the "paused" play state supersedes the "finished" play state; if the animation is both paused and finished, the "paused" state is the one that will be reported. you can force the animation into the "finished" state by setting its starttime to document.timeline.currenttime - (animation.currenttime * animation.playbackrate). ...
...is called to immediately cause the animation to finish up. the "paused" play state supersedes the "finished" play state; if the animation is both paused and finished, the "paused" state is the one that will be reported. you can force the animation into the "finished" state by setting its starttime to document.timeline.currenttime - (animation.currenttime * animation.playbackrate). syntax var finishhandler = animation.onfinish; animation.onfinish = finishhandler; value a function to be called to handle the finish event, or null if no finish event handler is set. examples animation.onfinish is used several times in the alice in web animations api land growing/shrinking alice game. here is one instance where we add pointer events back to an element after its opacity animation has faded it...
... working draft editor's draft. ...
...e said animation's credits bringui.pause(); // this function removes pointer events on the credits. hide(endingui); // when the credits are later faded in, // we re-add the pointer events when they're done bringui.onfinish = function() { endingui.style.pointerevents = 'auto'; }; specifications specification status comment web animationsthe definition of 'animation.onfinish' in that specification. working draft editor's draft. ...
Animation.finish() - Web APIs
Web › API › Animation › finish
the finish() method of the web animations api's animation interface sets the current playback time to the end of the animation corresponding to the current playback direction. that is, if the animation is playing forward, it sets the playback time to the length of the animation sequence, and if the animation is playing in reverse (having had its reverse() method called), it sets the playback time to 0. syntax animation.finish(); parameters none. return value none. exceptions invalidstate the player's playback rate is 0 or the animation's playback rate is greater than 0 and the end time of the animation is infinity. examples the following example shows how to use the finish() method and catch an invalidstate error. interfaceelement.addeventlistener("mousedown", function() ...
...on.finish(); parameters none. return value none. exceptions invalidstate the player's playback rate is 0 or the animation's playback rate is greater than 0 and the end time of the animation is infinity. examples the following example shows how to use the finish() method and catch an invalidstate error. interfaceelement.addeventlistener("mousedown", function() { try { player.finish(); } catch(e if e instanceof invalidstate) { console.log("finish() called on paused or finished animation."); } catch(e); logmyerrors(e); //pass exception object to error handler } }); the following example finishes all the animations on a single element, regardless of their direction of playback. ...
...er.finish(); } catch(e if e instanceof invalidstate) { console.log("finish() called on paused or finished animation."); } catch(e); logmyerrors(e); //pass exception object to error handler } }); the following example finishes all the animations on a single element, regardless of their direction of playback. elem.getanimations().foreach( function(animation){ return animation.finish(); } ); specifications specification status comment web animationsthe definition of 'finish()' in that specification. working draft ...
Finishing up - Game development
« previous this is the 10th and final step of the gamedev canvas tutorial. you can find the source code as it should look after completing this lesson at gamedev-canvas-workshop/lesson10.html. there's always room for improvements in any game we write. for example, we can offer more than one life to the player. they could make a mistake or two and still be able to finish the game. we could also improve our code rendering. giving the player some lives implementing lives is quite straightforward. let's first add a variable to store the number of lives in the same place where we declared our other variables: var lives = 3; drawing the life counter looks almost the same as drawing the score counter — add the following function to your code, below the drawscore() function: functio...
...ck to the browser. it will sync the framerate accordingly and render the shapes only when needed. this produces a more efficient, smoother animation loop than the older setinterval() method. compare your code that's all — the final version of the game is ready and set to go ! exercise: change the number of lives and the angle the ball bounces off the paddle. game over - for now! you've finished all the lessons - congratulations! by this point, you should now know the basics of canvas manipulation and the logic behind simple 2d games. now it's a good time to learn some frameworks and continue game development. you can check out this series' counterpart, 2d breakout game using phaser or the cyber orb built in phaser tutorial. you can also look through the games section on mdn for inspir...
NS_CStringContainerFinish
history this function was finalized for mozilla 1.7. see bug 239123 for details. ...
... history this function was finalized for mozilla 1.7. see bug 239123 for details. ...
NS_StringContainerFinish
return values this function does not return a value. example code see ns_stringcontainerinit for an example. history this function was frozen for mozilla 1.7. see bug 239123 for details. ...
... return values this function does not return a value. example code see ns_stringcontainerinit for an example. history this function was frozen for mozilla 1.7. see bug 239123 for details. ...
Animation.finished - Web APIs
the animation.finished read-only property of the web animations api returns a promise which resolves once the animation has finished playing. every time the animation leaves the finished play state (that is, when it starts playing again), a new promise is created for this property. the new promise will resolve once the new animation sequence has completed. syntax var animationspromise = animation.finished; value a promise object which will resolve once the animation has finished running. ...
...ay state (that is, when it starts playing again), a new promise is created for this property. the new promise will resolve once the new animation sequence has completed. syntax var animationspromise = animation.finished; value a promise object which will resolve once the animation has finished running. examples the following code waits until all animations running on the element elem have finished, then deletes the element from the dom tree: promise.all( elem.getanimations().map( function(animation) { return animation.finished } ) ).then( function() { return elem.remove(); } ); specifications specification status comment web animationsthe definition of 'animation.finished' in that specification. working draft editor's draft. ...
JS_Finish
obsolete since jsapi 19this 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. same function as js_destroyruntime. syntax void js_finish(jsruntime *rt); name type description rt jsruntime * pointer to a js runtime to destroy. description js_finish is obsolete. use js_destroyruntime instead. see also js_destroyruntime bug 805080 ...
Finishing the Component
interface provides a means to obtain * global services in an application. the service manager depends * on the repository to find and instantiate factories to obtain * services. * * users of the service manager must first obtain a pointer to the * global service manager by calling ns_getservicemanager. after that, * they can request specific services by calling getservice. * when they are finished they can ns_release() the service as usual. * * a user of a service may keep references to particular services * indefinitely and only must call release when it shuts down. * * @status frozen */ these frozen interfaces and functions are part of the gecko sdk. the rule of thumb is that interfaces outside of the sdk are considered "experimental" or unfrozen. see the following sidebar for ...
WebGLRenderingContext.finish() - Web APIs
the webglrenderingcontext.finish() method of the webgl api blocks execution until all previously called commands are finished. syntax void gl.finish(); parameters none. return value none. specifications specification status comment webgl 1.0the definition of 'finish' in that specification. recommendation initial definition. opengl es 2.0the definition of 'glfinish' in that specification. standard man page of the opengl api. ...
Index - Web APIs
Web › API › Index
r paused. 66 animation.effect api, animation, experimental, property, reference, web animations, effect, web animations api the animation.effect property of the web animations api gets and sets the target effect of an animation. the target effect may be either an effect object of a type based on animationeffectreadonly, such as keyframeeffect, or null. ...
...tion.effect api, animation, experimental, property, reference, web animations, effect, web animations api the animation.effect property of the web animations api gets and sets the target effect of an animation. the target effect may be either an effect object of a type based on animationeffectreadonly, such as keyframeeffect, or null. ...
... web animations api the animation.effect property of the web animations api gets and sets the target effect of an animation. the target effect may be either an effect object of a type based on animationeffectreadonly, such as keyframeeffect, or null. ...
...And 35 more matches
Download
ay not be known before the download is started. hasprogress read only boolean indicates whether this download's progress property is able to report partial progress while the download proceeds, and whether the value in totalbytes is relevant. this depends on the saver and the download source. launchwhensucceeded boolean if this property is true when the download finishes successfully, the target file will be opened or executed automatically. launcherpath string local file path of the application to be used to launch the target file, or null if the file should be launched with the default application associated with the contenttype property or the extension of the target file. onchange function this can be set to a function tha...
... time, or when a failed or canceled download is restarted. succeeded read only boolean this propery is true if the download has been completed successfully. target read only downloadtarget target of this download. totalbytes read only number when hasprogress is true, this indicates the total number of bytes to be transferred before the download finishes; this value can be zero if the file is empty. note: this property's value may not match the actual final size of the downloaded file if the download is encoded during the network transfer. you can use the downloadtarget.size property to get the actual size of the completely-downloaded file once the download has succeeded. when hasprogress is false, this property is always zero. ...
...s start() starts the download for the first time, or restarts a download that failed or has been canceled. calling this method when the download has been completed successfully has no effect, and the method returns a resolved promise. if the download is in progress, the method returns the same promise as the previous call. ...
...And 8 more matches
Drawing graphics - Learn web development
image using html attributes or dom properties, as explained above. you could use css, but the trouble then is that the sizing is done after the canvas has rendered, and just like any other image (the rendered canvas is just an image), the image could become pixellated/distorted. getting the canvas context and final setup we need to do one final thing before we can consider our canvas template finished. to draw onto the canvas we need to get a special reference to the drawing area called a context. this is done using the htmlcanvaselement.getcontext() method, which for basic usage takes a single string as a parameter representing the type of context you want to retrieve. in this case we want a 2d canvas, so add the following javascript line below the others inside the <script> element: cons...
...lt width of strokes is 1 pixel; you can adjust the linewidth property value to change this (it takes a number representing the number of pixels wide the stroke is). add the following line in between the previous two lines: ctx.linewidth = 5; now you should see that your white outline has become much thicker! that's it for now. at this point your example should look like this: note: the finished code is available on github as 2_canvas_rectangles.html. drawing paths if you want to draw anything more complex than a rectangle, you need to draw a path. basically, this involves writing code to specify exactly what path the pen should move along on your canvas to trace the shape you want to draw. canvas includes functions for drawing straight lines, circles, bézier curves, and more. let...
...code, you'd get just an edge of the circle chopped off between the start and end point of the arc. this illustrates another important point of the canvas — if you try to fill an incomplete path (i.e. one that is not closed), the browser fills in a straight line between the start and end point and then fills it in. that's it for now; your final example should look like this: note: the finished code is available on github as 3_canvas_paths.html. note: to find out more about advanced path drawing features such as bézier curves, check out our drawing shapes with canvas tutorial. text canvas also has features for drawing text. let's explore these briefly. start by making another fresh copy of our canvas template (1_canvas_template.html) in which to draw the new example. text is d...
...And 6 more matches
2D maze game with device orientation - Game development
which updates things such as the ball position. ball.game = function(game) {}; ball.game.prototype = { create: function() {}, initlevels: function() {}, showlevel: function(level) {}, updatecounter: function() {}, managepause: function() {}, manageaudio: function() {}, update: function() {}, wallcollision: function() {}, handleorientation: function(e) {}, finishlevel: function() {} }; the create and update functions are framework-specific, while others will be our own creations: initlevels initializes the level data. showlevel prints the level data on the screen. updatecounter updates the time spent playing each level and records the total time spent playing the game.. managepause pauses and resumes the game. manageaudio turns the audio on and of...
...ds the total time spent playing the game.. managepause pauses and resumes the game. manageaudio turns the audio on and off. wallcollision is executed when the ball hits the walls or other objects. handleorientation is the function bound to the event responsible for the device orientation api, providing the motion controls when the game is running on a mobile device with appropriate hardware. finishlevel loads a new level when the current level is completed, or finished the game if the final level is completed. adding the ball and its motion mechanics first, let’s go to the create() function, initialize the ball object itself and assign a few properties to it: this.ball = this.add.sprite(this.ballstartpos.x, this.ballstartpos.y, 'ball'); this.ball.anchor.set(0.5); this.physics.enable(t...
...mplete updatecounter function looks: updatecounter: function() { this.timer++; this.timertext.settext("time: "+this.timer); this.totaltimetext.settext("total time: "+(this.totaltimer+this.timer)); }, as you can see we’re incrementing the this.timer variable and updating the content of the text objects with the current values on each iteration, so the player sees the elapsed time. ...
...And 5 more matches
NSS functions
ertextension mxr 3.4 and later cert_findcertissuer mxr 3.3 and later cert_findkeyusageextension mxr 3.4 and later cert_findsmimeprofile mxr 3.2 and later cert_findsubjectkeyidextension mxr 3.7 and later cert_findusercertbyusage mxr 3.4 and later cert_findusercertsbyusage mxr 3.4 and later cert_finishcertificaterequestattributes mxr 3.10 and later cert_finishextensions mxr 3.5 and later cert_formatname mxr 3.2 and later cert_freedistnames mxr 3.2 and later cert_freenicknames mxr 3.2 and later cert_getavatag mxr 3.2 and later cert_getcertchainfromcert mxr 3.4 and later cert_getcertemailaddre...
... 3.4 and later sec_asn1decodeinteger mxr 3.2 and later sec_asn1decodeitem mxr 3.2 and later sec_asn1decoderabort mxr 3.9 and later sec_asn1decoderclearfilterproc mxr 3.2 and later sec_asn1decoderclearnotifyproc mxr 3.2 and later sec_asn1decoderfinish mxr 3.2 and later sec_asn1decodersetfilterproc mxr 3.2 and later sec_asn1decodersetnotifyproc mxr 3.2 and later sec_asn1decoderstart mxr 3.2 and later sec_asn1decoderupdate mxr 3.2 and later sec_asn1encode mxr 3.2 and later sec_asn...
...later sec_asn1encodeitem mxr 3.2 and later sec_asn1encoderabort mxr 3.9 and later sec_asn1encoderclearnotifyproc mxr 3.2 and later sec_asn1encoderclearstreaming mxr 3.2 and later sec_asn1encodercleartakefrombuf mxr 3.2 and later sec_asn1encoderfinish mxr 3.2 and later sec_asn1encodersetnotifyproc mxr 3.2 and later sec_asn1encodersetstreaming mxr 3.2 and later sec_asn1encodersettakefrombuf mxr 3.2 and later sec_asn1encoderstart mxr 3.2 and later sec_asn1encoderupdate mxr 3.2 and later ...
...And 5 more matches
Event reference
ts used internally by specific browsers; for example, mozilla-specific events are listed so that add-ons can use them to interact with the browser. most common categories resource events event name fired when error a resource failed to load. abort the loading of a resource has been aborted. load a resource and its dependent resources have finished loading. beforeunload the window, the document and its resources are about to be unloaded. unload the document or a dependent resource is being unloaded. network events event name fired when online the browser has gained access to the network. offline the browser has lost access to the network. focus events ...
...minated. durationchange the duration attribute has been updated. emptied the media has become empty; for example, this event is sent if the media has already been loaded (or partially loaded), and the load() method is called to reload it. ended playback has stopped because the end of the media was reached. loadeddata the first frame of the media has finished loading. loadedmetadata the metadata has been loaded. pause playback has been paused. play playback has begun. playing playback is ready to start after having been paused or delayed due to lack of data. ratechange the playback rate has changed. seeked a seek operation completed. seeking a seek operation began. ...
...on has started. appinstalled event web app manifest a web application is successfully installed as a progressive web app. audioprocess audioprocessingevent web audio apithe definition of 'audioprocess' in that specification. the input buffer of a scriptprocessornode is ready to be processed. audioend event web speech api the user agent has finished capturing audio for speech recognition. audiostart event web speech api the user agent has started to capture audio for speech recognition. beforeprint event html5 the associated document is about to be printed or previewed for printing. beforeunload beforeunloadevent html5 the window, the document and its resources are about to be unloade...
...And 5 more matches
General asynchronous programming concepts - Learn web development
le 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. ...
...ait for the other function to finish and return, and until that happens, the entire program is essentially stopped from the perspective of the user. mac users, for example, sometimes experience this as the spinning rainbow-colored cursor (or "beachball" as it is often called). this cursor is how the operating system says "the current program you're using has had to stop and wait for something to finish up, and it's taking so long that i was worried you'd wonder what was going on." this is a frustrating experience and isn't a good use of computer processing power — especially in an era in which computers have multiple processor cores available. there's no sense sitting there waiting for something when you could let the other task chug along on another processor core and let you know when it...
... note: the previous example is very unrealistic. you would never calculate 10 million dates on a real web app! it does, however, serve to give you the basic idea. in our second example, simple-sync-...
...And 4 more matches
Application cache implementation overview
rom the manifest content we download from the server to be compared to existing md5 (in case of an “update”). during the load, manifest is parsed according the “parsing the cache manifest” html5 spec, and lists of entries and namespaces are collected. after the manifest fetch is done, nsofflinecacheupdate::loadcompleted() is called. nsofflinecacheupdate::loadcompleted() is called for each finished entry load, including the manifest and is the main place handling each update state as following: on checking state, a state the update is at after manifest parsing has been done, loadcompleted checks whether the new hash, i.e. the manifest content, differs or this is just “first download”. if so, the update switches to downloading state and fetches in parallel items listed in the m...
...te the update is at after manifest parsing has been done, loadcompleted checks whether the new hash, i.e. the manifest content, differs or this is just “first download”. if so, the update switches to downloading state and fetches in parallel items listed in the manifest by call to nsofflinecacheupdate::processnexturi(). if the new hash is identical, update invokes onnoupdate event and is 'finished'. then it associates any documents waiting for this update to finish with the current existing nsiapplicationcache. if the manifest load failed, onerror event is invoked and the update 'finishes'. the parallel load is implemented by asynchronous recursive calls to processnexturi(), a method searching always a single entry that is scheduled to load. when found, channel is open for it (+o...
...ped. from now on processnexturi can only be called from loadcompleted() again. note: the processnexturi method early returns when state of the update is different then downloading. on downloading state loadcompleted checks whether load of the item succeeded. if so, its marked as valid in the new cache version and processnexturi() is called. otherwise, the update invokes onerror and 'finishes'. when processnexturi discovers there are no more items to download it starts a “manifest check” implemented by nsmanifestcheck. nsmanifestcheck downloads the manifest from the server one more time and checks its content has not changed again. the results is passed to the original update via manifestcheckcompleted method. when the manifest is identical, t...
...And 4 more matches
Legacy layout methods - Learn web development
} .col.span8 { width: 620px; } .col.span9 { width: 700px; } .col.span10 { width: 780px; } .col.span11 { width: 860px; } .col.span12 { width: 940px; } with these classes created we can now lay out different width columns on the grid. try saving and loading the page in your browser to see the effects. note: if you are having trouble getting the above example to work, try comparing it against our finished version on github (see it running live also). try modifying the classes on your elements or even adding and removing some containers, to see how you can vary the layout. for example, you could make the second row look like this: <div class="row"> <div class="col span8">13</div> <div class="col span4">14</div> </div> now you've got a grid system working, you can simply define the rows an...
... our css we can replace the 60 pixel column width with 6.25%. we need to do the same with our gutter width: 20 / 960 = 0.02083333333 so we need to replace the 20 pixel margin-left on our .col rule and the 20 pixel padding-right on .wrapper with 2.08333333%. updating our grid to get started in this section, make a new copy of your previous example page, or make a local copy of our simple-grid-finished.html code to use as a starting point. update the second css rule (with the .wrapper selector) as follows: body { width: 90%; max-width: 980px; margin: 0 auto; } .wrapper { padding-right: 2.08333333%; } not only have we given it a percentage width, we have also added a max-width property in order to stop the layout becoming too wide. next, update the fourth css rule (with the .col s...
... 64.58333331%; } .col.span9 { width: 72.91666664%; } .col.span10 { width: 81.24999997%; } .col.span11 { width: 89.5833333%; } .col.span12 { width: 97.91666663%; } now save your code, load it in a browser, and try changing the viewport width — you should see the column widths adjust nicely to suit. note: if you are having trouble getting the above example to work, try comparing it against our finished version on github (see it running live also). easier calculations using the calc() function you could use the calc() function to do the math right inside your css — this allows you to insert simple mathematical equations into your css values, to calculate what a value should be. it is especially useful when there is complex math to be done, and you can even compute a calculation that uses ...
...And 3 more matches
Introducing asynchronous JavaScript - Learn web development
nything else to it. there are two main types of asynchronous code style you'll come across in javascript code, old-style callbacks and newer promise-style code. in the below sections we'll review each of these in turn. async callbacks async callbacks are functions that are specified as arguments when calling a function which will start executing code in the background. when the background code finishes running, it calls the callback function to let you know the work is done, or to let you know that something of interest has happened. using callbacks is slightly old-fashioned now, but you'll still see them in use in a number of older-but-still-commonly-used apis. an example of an async callback is the second parameter of the addeventlistener() method (as we saw in action above): btn.addevent...
... display the url in, appending it to the document's <body>. however, we then create a loadasset() function that takes a callback as a parameter, along with a url to fetch and a content type. it uses xmlhttprequest (often abbreviated to "xhr") to fetch the resource at the given url, then pass the response to the callback to do something with. in this case the callback is waiting on the xhr call to finish downloading the resource (using the onload event handler) before it passes it to the callback. callbacks are versatile — not only do they allow you to control the order in which functions are run and what data is passed between them, they also allow you to pass data to different functions depending on circumstance. so you could have different actions to run on the response downloaded, such as ...
...) api, which is basically like a modern, more efficient version of xmlhttprequest. let's look at a quick example, from our fetching data from the server article: fetch('products.json').then(function(response) { return response.json(); }).then(function(json) { products = json; initialize(); }).catch(function(err) { console.log('fetch problem: ' + err.message); }); note: you can find the finished version on github (see the source here, and also see it running live). here we see fetch() taking a single parameter — the url of a resource you want to fetch from the network — and returning a promise. the promise is an object representing the completion or failure of the async operation. it represents an intermediate state, as it were. in essence, it's the browser's way of saying "i pro...
...And 3 more matches
Browser chrome tests
rome tests. this file will be injected into the test scope for each test living in the same folder. notice that any function call in head.js main scope will run before the main test() method. asynchronous tests when writing async tests, you can use the add_task method with promises. the test suite also supports asynchronous tests, using the same function names as mochitest. ...
... notice that any function call in head.js main scope will run before the main test() method. asynchronous tests when writing async tests, you can use the add_task method with promises. the test suite also supports asynchronous tests, using the same function names as mochitest. call waitforexplicitfinish() from test() if you want to delay reporting a result until after test() has returned. call finish() once the test is complete. ...
...ite also supports asynchronous tests, using the same function names as mochitest. call waitforexplicitfinish() from test() if you want to delay reporting a result until after test() has returned. call finish() once the test is complete. be aware that the test harness will mark tests that take too long to complete as failed (the current timeout is 30 seconds). function test() { waitforexplicitfinish(); settimeout(completetest, 1000); } function completetest() { ok(true, "timeout ran"); finish(); } if your test is randomly timing out and you think that's just due to it taking too long, you can extend the timeout. be aware that this is not a solution; you should investigate why your test is taking so long, since it's most likely due to a bad test design or a performance problem.
...And 3 more matches
sslfnc.html
messages in ssl2-compatible format. if set to pr_true, it will; otherwise, it will not. factory setting is on (pr_true). see the description below for more information on this option. ssl_no_cache disallows use of the session cache. factory setting is off. if you turn this option on, this socket will be unable to resume a session begun by another socket. when this socket's session is finished, no other socket will be able to resume the session begun by this socket. ssl_rollback_detection disables detection of a rollback attack. factory setting is on. you must turn this option off to interoperate with tls clients ( such as certain versions of microsoft internet explorer) that do not conform to the tls specification regarding rollback attacks. important: turning this opt...
...ether or not to send ssl3 client hello messages in ssl2-compatible format. if set to pr_true, it will; otherwise, it will not. see the description below for more information on this option. ssl_no_cache disallows use of the session cache. factory setting is off. if you turn this option on, this socket will be unable to resume a session begun by another socket. when this socket's session is finished, no other socket will be able to resume the session begun by this socket. ssl_rollback_detection disables detection of a rollback attack. factory setting is on. you must turn this option off to interoperate with tls clients ( such as certain versions of microsoft internet explorer) that do not conform to the tls specification regarding rollback attacks. important: turning this option off...
...cate." returns the function returns one of these values: if successful, secsuccess. if unsuccessful, secfailure. use pr_geterror to obtain the error code. description the ssl_securitystatus function fills in values only if you supply pointers to values of the appropriate type. pointers passed can be null, in which case the function does not supply values. when you are finished with them, you should free all the returned values using pr_free. ssl_getsessionid returns a secitem structure containing the ssl session id associated with a file descriptor. syntax #include "ssl.h" secitem *ssl_getsessionid(prfiledesc *fd); parameter this function has the following parameter: fd a pointer to the file descriptor for the ssl sock...
...And 3 more matches
Observer Notifications
xpcom-will-shutdown called just before xpcom-shutdown. observer must not spin event loop. xpcom-shutdown assortment of critical services stop operating. many things will not be available here. web-workers-shutdown called inside xpcom-shutdown. this shuts down all web workers. xpcom-shutdown-threads shuts down the thread manager, causing all nsthreads to finish processing any events already queued and stop accepting new events. browser these topics indicate interesting things that happen that the browser alerts you to. topic description browser:purge-session-history sent when the sanitizer runs to purge all history and other information. browser:purge-domain-data sent after domain-specific history and other i...
...ferences. the data value is an nsisupportsprbool. recipients may set this to true to abort the close. browser-lastwindow-close-granted sent when all interested parties have responded to the browser-lastwindow-close-requested notification and none of them requested that the close be aborted. after this is sent and handled, the browser window will close. browser-delayed-startup-finished sent when the browser window and all its components have been loaded and initialized. documents these topics indicate notifications you can monitor related to dom documents. topic subject data description chrome-document-global-created nsidomwindow null sent immediately after a chrome document window has been set up, but before any script code has...
... the response header of any network request. this notification will come only after the "http-on-examine-response" is fired, but it will not always appear. download manager these topics indicate that events related to the download manager have occurred. topic description download-manager-ui-done called when the list of downloads in the download manager windows finishes updating. this can happen multiple times, such as when the window first opens, when multiple items are removed, and when entering private browsing mode. download-manager-remove-download called when a download of the list is removed or all the list is cleared. the subject will be the download id wrapped in nsisupportspruint32, for one download removed, or null for multi download rem...
...And 3 more matches
Using the Web Animations API - Web APIs
use, unlike css animations where the default animation-timing-function is ease, in the web animations api the default easing is linear — which is what we want here. bring the pieces together now it’s time to bring them both together with the element.animate() method: document.getelementbyid("alice").animate( alicetumbling, alicetiming ) and boom: the animation starts playing (see the finished version on codepen). the animate() method can be called on any dom element that could be animated with css. and it can be written in several ways. instead of making objects for keyframes and timing properties, we could just pass their values in directly, like so: document.getelementbyid("alice").animate( [ { transform: 'rotate(0) translate3d(-50%, -50%, 0)', color: '#000' }, { color...
... animation.cancel() aborts the animation and removes its effects. animation.reverse() sets the animation’s playback rate (animation.playbackrate) to a negative value so it runs backward. let’s take a look at playbackrate first — a negative playbackrate will cause an animation to run in reverse. when alice drinks from the bottle, she grows smaller. thi...
...eight >= .666) { // alice got bigger! ... } else { // alice didn't change significantly ... } } note: getanimations() and effect are not shipping in all browsers as of this writing, but the polyfill does support them today. ...
...And 3 more matches
Test your skills: Selectors - Learn web development
n the tasks. if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page. selectors one without changing the html, use css to do the following things: make h1 headings blue. give h2 headings a blue background and white text. cause text wrapped in a span to have a font-size of 200%. try updating the live code below to recreate the finished example: for assessment or further work purposes, download the starting point for this task to work in your own editor or in an online editor. selectors two without changing the html, make the following changes to the look of the content in this example: give the element with an id of special a yellow background. give the element with a class of alert a 1px grey border. if the eleme...
...es to the look of the content in this example: give the element with an id of special a yellow background. give the element with a class of alert a 1px grey border. if the element with a class of alert also has a class of stop, make the background red. if the element with a class of alert also has a class of go, make the background green. try updating the live code below to recreate the finished example: for assessment or further work purposes, download the starting point for this task to work in your own editor or in an online editor. selectors three in this example, try making the following changes without adding to the html. style links, making the link-state orange, visited links green, and remove the underline on hover. make the first element inside the container font-s...
...g to the html. style links, making the link-state orange, visited links green, and remove the underline on hover. make the first element inside the container font-size: 150% and the first line of that element red. stripe every other row in the table by selecting these rows and giving them a background color of #333 and foreground of white. try updating the live code below to recreate the finished example: for assessment or further work purposes, download the starting point for this task to work in your own editor or in an online editor. selectors four in this task try the following: make any paragraph that directly follows an h2 element red. remove the bullets and add a 1px grey bottom border only to list items that are a direct child of the ul with a class of list. try u...
...And 2 more matches
Understanding client-side JavaScript frameworks - Learn web development
oviding an enjoyable developer experience. this article will explore the main features of “the big 4” frameworks, looking at how frameworks tend to work from a high level and the differences between them. react tutorials note: react tutorials last tested in may 2020, with react/reactdom 16.13.1 and create-react-app 3.4.1. if you need to check your code against our version, you can find a finished version of the sample react app code in our todo-react repository. for a running live version, see https://mdn.github.io/todo-react-build/. 1. getting started with react in this article we will say hello to react. we'll discover a little bit of detail about its background and use cases, set up a basic react toolchain on our local computer, and create and play with a simple starter app, lea...
...ents and state with our component plan worked out, it's now time to start updating our app from a completely static ui to one that actually allows us to interact and change things. in this article we'll do this, digging into events and state along the way. 5. react interactivity: editing, filtering, conditional rendering as we near the end of our react journey (for now at least), we'll add the finishing touches to the main areas of functionality in our todo list app. this includes allowing you to edit existing tasks and filtering the list of tasks between all, completed, and incomplete tasks. we'll look at conditional ui rendering along the way. 6. accessibility in react in our final tutorial article, we'll focus on (pun intended) accessibility, including focus management in react, which ca...
...hich can improve usability and reduce confusion for both keyboard-only and screen reader users. 7. react resources our final article provides you with a list of react resources that you can use to go further in your learning. ember tutorials note: ember tutorials last tested in may 2020, with ember/ember cli version 3.18.0. if you need to check your code against our version, you can find a finished version of the sample ember app code in the ember-todomvc-tutorial repository. for a running live version, see https://nullvoxpopuli.github.io/ember-todomvc-tutorial/ (this also includes a few additional features not covered in the tutorial). 1. getting started with ember in our first ember article we will look at how ember works and what it's useful for, install the ember toolchain locall...
...And 2 more matches
Handling common JavaScript problems - Learn web development
n windows/linux) and choose the install option in the left-hand menu. in the search packages text field, type "jslint" and press enter/return to search for linting-related packages. you should see a package called lint at the top of the list. install this first (using the install button), as other linters rely on it to work. after that, install the linter-jshint plugin. after the packages have finished installing, try loading up a javascript file: you'll see any issues highlighted with green (for warnings) and red (for errors) circles next to the line numbers, and a separate panel at the bottom provides line numbers, error messages, and sometimes suggested values or other fixes. other popular editors have similar linting packages available. for example, see the "plugins for text editors and...
...your scripts into a single file using a solution like browserify. in general, reducing the number of http requests is very good for performance. make your files even smaller by minifying them before you load them onto your production server. minifying squashes all the code together onto a huge single line, making it take up far less file size. it is ugly, but you don't need to read it when it is finished! this is best done using a minification tool like uglify (there's also an online version — see jscompress.com) when using apis, make sure you turn off the api features when they are not being used; some api calls can be really expensive on processing power. for example, when showing a video stream, make sure it is turned off when you can't see it. when tracking a device's location using repe...
... note: again, there are many different ways to make use of the different polyfills you will encounter — consult each polyfill's individual documentation. one thing you might be thinking is "why should we always load the polyfill code, even if we don't need it?" this is a good point — as your sites get more complex and y...
...And 2 more matches
Creating reftest-based unit tests
ochitest/tests/simpletest/windowsnapshot.js. register them in the chrome package in layout/tools/reftest/jar.mn, and reference the chrome uris in the manifest file (see an example). testing invalidation testing that a document displays correctly once it has loaded is only one part of testing rendering. another part is testing invalidation - testing that when a document is changed after it has finished loading and displaying, that the browser correctly "invalidates" the parts of the screen that should change so that the screen displays the correct output the next time it is repainted. invalidation tests check both that the internal state of the document has been updated correctly, and that the browser then correctly invalidates and repaints the appropriate parts of the screen. in order to te...
... screen that should change so that the screen displays the correct output the next time it is repainted. invalidation tests check both that the internal state of the document has been updated correctly, and that the browser then correctly invalidates and repaints the appropriate parts of the screen. in order to test invalidation it is important that invalidation tests let the document completely finish loading and displaying before making the changes for which invalidation and repainting is to be tested. making the changes before the document has completely finished loading and painting would mean that the test may not actually test the browser's invalidation logic, since the changed parts of the document may end up displaying correctly purely due to a pending post-load paint. to write an inva...
...an that the test may not actually test the browser's invalidation logic, since the changed parts of the document may end up displaying correctly purely due to a pending post-load paint. to write an invalidation reftest requires three extra steps. first you need to add class="reftest-wait" to the root element in the test to tell the reftest framework not to check the rendering as 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 'mo...
...And 2 more matches
Eclipse CDT Manual Setup
ont size. creating an eclipse project to create an eclipse project for your mozilla source tree, select "file > new > makefile project with existing code". in the "import existing code" window that opens, enter a meaningful project name that identifies your mozilla source tree, set the code location to the root of your source tree, select an appropriate toolchain (e.g., "macosx gcc"), and click finish. the status bar at the bottom right of the window should now show that eclipse is "refreshing the workspace" (gathering a list of all the files in the source tree). click on the little green button beside this message to open the "progress" tab, and keep an eye on the "refreshing workspace" item as you continue with the steps below. (if an "indexing" item starts after the "refreshing the workspa...
... bar at the bottom right of the window should now show that eclipse is "refreshing the workspace" (gathering a list of all the files in the source tree). click on the little green button beside this message to open the "progress" tab, and keep an eye on the "refreshing workspace" item as you continue with the steps below. (if an "indexing" item starts after the "refreshing the workspace" item has finished, click the little red box beside that item to cancel it, since we want to configure the project before the indexer runs.) initial project properties so that the indexer will run faster and give better results, and so that eclipse doesn't give results for irrelevant files, you should add some resource filters to have eclipse ignore certain non-source files and directories. note, you must not m...
...egular expression as necessary. add a recursive, regular expression "exclude all" filter for files with name matching "\.(?:rej|orig|o|pp|swp)$" to exclude .rej, .orig, .pp, .o, and .swp files. add "exclude all" filters for any other non-source directories that you've added to your source tree (e.g., xcode or msvc project directories). click ok to close the filters window, wait for eclipse to finish processing your resource filters, then make sure the filtered directories and files have disappeared from the project explorer tab on the left. also, if your main object directory is in your source tree, and not somewhere outside it, make sure that it has not disappeared from the project explorer tab. reopen the project properties window and select "c/c++ build" from the left of the project prop...
...And 2 more matches
DeferredTask.jsm
ostpone) task. void start(); flush obsolete since gecko 28 perform any postponed task immediately. void flush(); cancel obsolete since gecko 28 cancel any pending task. void cancel(); arm request the execution of the task after the delay specified on construction. multiple calls don't introduce further delays. if the task is running, the delay will start when the current execution finishes. the task will always be executed on a different tick of the event loop, even if the delay specified on construction is zero. multiple "arm" calls within the same tick of the event loop are guaranteed to result in a single execution of the task. by design, this method doesn't provide a way for the caller to detect when the next execution terminates, or collect a result. in fact, doing that wo...
...etion on shutdown. void arm(); disarm cancel any request for a delayed execution of the task, though the task itself cannot be canceled in case it is already running. this method stops any currently running timer, thus the delay will restart from its original value in case the "arm" method is called again. void disarm(); finalize ensure that any pending task is executed from start to finish, while preventing any attempt to arm the timer again. if the task is running and the timer is armed, then one last execution from start to finish will happen again, immediately after the current execution terminates; then the returned promise will be resolved. if the task is running and the timer is not armed, the returned promise will be resolved when the current execution terminates. if th...
... promise finalize(); example firefox 28 note this section describes about deferredtask.jsm in firefox 28.0 or higher. set up a function or an asynchronous task whose execution can be triggered after a defined delay. multiple attempts to run the task before the delay has passed are coalesced. the task cannot be re-entered while running, but can be executed again after a previous run finished. a common use case occurs when a data structure should be saved into a file every time the data changes, using asynchronous calls, and multiple changes to the data may happen within a short time: let savedeferredtask = new deferredtask(function* () { yield os.file.writeatomic(...); // any uncaught exception will be reported. }, 2000); // the task is ready, but will not be executed until ...
...And 2 more matches
Index
Mozilla › Tech › XPCOM › Index
o on unix). 104 creating the component code xpcom this chapter goes over the basic code required to handle the relationship between your component and xpcom. having the component found and registered properly is the goal of this first chapter of the tutorial. in the subsequent chapters, we can begin to work on the example weblock component functionality itself. 105 finishing the component xpcom at this point you have created most of the infrastructure of the component. the component will be recognized by xpcom and registered with the category manager so that it starts up when xpcom initializes. when the component starts up, it populates a list of urls read in from a file stored next to the gecko binary on the local system. 106 packaging webloc...
...mic "binding" of clsids will be required to use some higher-level services (tbd) to figure out the clsids they should use. the intent is that such services themselves be built on top of the new moziregistry interface. 201 mozirepresentativecolorcallback interfaces, interfaces:scriptable, places, xpcom api reference, xpcom interface reference will be called when color analysis finishes. 202 mozispellcheckingengine interfaces, interfaces:scriptable, spell check, xpcom interface reference this interface represents a spell checking engine. the built in hunspell engine has contract id "@mozilla.org/spellchecker/engine;1". extensions can use this interface to check spelling or provide its own spell checker to editors. 203 mozistorageaggregatefunctio...
...nment for scripts that are loaded into content frames using the nsiframescriptloader interface. it enables these scripts to receive messages from the chrome process and send messages back to the chrome process. 434 nsicontentpref preferences, xpcom no summary! 435 nsicontentprefcallback2 preferences, xpcom, xpcom interface reference called when the method finishes. this will be called exactly once for each method invocation, and afterward no other callback methods will be called. 436 nsicontentprefobserver interfaces, interfaces:scriptable, xpcom, xpcom api reference, xpcom interface reference called when a content preference is removed. 437 nsicontentprefservice interfaces, interfaces:scriptable, preferences, xpcom, x...
...And 2 more matches
nsICryptoHash
n of some data. you can, for example, calculate the sha256 hash of a file to determine if it contains the data you think it does. the hash algorithms supported are md2, md5, sha-1, sha-256, sha-384, and sha-512. ...
...ed in mozilla/security/nss/lib/cryptohi/hasht.h. constant value description md2 1 message digest algorithm 2 md5 2 message-digest algorithm 5 sha1 3 secure hash algorithm 1 sha256 4 secure hash algorithm 256 sha384 5 secure hash algorithm 384 sha512 6 secure hash algorithm 512 methods finish() completes the hash object and produces the actual hash data. note: this method may be called any time after " .. manch("init") .. " is called. this call resets the object. acstring finish( in prbool aascii ); parameters aascii if true then the returned value is a base-64 encoded string. if false, then the returned value is binary data. return value this method returns a hash of th...
...var s = array.from(hash, (c, i) => tohexstring(hash.charcodeat(i))).join(""); // s now contains your hash in hex this gives 5eb63bbbe01eeed093cb22bb8f5acdc3 for the hash value. this example, while simp...
...And 2 more matches
EffectTiming.fill - Web APIs
Web › API › EffectTiming › fill
n order to properly render an affected element when outside the animation's active interval (that is, when it's not actively animating). the default is "auto". "none" the animation's effects are only visible while the animation is iterating or its playhead is positioned over an iteration. the animation's effects are not visible when its playstate is pending with a delay, when its playstate is finished, or during its enddelay or delay. in other words, if the animation isn't in its active interval, the affected element is not visible. "forwards" the affected element will continue to be rendered in the state of the final animation framecontinue to be applied to the after the animation has completed playing, in spite of and during any enddelay or when its playstate is finished. "backwards" ...
...mation's effects should be reflected by the element(s) state prior to playing, in spite of and during any delay and pending playstate. "both" combining the effects of both forwards and backwards: the animation's effects should be reflected by the element(s) state prior to playing and retained after the animation has completed playing, in spite of and during any enddelay, delay and/or pending or finished playstate. "auto" if the animation effect the fill mode is being applied to is a keyframe effect (keyframeeffect or keyframeeffectreadonly), "auto" is equivalent to "none". otherwise, the result is "both". examples here are a few examples. fill mode: none html content the html is pretty simple. we have a <div> named "main" which is a container for the element we'll be animating, which i...
...ing the boxrotationkeyframes and boxrotationtiming objects to describe the animation that should occur. result below we see what the result looks like. notice how before the animation starts running, the box is upright, then upon clicking the "animate!" button, the box is instantly rotated 90° to the left (to correspond to the first keyframe in the animation sequence). then, when the animation finishes running, the box instantaneously leaps back to its original state and is upright once again. give it a try below! follow the white rabbit example in the follow the white rabbit example, the white rabbit's animation is formed by coupling a keyframeeffect with an animation object. the keyframeeffect takes an object of timing properties, which is where we pass in fill. forwards makes the rabb...
...And 2 more matches
RTCPeerConnection - Web APIs
also included is a list of any ice candidates that may already have been generated by the ice agent since the offer or answer represented by the description was first instantiated.currentremotedescription read only the read-only property rtcpeerconnection.currentremotedescription returns an rtcsessiondescription object describing the remote end of th...
...also included is a list of any ice candidates that may already have been generated by the ice agent since the offer or answer represented by the description was first instantiated.getdefaulticeservers() the getdefaulticeservers() method of the rtcpeerconnection interface returns an array of objects based on the rtciceserver dictionary, which indicat...
...rconnection.iceconnectionstate returns an enum of type rtciceconnectionstate which state of the ice agent associated with the rtcpeerconnection.icegatheringstate read only the read-only property rtcpeerconnection.icegatheringstate returns an enum of type rtcicegatheringstate that describes connection's ice gathering state. this lets you detect, for example, when collection of ice candidates has finished.localdescription read only the read-only property rtcpeerconnection.localdescription returns an rtcsessiondescription describing the session for the local end of the connection. if it has not yet been set, this is null.peeridentity read only the read-only rtcpeerconnection property peeridentity returns a javascript promise that resolves to an rtcidentityassertion which contains a domstring id...
...And 2 more matches
Using writable streams - Web APIs
at an early stage right now. only chrome currently has basic writable streams implemented. introducing an example in our dom-examples/streams repo you’ll find a simple writer example (see it live also). this takes a given message and writes it into a writable stream, displaying each chunk on the ui as it is written to the stream and also displaying the whole message on the ui when writing has finished. how writable streams work let’s look at 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...
...blestream is constructed. inside this method, you should include code that sets up the stream functionality, e.g. getting access to the underlying sink. 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 ...
...ved] " + result; list.appendchild(listitem); }, abort(err) { console.log("sink error:", err); } }, queuingstrategy); the write() method contains a promise including code that decodes each written chunk into a format that can be written to the ui. this is called when each chunk is actually written (see the next section). the close() method is called automatically when writing has finished — it prints the entire decoded result to the ui in one string. the abort() method simply prints an error to the console if the stream is aborted. writing to actually write content to the stream we call the sendmessage() function, passing it a message to be written and the stream to write to: sendmessage("hello, world.", writablestream); the sendmessage() definition looks like so: funct...
...And 2 more matches
Using DTMF with WebRTC - Web APIs
tcdtmfsender object you'll use for sending dtmf. from there, you can simply call rtcdtmfsender.insertdtmf() to enqueue dtmf signals to be sent on the track to the other peer. the rtcrtpsender will then send the tones to the other peer as packets alongside the track's audio data. each time a tone is sent, the rtcpeerconnection receives a tonechange event with a tone property specifying which tone finished playing, which is an opportunity to update interface elements, for example. when the tone buffer is empty, indicating that all the tones have been sent, a tonechange event with its tone property set to "" (an empty string) is delivered to the connection object. if you'd like to know more about how this works, read rfc 3550: rtp: a transport protocol for real-time applications and rfc 4733: rtp...
...e. instead, we'll focus on how to use dtmf within the context of an rtcpeerconnection by studying how an example works. simple example this simple example constructs two rtcpeerconnections, establishes a connection between them, then waits for the user to click a "dial" button. when the button is clicked, a dtmf string is sent over the connection using rtcdtmfsender.insertdtmf(). once the tones finish transmitting, the connection is closed. note: this example is obviously somewhat contrived, since normally the two rtcpeerconnection objects would exist on different devices, and signaling would be done over the network instead of it all being simply linked up inline as it is here. html the html for this example is very basic; there are only three elements of importance: an <audio> elemen...
...f getsenders() isn't available, we instead call rtcpeerconnection.createdtmfsender() to get the rtcdtmfsender object. although this method is obsolete, this example supports it as a fallback to let older browsers (and those not yet updated to support the current webrtc dtmf api) run the example. finally, we set the dtmf sender's ontonechange event handler so we get notified each time a dtmf tone finishes playing. you can find the log function at the bottom of the documentation. when a tone finishes playing each time a dtmf tone finishes playing, a tonechange event is delivered to callerpc. the event listener for these is implemented as the handletonechangeevent() function. function handletonechangeevent(event) { if (event.tone !== "") { log("tone played: " + event.tone); } else { ...
...And 2 more matches
Using CSS animations - CSS: Cascading Style Sheets
res the animation, keyframes use a <percentage> to indicate the time during the animation sequence at which they take place. 0% indicates the first moment of the animation sequence, while 100% indicates the final state of the animation. because these two times are so important, they have special aliases: from and to. both are optional. if from/0% or to/100% is not specified, the browser starts or finishes the animation using the computed values of all attributes. you can optionally include additional keyframes that describe intermediate steps between the start and end of the animation. examples note: some older browsers (pre-2017) may need prefixes; the live examples you can click to see in your browser include the -webkit prefixed syntax. making text slide across the browser window this si...
...put the element to be animated in a container, and set overflow:hidden on the container. p { animation-duration: 3s; animation-name: slidein; } @keyframes slidein { from { margin-left: 100%; width: 300%; } to { margin-left: 0%; width: 100%; } } in this example the style for the <p> element specifies that the animation should take 3 seconds to execute from start to finish, using the animation-duration property, and that the name of the @keyframes at-rule defining the keyframes for the animation sequence is named “slidein”. if we wanted any custom styling on the <p> element to appear in browsers that don’t support css animations, we would include it here as well; however, in this case we don’t want any custom styling other than the animation effect. the k...
...he containing element), and the width of the element to be 300% (or three times the width of the containing element). this causes the first frame of the animation to have the header drawn off the right edge of the browser window. the second (and final) keyframe occurs at 100% (using the alias to). the left margin is set to 0% and the width of the element is set to 100%. this causes the header to finish its animation flush against the left edge of the content area. <p>the caterpillar and alice looked at each other for some time in silence: at last the caterpillar took the hookah out of its mouth, and addressed her in a languid, sleepy voice.</p> note: reload page to see the animation, or click the codepen button to see the animation in the codepen environment. adding another keyframe le...
...And 2 more matches
Creating a Wizard - Archive of obsolete content
rd has two pages, one that has a drop-down menu and the other with a set of radio buttons. the wizard will be formatted automatically, with a title across the top and a set of buttons along the bottom. the user can navigate between the pages of the wizard with the back and next buttons. these buttons will enable and disable themselves at the appropriate moments. ...
...last page, the finish button will appear. all of this is automatic, so you don't have to do anything to manipulate the pages. the description attribute may optionally be placed on a wizardpage element to provide a sub-caption for that page. in the example above, it has been placed on the second page, but not the first page. handling page changes you will generally want to do something once the finish button is pressed. you can set an attribute onwizardfinish on the wizard element to accomplish this. set it to a script which performs whatever task you want and then returns true. this script might be used to save the information that the user entered during the wizard. ...
...if the function returns true, the wizard closes. ...
... accomplish this. set it to a script which performs whatever task you want and then returns true. this script might be used to save the information that the user entered during the wizard. for example: <wizard id="example-window" title="select a dog wizard" onwizardfinish="return savedoginfo();" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> when the user clicks the finish button, the function savedoginfo() will be called, which would be defined in a script file to save the information that was entered. if the function returns true, the wizard closes. if it returns false, then the wizard does not close, which might occur if the function savedoginfo() encountered invalid input, for example. there are also related onwizardback, onwizardnext and onwizardcancel attrib...
Test your skills: HTML accessibility - Learn web development
ur understanding of text semantics, and why they are good for accessibility. the given text is a simple information panel with action buttons, but the html is really bad. we want you to update it use appropriate semantic html. you don't need to worry too much about recreating the exact same look and text sizing, as long as the semantics are good. try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor. html accessibility 2 in the second task, you have a form containing three input fields. you need to: semantically associate the input with their labels. assume that these inputs will be part of a larger form, and wrap them in an element that associates them all together as a single r...
...ave a form containing three input fields. you need to: semantically associate the input with their labels. assume that these inputs will be part of a larger form, and wrap them in an element that associates them all together as a single related group. give the group a description/title that summarises all of the information as personal data. try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor. html accessibility 3 in this task you are required to turn all the information links in the paragraph into good, accessible links. the first two links just go to regular web pages. the third link goes to a pdf, and it's large — 8mb. the fourth link goes to a word document, so the ...
...bility 3 in this task you are required to turn all the information links in the paragraph into good, accessible links. the first two links just go to regular web pages. the third link goes to a pdf, and it's large — 8mb. the fourth link goes to a word document, so the user will need some kind of application installed that can handle that. try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor. html accessibility 4 in our final html accessibility task, you are given a simple image gallery, which has some accessibility problems. can you fix them? the header image has an accessiiblity issue, and so do the gallery images. you could take the header image further and implement i...
...ssibility task, you are given a simple image gallery, which has some accessibility problems. can you fix them? the header image has an accessiiblity issue, and so do the gallery images. you could take the header image further and implement it using css for arguably better accessibility. why is this better, and what would a solution look like? try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor. assessment or further help you can practice these examples in the interactive editors above. if you would like your work assessed, or are stuck and want to ask for help: put your work into an online shareable editor such as codepen, jsfiddle, or glitch. you can write the code yoursel...
Test your skills: Flexbox - Learn web development
however it may be helpful to download the code and use an online tool such as codepen, jsfiddle, or glitch to work on the tasks. if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page. flex layout one these list items are the navigation for a site. they should be laid out as a row, with an equal amount of space between each item. the finished example should look like the image below. try updating the live code below to recreate the finished example: for assessment or further work purposes, download the starting point for this task to work in your own editor or in an online editor. flex layout two these list items are all different sizes, but we want them to be displayed as three equal sized columns, no matter what content ...
... code below to recreate the finished example: for assessment or further work purposes, download the starting point for this task to work in your own editor or in an online editor. flex layout two these list items are all different sizes, but we want them to be displayed as three equal sized columns, no matter what content is in each item. try updating the live code below to recreate the finished example: additional questions: can you now make the first item twice the size of the other items? for assessment or further work purposes, download the starting point for this task to work in your own editor or in an online editor. flex layout three there are two elements in the html below, a div with a class of .parent which contains another div with a class of .child. use flexbox ...
...he other items? for assessment or further work purposes, download the starting point for this task to work in your own editor or in an online editor. flex layout three there are two elements in the html below, a div with a class of .parent which contains another div with a class of .child. use flexbox to center the child inside the parent. ...
... assessment or further help you can practice these examples in the interactive editors mentioned above. ...
Index - Learn web development
in this module we take a look at asynchronous javascript, why it is important, and how it can be used to effectively handle potential blocking operations such as fetching resources from a server. 50 choosing the right approach beginner, intervals, javascript, learn, optimize, promises, async, asynchronous, await, requestanimationframe, setinterval, settimeout, timeouts 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. 51 cooperative asynchronous javascript: timeouts and intervals animation, beginner, coding...
...ssue is that we've completely ignored its look and feel up to now. in the next article, we'll concentrate on fixing this, looking at the different ways vue provides to style components. 272 advanced svelte: reactivity, lifecycle, accessibility accessibility, beginner, components, frameworks, javascript, learn, lifecycle, svelte, client-side, reactivity in this article we have finished adding all the required functionality to our app, plus we've taken care of a number of accessibility and usability issues. we also finished splitting our app into manageable components, each one with a unique responsibility. 273 beginning our react todo list app, beginner, frameworks, javascript, learn, react, style, client-side now our todo list app actually looks a bit mo...
...vue components beginner, frameworks, javascript, learn, client-side, lists, v-for, vue and that brings us to the end of another article. we now have sample data in place, and a loop that takes each bit of data and renders it inside a todoitem in our app. 294 routing in ember beginner, ember, frameworks, javascript, learn, routing, client-side congratulations! you've finished this tutorial! 295 starting our svelte todo list app beginner, components, frameworks, javascript, learn, svelte, client-side, state with our markup and styling in place our todo list app is starting to take shape, and we have everything ready so that we can start to focus on the features we have to implement. 296 styling vue components with css beginner, css...
...opment tools beginner, css, deployment, html, javascript, learn, tools, transformation, client-side, linting client-side tooling can be intimidating, but this series of articles aims to illustrate the purpose of some of the most common client-side tool types, explain the tools you can chain together, how to install them using package managers, and control them using the command line. we finish up by providing a complete toolchain example showing you how to get productive. 303 client-side tooling overview beginner, introduction, learn, tools, client-side that rounds off our gentle introduction to the topic of client-side web tooling, from a high level. next up we provide you with a crash course on the command line, which is where a lot of tooling is invoked from. we...
Graceful asynchronous programming with Promises - Learn web development
onnected". if getusermedia() fails, the catch block runs. this uses setstatusmessage() to update the status box to indicate that an error occurred. the important thing here is that the getusermedia() call returns almost immediately, even if the camera stream hasn't been obtained yet. even if the handlecallbutton() function has already returned to the code that called it, when getusermedia() has finished working, it calls the handler you provide. as long as the app doesn't assume that streaming has begun, it can just keep on running. note: you can learn more about this somewhat advanced topic, if you're interested, in the article signaling and video calling. code similar to this, but much more complete, is used in that example. the trouble with callbacks to fully understand why promises ar...
...with callbacks to fully understand why promises are a good thing, it helps to think back to old-style callbacks and to appreciate why they are problematic. let's talk about ordering pizza as an analogy. there are certain steps that you have to take for your order to be successful, which doesn't really make sense to try to execute out of order, or in order but before each previous step has quite finished: you choose what toppings you want. this can take a while if you are indecisive, and may fail if you just can't make up your mind, or decide to get a curry instead. you then place your order. this can take a while to return a pizza and may fail if the restaurant does not have the required ingredients to cook it. you then collect your pizza and eat. this might fail if, say, you forgot your ...
... note: then()/catch()/finally() is the async equivalent to try/catch/finally in sync code. building your own custom promises the good news is that, in a way, you've already built your own promises. when you've chained multiple promises together with .then() blocks, or otherwise combined t...
... note: then()/catch()/finally() is the async equivalent to try/catch/finally in sync code. ...
Cooperative asynchronous JavaScript: Timeouts and intervals - Learn web development
setinterval() returns an identifying value you can use later when you need to clear the interval. clearing intervals setinterval() keeps running a task forever, unless you do something about it. you'll probably want a way to stop such tasks, otherwise you may end up getting errors when the browser can't complete any further versions of the task, or if the animation being handled by the task has finished. you can do this the same way you stop timeouts — by passing the identifier returned by the setinterval() call to the clearinterval() function: const myinterval = setinterval(myfunction, 2000); clearinterval(myinterval); active learning: creating your own stopwatch! with this all said, we've got a challenge for you. take a copy of our setinterval-clock.html example, and modify it to creat...
... as possible but only after the main code thread has been run. for instance, the code below (see it live) outputs an alert containing "hello", then an alert containing "world" as soon as you click ok on the first alert. settimeout(function() { alert('world'); }, 0); alert('hello'); this can be useful in cases where you want to set a block of code to run as soon as all of the main thread has finished running — put it on the async event loop, so it will run straight afterwards. clearing with cleartimeout() or clearinterval() cleartimeout() and clearinterval() both use the same list of entries to clear from. interestingly enough, this means that you can use either method to clear a settimeout() or setinterval(). for consistency, you should use cleartimeout() to clear settimeout() entries...
...able defined earlier to an active requestanimation() call, which takes the draw() function as its parameter. this starts the animation off, constantly running the draw() function at a rate as near 60 fps as possible. raf = requestanimationframe(draw); below the draw() function definition, add a call to the the draw() function to start the animation. draw(); note: you can find the finished example live on github. (you can see the source code, also.) clearing a requestanimationframe() call clearing a requestanimationframe() call can be done by calling the corresponding cancelanimationframe() method. (note that the function name starts with "cancel", not "clear" as with the "set..." methods.) just pass it the value returned by the requestanimationframe() call to cancel, which ...
...key. when the start button is pressed, a spinner like the one we saw earlier is displayed for a random amount of time between 5 and 10 seconds. after that time, a message will appear saying "players go!!" — once this happens, the first player to press their control button will win the game. let's work through this: first of all, download the starter file for the app. this contains the finished html structure and css styling, giving us a game board that shows the two players' information (as seen above), but with the spinner and results paragraph displayed on top of one another. you just have to write the javascript code. inside the empty <script> element on your page, start by adding the following lines of code that define some constants and variables you'll need in the rest of...
Test your skills: Conditionals - Learn web development
uninitialized, but is later used to store a reponse that will be printed to the output panel. we want you to create a conditional that checks whether season contains the string "summer", and if so assigns a string to response that gives the user an appropriate message about the season. if not, it should assign a generic string to response that tells the user we don't know what season it is. to finish off, you should then add another test that checks whether season contains the string "winter", and again assigns an appropriate string to response. try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor. conditionals 2 for this task you are given three variables: machineactive — co...
...was a terrible score — total fail!" score of 20 to 39 — "you know some things, but it's a pretty bad score. needs improvement." score of 40 to 69 — "you did a passable job, not bad!" score of 70 to 89 — "that\'s a great score, you really know your stuff." score of 90 to 100 — "what an amazing score! did you cheat? are you for real?" try updating the live code below to recreate the finished example. after you've entered your code, try changing machineactive to true, to see if it works. download the starting point for this task to work in your own editor or in an online editor. conditionals 3 in this task you need to take the code you wrote for the second task, and rewrite the inner if...else if...else to use a switch statement instead. try updating the live code below to r...
...after you've entered your code, try changing machineactive to true, to see if it works. download the starting point for this task to work in your own editor or in an online editor. conditionals 3 in this task you need to take the code you wrote for the second task, and rewrite the inner if...else if...else to use a switch statement instead. try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor. conditionals 4 for the final task you are given four variables: machineactive — contains an indicator of whether the login machine is switched on or not (true/false). pwd — contains the user's login password. machineresult — begins uninitialized, but is later used to store a r...
...that checks whether the pwd is equal to cheese. if so, it should assign a string to pwdresult telling the user they logged in successfully. if not, it should assign a different string to pwdresult telling the user their login attempt was not successful. we'd like you to do this in a single line, using something that isn't an if ... else structure. try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor. assessment or further help you can practice these examples in the interactive editors above. if you would like your work assessed, or are stuck and want to ask for help: put your work into an online shareable editor such as codepen, jsfiddle, or glitch. you can write the code yoursel...
Client-side storage - Learn web development
mber' part forgetdiv.style.display = 'none'; rememberdiv.style.display = 'block'; } } last but not least, we need to run the namedisplaycheck() function every time the page is loaded. if we don't do this, then the personalized greeting will not persist across page reloads. ...
..., we need to run the namedisplaycheck() function every time the page is loaded. if we don't do this, then the personalized greeting will not persist across page reloads. add the following to the bottom of your code: document.body.onload = namedisplaycheck; your example is finished — well done! all that remains now is to save your code and test your html page in a browser. you can see our finished version running live here. note: there is another, slightly more complex example to explore at using the web storage api. note: in the line <script src="index.js" defer></script> of the source for our finished version, the defer attribute specifies that the contents of the <script> element will not execute until the page has finished loading. storing complex data — indexeddb the index...
...e this in a few places, so we've declared it globally here to make things easier. next, add the following to the bottom of your code: window.onload = function() { }; we will write all of our subsequent code inside this window.onload event handler function, called when the window's load event fires, to make sure we don't try to use indexeddb functionality before the app has completely finished loading (it could fail if we don't). inside the window.onload handler, add the following: // open our database; it is created if it doesn't already exist // (see onupgradeneeded below) let request = window.indexeddb.open('notes_db', 1); this line creates a request to open version 1 of a database called notes_db. if this doesn't already exist, it will be created for you by subsequent...
... displaydata(); }; transaction.onerror = function() { console.log('transaction not opened due to error'); }; } this is quite complex; breaking it down, we: run event.preventdefault() on the event object to stop the form actually submitting in the conventional manner (this would...
Manipulating documents - Learn web development
o point using javascript to create static content — you might as well just write it into your html and not use javascript. it is more complex than html, and creating your content with javascript also has other issues attached to it (such as not being readable 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 i...
...he window is resized — let's access that via the window.onresize event handler and rerun our sizing code each time it changes. add the following to the bottom of your code: window.onresize = function() { winwidth = window.innerwidth; winheight = window.innerheight; div.style.width = winwidth + 'px'; div.style.height = winheight + 'px'; } note: if you get stuck, have a look at our finished window resize example (see it live also). active learning: a dynamic shopping list to round off the article, we'd like to set you a little challenge — we want to make a simple shopping list example that allows you to dynamically add items to the list using a form input and button. when you add an item to the input and press the button: the item should appear in the list. each item shou...
...we want to make a simple shopping list example that allows you to dynamically add items to the list using a form input and button. when you add an item to the input and press the button: the item should appear in the list. each item should be given a button that can be pressed to delete that item off the list. the input should be emptied and focused ready for you to enter another item. the finished demo will look something like this: to complete the exercise, follow the steps below, and make sure that the list behaves as described above. to start with, download a copy of our shopping-list.html starting file and make a copy of it somewhere. you'll see that it has some minimal css, a list with a label, input, and button, and an empty list and <script> element. you'll be making all you...
...t value you saved earlier, and the text content of the button to 'delete'. append the list item as a child of the list. attach an event handler to the delete button, so that when clicked it will delete the entire list item it is inside. finally, use the focus() method to focus the input element ready for entering the next shopping list item. note: if you get really stuck, have a look at our finished shopping list (see it running live also.) summary we have reached the end of our study of document and dom manipulation. at this point you should understand what the important parts of a web browser are with respect to controlling documents and other aspects of the user's web experience. most importantly, you should understand what the document object model is, and how to manipulate it to cr...
Test your skills: Strings - Learn web development
quote, and add it to the example inside a variable called quoteend. concatenate the two strings together to make a single string containing the complete quote. save the result inside a variable called finalquote. you'll find that you get an error at this point. can you fix the problem with quotestart, so that the full quote displays correctly? try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor. strings 2 in this task you are provided with two variables, quote and substring, which contain two strings. we would like you to: retrieve the length of the quote, and store it in a variable called quotelength. find the index position where substring appears in quote, and store that ...
... in a variable called quotelength. find the index position where substring appears in quote, and store that value in a variable called index. use a combination of the variables you have and available string properties/methods to trim down the original quote to "i do not like green eggs and ham.", and store it in a variable called revisedquote. try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor. strings 3 in the next string task, you are given the same quote that you ended up with in the previous task, but it is somewhat broken! we want you to fix and update it, like so: change the casing to correct sentence case (all lowercase, except for upper case first letter). store the ...
...ence case (all lowercase, except for upper case first letter). store the new quote in a variable called fixedquote. in fixedquote, replace "green eggs and ham" with another food that you really don't like. there is one more small fix to do — add a full stop onto the end of the quote, and save the final version in a variable called finalquote. try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor. strings 4 in the final string task, we have given you the name of a theorem, two numeric values, and an incomplete string (the bits that need adding are marked with asterisks (*)). we want you to change the value of the string as follows: change it from a regular string literal into a...
...l placeholders. these should be: the name of the theorem. the two number values we have. the length of the hypotenuse of a right-angled triangle, given that the two other side lengths are the same as the two values we have. you'll need to look up how to calculate this from what you have. do the calculation inside the placeholder. try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor. assessment or further help you can practice these examples in the interactive editors above. if you would like your work assessed, or are stuck and want to ask for help: put your work into an online shareable editor such as codepen, jsfiddle, or glitch. you can write the code yoursel...
DownloadList
cross sessions. a reference to a downloadlist object can be obtained using the downloads.getlist() function. method overview promise<array<download>> getall(); promise add(download adownload); promise remove(download adownload); promise addview(object aview); promise removeview(object aview); void removefinished([optional] function afilterfn); methods getall() retrieves a snapshot of the downloads that are currently in the list. the returned array does not change when downloads are added or removed, though the download objects it contains are still updated in real time. promise<array<download>> getall(); parameters none. promise resolves to an array of download objects. add() adds a new downl...
...ll the ondownloadadded notifications for the existing downloads have been sent. removeview() removes a view that was previously added using addview(). promise removeview( object aview ); parameters aview optional the view object to remove. promise resolves to undefined when the view has been removed. at this point, the removed view will not receive any more notifications. ...
... downloads have been sent. removeview() removes a view that was previously added using addview(). promise removeview( object aview ); parameters aview optional the view object to remove. promise resolves to undefined when the view has been removed. at this point, the removed view will not receive any more notifications. ...
...d view will not receive any more notifications. removefinished() removes downloads from the list that have finished, have failed, or have been canceled without keeping partial data. a filter function may be specified to remove only a subset of those downloads. this method finalizes each removed download, ensuring that any partially downloaded data associated with it is also removed. promise removefinished( function afilterfn ); parameters afilterfn the filter function is called with each download as its only argument, and should return true to remove the download and false to keep it. this parameter may be null or omitted to have no additional filter. ...
Index
directory. the %temp% directory is created at the beginning of the installation and destroyed at the end. the purpose of %temp% is to hold executable files (such as setup programs) or files that are used by these programs. files destined for the temporary directory are guaranteed to be in place before any executable file is run; they are not deleted until all executable files have finished. absolutepath specifies the destination directory of the file as an absolute path. executable specifies that the file is to be executed during the course of the installation. typically, this string is used for a setup program provided by a module vendor, such as a self-extracting setup executable. more than one file can be specified as executable, in which case the files ...
...e installed on the machines to which you are distributing it. before you can use netscape signing tool to sign files, you must have an object-signing certificate, which is a special certificate whose associated private key is used to create digital signatures. for testing purposes only, you can create an object-signing certificate with netscape signing tool 1.3. when testing is finished and you are ready to disitribute your software, you should obtain an object-signing certificate from one of two kinds of sources: * an independent certificate authority (ca) that authenticates your identity and charges you a fee. you typically get a certificate from an independent ca if you want to sign software that will be distributed over the internet. * ca server soft...
...if you are installing the keys and certificate in the communicator databases, you must exit communicator before using this option; otherwise, you risk corrupting the databases. in all cases, the certificate is also output to a file named x509.cacert, which has the mime-type application/x-x509-ca-cert. unlike certificates normally used to sign finished code to be distributed over a network, a test certificate created with -g is not signed by a recognized certificate authority. instead, it is self-signed. in addition, a single test signing certificate functions as both an object-signing certificate and a ca. when you are using it to sign objects, it behaves like an object-signing certifica...
...ular hardware or software token. -m modify a certificate's trust attributes using the values of the -t argument. -n create new certificate and key databases. -o print the certificate chain. -r create a certificate request file that can be submitted to a certificate authority (ca) for processing into a finished certificate. output defaults to standard out unless you use -o output-file argument. use the -a argument to specify ascii output. -s create an individual certificate and add it to a certificate database. -t reset the key database or token. -u list all available modules or print a single named module. -v ...
Mozilla internal string guide
erence to an nsresult for indicating failure on oom. (don't access the return value if the nsresult indicates failure. unfortunately mozilla::result is not versatile enough to be used here.) bulkwrite() returns a mozilla::bulkwritehandle<t>, where t is either char or char16_t. the actual writes are performed through this handle. ...
...lt indicates failure. unfortunately mozilla::result is not versatile enough to be used here.) bulkwrite() returns a mozilla::bulkwritehandle<t>, where t is either char or char16_t. the actual writes are performed through this handle. you must not access the string except via the handle until you call finish() on the handle in the success case or you let the handle go out of scope without calling finish() in the failure case, in which case the destructor of the handle puts the string in a mostly harmless but consistent state (containing a single replacement character if a capacity greater than 0 was requested, or in the char case if the three-byte utf-8 representation of the replacement character doesn't fit, an ascii substitute). mozilla::bulkwritehandle<t> autoconverts to a writable mozilla::...
...essors named consistently with those on span: elements() and length() the latter is not the logical length of the string but the writable length of the buffer. the buffer exposed via these methods includes the prefix that you may have requested to be preserved. it's up to you to skip past it so as to not overwrite it. if there's a need to request a different capacity before you are ready to call finish(), you can call restartbulkwrite() on the handle. it takes three arguments that match the first three arguments of bulkwrite(). it returns mozilla::result<mozilla::ok, nsresult> to indicate success or oom. calling restartbulkwrite() invalidates previously-obtained span, raw pointer or length. once you are done writing, call finish(). it takes two arguments: the new logical length of the string (...
...compared to a c string using c functions. ns*string.equalsascii(const char *) - compares with an ascii c string. ns*string.equalsliteral - compares with a string literal. common patterns callee-allocated parameters many apis result in a method allocating a buffer in order to return strings to its caller. this can be tricky because the caller has to remember to free the string when they have finished using it. fortunately, the getter_copies() function makes this very easy. a method may look like this: void getvalue(char16_t** avalue) { *avalue = tonewunicode(foo); } without getter_copies(), the caller would need to free the string: { char16_t* val; getvalue(&val); if (somecondition) { // don't forget to free the value! ns_free(val); return ns_er...
nsIProcess
this method will block until the process terminates; if false, the method returns immediately. args an array of count arguments, using the native character set, to be passed to the executable on its command line. count the number of arguments in the args array. runasync() asynchronously runs the process with which the object was initialized, optionally calling an observer when the process finishes running. void runasync( [array, size_is(count)] in string args, in unsigned long count, in nsiobserver observer, optional in boolean holdweak optional ); parameters args an array of arguments to pass into the process, using the native character set. this array must have count entries. count the number of arguments passed in the args array. observer optional an observer that w...
...er, optional in boolean holdweak optional ); parameters args an array of arguments to pass into the process, using the native character set. this array must have count entries. count the number of arguments passed in the args array. observer optional an observer that will be notified when the process exits. the observer will receive this nsiprocess instance as the subject and "process-finished" or "process-failed" as the topic. the observer will be notified on the main thread. holdweak optional if true, a weak reference is used to hold the observer. runw() executes the file this object was initialized with. void runw( in boolean blocking, [array, size_is(count)] in wstring args, in unsigned long count ); parameters blocking if true, this method will block until t...
...locking if true, this method will block until the process terminates; if false, the method returns immediately. args an array of count arguments, using utf-16, to be passed to the executable on its command line. count the number of arguments in the args array. runwasync() asynchronously runs the process with which the object was initialized, optionally calling an observer when the process finishes running. void runwasync( [array, size_is(count)] in wstring args, in unsigned long count, in nsiobserver observer, optional in boolean holdweak optional ); parameters args an array of arguments to pass into the process, using utf-16. this array must have count entries. count the number of arguments passed in the args array. observer optional an observer that will be notified ...
...nsiobserver observer, optional in boolean holdweak optional ); parameters args an array of arguments to pass into the process, using utf-16. this array must have count entries. count the number of arguments passed in the args array. observer optional an observer that will be notified when the process exits. the observer will receive this nsiprocess instance as the subject and "process-finished" or "process-failed" as the topic. the observer will be notified on the main thread. holdweak optional if true, a weak reference is used to hold the observer. example // create an nsifile for the executable var file = components.classes["@mozilla.org/file/local;1"] .createinstance(components.interfaces.nsifile); file.initwithpath("c:\\myapp.exe"); // create an nsiproc...
Animation - Web APIs
Web › API › Animation
new animation object instance. properties animation.currenttime the current time value of the animation in milliseconds, whether running or paused. if the animation lacks a timeline, is inactive or hasn't been played yet, its value is null. animation.effect gets and sets the animationeffectreadonly associated with this animation. this will usually be a keyframeeffect object. animation.finished read only returns the current finished promise for this animation. animation.id gets and sets the string used to identify the animation. animation.pending read only indicates whether the animation is currently waiting for an asynchronous operation such as initiating playback or pausing a running animation. animation.playstate read only returns an enumerated value describing the pla...
...will be active if the animation has been replaced, or persisted if animation.persist() has been invoked on it. animation.starttime gets or sets the scheduled time when an animation's playback should begin. animation.timeline gets or sets the timeline associated with this animation. event handlers animation.oncancel gets and sets the event handler for the cancel event. animation.onfinish gets and sets the event handler for the finish event. animation.onremove allows you to set and run an event handler that fires when the animation is removed (i.e., put into an active replace state). methods animation.cancel() clears all keyframeeffects caused by this animation and aborts its playback. animation.commitstyles() commits the end styling state of an animation to the element...
...hods animation.cancel() clears all keyframeeffects caused by this animation and aborts its playback. animation.commitstyles() commits the end styling state of an animation to the element being animated, even after that animation has been removed. it will cause the end styling state to be written to the element being animated, in the form of properties inside a style attribute. animation.finish() seeks either end of an animation, depending on whether the animation is playing or reversing. animation.pause() suspends playing of an animation. animation.persist() explicitly persists an animation, when it would otherwise be removed due to the browser's automatically removing filling animations behavior. animation.play() starts or resumes playing of an animation, or begins the an...
...ation, depending on whether the animation is playing or reversing. animation.pause() suspends playing of an animation. animation.persist() explicitly persists an animation, when it would otherwise be removed due to the browser's automatically removing filling animations behavior. animation.play() starts or resumes playing of an animation, or begins the animation again if it previously finished. animation.reverse() reverses playback direction, stopping at the start of the animation. if the animation is finished or unplayed, it will 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...
Document.onafterscriptexecute - Web APIs
the document.onafterscriptexecute property references a function that fires when a static <script> element finishes executing its script. it does not fire if the element is added dynamically, such as with appendchild(). syntax document.onafterscriptexecute = funcref; funcref is a function reference, called when the event is fired. the event's target attribute is set to the <script> element that just finished executing. ...
...erences a function that fires when a static <script> element finishes executing its script. it does not fire if the element is added dynamically, such as with appendchild(). syntax document.onafterscriptexecute = funcref; funcref is a function reference, called when the event is fired. the event's target attribute is set to the <script> element that just finished executing. ...
...s when a static <script> element finishes executing its script. it does not fire if the element is added dynamically, such as with appendchild(). syntax document.onafterscriptexecute = funcref; funcref is a function reference, called when the event is fired. the event's target attribute is set to the <script> element that just finished executing. ...
...t is added dynamically, such as with appendchild(). syntax document.onafterscriptexecute = funcref; funcref is a function reference, called when the event is fired. ...
FileReader - Web APIs
ndler for the progress event. this event is triggered while reading a blob content. as filereader inherits from eventtarget, all those events can also be listened for by using the addeventlistener method. methods filereader.abort() aborts the read operation. upon return, the readystate will be done. ...
...ing the addeventlistener method. methods filereader.abort() aborts the read operation. upon return, the readystate will be done. filereader.readasarraybuffer() starts reading the contents of the specified blob, once finished, the result attribute contains an arraybuffer representing the file's data. filereader.readasbinarystring() starts reading the contents of the specified blob, once finished, the result attribute contains the raw binary data from the file as a string. ...
...an optional encoding name can be specified. ...
...an optional encoding name can be specified. events listen to these events using addeventlistener() or by assigning an event listener to the oneventname property of this interface. ...
PerformanceTiming - Web APIs
art. performancetiming.unloadeventstart read only when the unload event has been thrown, indicating the time at which the previous document in the window began to unload. if there is no previous document, or if the previous document or one of the needed redirects is not of the same origin, the value returned is 0. performancetiming.unloadeventend read only when the unload event handler finishes. if there is no previous document, or if the previous document, or one of the needed redirects, is not of the same origin, the value returned is 0. performancetiming.redirectstart read only when the first http redirect starts. if there is no redirect, or if one of the redirects is not of the same origin, the value returned is 0. performancetiming.redirectend read only when the last ...
...nt using an http request. this moment is before the check to any application cache. performancetiming.domainlookupstart read only when the domain lookup starts. if a persistent connection is used, or the information is stored in a cache or a local resource, the value will be the same as performancetiming.fetchstart. performancetiming.domainlookupend read only when the domain lookup is finished. if a persistent connection is used, or the information is stored in a cache or a local resource, the value will be the same as performancetiming.fetchstart. performancetiming.connectstart read only when the request to open a connection is sent to the network. if the transport layer reports an error and the connection establishment is started again, the last connection establishment start...
...the last byte of the response, or when the connection is closed if this happened first, from the server, the cache, or from a local resource. performancetiming.domloading read only when the parser started its work, that is when its document.readystate changes to 'loading' and the corresponding readystatechange event is thrown. performancetiming.dominteractive read only when the parser finished its work on the main document, that is when its document.readystate changes to 'interactive' and the corresponding readystatechange event is thrown. performancetiming.domcontentloadedeventstart read only right before the parser sent the domcontentloaded event, that is right after all the scripts that need to be executed right after parsing have been executed. performancetiming.domcont...
...ad only right before the parser sent the domcontentloaded event, that is right after all the scripts that need to be executed right after parsing have been executed. performancetiming.domcontentloadedeventend read only right after all the scripts that need to be executed as soon as possible, in order or not, have been executed. performancetiming.domcomplete read only when the parser finished its work on the main document, that is when its document.readystate changes to 'complete' and the corresponding readystatechange event is thrown. performancetiming.loadeventstart read only when the load event was sent for the current document. if this event has not yet been sent, it returns 0. performancetiming.loadeventend read only when the load event handler terminated, that is w...
RTCPeerConnection: icegatheringstatechange event - Web APIs
g process changes. this signifies that the value of the connection's icegatheringstate property has changed. when ice firststarts to gather connection candidates, the value changes from new to gathering to indicate that the process of collecting candidate configurations for the connection has begun. when the value changes to complete, all of the transports that make up the rtcpeerconnection have finished gathering ice candidates. bubbles no cancelable no interface event event handler onicegatheringstatechange note: while you can determine that ice candidate gathering is complete by watching for icegatheringstatechange events and checking for the value of icegatheringstate to become complete, you can also simply have your handler for the i...
...ent handler onicegatheringstatechange note: while you can determine that ice candidate gathering is complete by watching for icegatheringstatechange events and checking for the value of icegatheringstate to become complete, you can also simply have your handler for the icecandidate event look to see if its candidate property is null. ...
...null. this also indicates that collection of candidates is finished. examples this example creates a handler for icegatheringstatechange events. ...
... candidate recommendation initial specification. ...
Migrating from webkitAudioContext - Web APIs
this means that you may need to restructure your code to run the part which happened after the createbuffer() call in the success callback, as you can see in the example above. renaming of audioparam.settargetvalueattime the settargetvalueattime() method on the audioparam...
... node or not. you can compare the value of audiocontext.currenttime to the first argument passed to start() to know whether playback has started or not. if you need to compare this attribute to playing_state, you can compare the value of audiocontext.currenttime to the first argument passed to start() to know whether playback has started or not. ...
...started or not. if you need to compare this attribute to playing_state, you can compare the value of audiocontext.currenttime to the first argument passed to start() to know whether playback has started or not. if you need to know when playback of the node is finished (which is the most significant use case of playbackstate), there is a new ended event which you can use to know when playback is finished. please see this code example: // old webkitaudiocontext code: var src = context.createbuffersource(); // some time later... ...
...ument passed to start() to know whether playback has started or not. if you need to know when playback of the node is finished (which is the most significant use case of playbackstate), there is a new ended event which you can use to know when playback is finished. please see this code example: // old webkitaudiocontext code: var src = context.createbuffersource(); // some time later... var isfinished = (src.playbackstate == src.finished_state); // new audiocontext code: var src = context.createbuffersource(); function endedhandler(event) { isfinished = true; } var isfinished = false; src.onended = endedhandler; the exact same changes have been applied to both audiobuffersourcenode and oscillatornode, so you can apply the same techniques to both kinds of nodes. removal of audiocontext.
tabs - Archive of obsolete content
open, manipulate, and access tabs, and receive tab events. usage open a tab you can open a new tab, specifying various properties including location: var tabs = require("sdk/tabs"); tabs.open("http://www.example.com"); track tabs you can register event listeners to be notified when tabs open, close, finish loading dom content, or are made active or inactive: var tabs = require("sdk/tabs"); // listen for tab openings. tabs.on('open', function onopen(tab) { myopentabs.push(tab); }); // listen for tab content loads. tabs.on('ready', function(tab) { console.log('tab is loaded', tab.title, tab.url); }); access tabs the module itself can be used as a list of all opened tabs across all windows. in particular, you can enumerate it: var tabs = require('sdk/tabs'); for (let tab of tabs)...
...ns various tab properties, several methods for manipulation, as well as per-tab event registration. tabs emit all the events described in the events section. listeners are passed the tab object that triggered the event. methods pin() pins this tab as an app tab. unpin() unpins this tab. close(callback) closes this tab. parameters callback : function a function to be called when the tab finishes its closing process. this is an optional argument. reload() reloads this tab. activate() makes this tab active, which will bring this tab to the foreground. getthumbnail() returns thumbnail data uri of the page currently loaded in this tab. attach(options) attach one or more scripts to the document loaded in the tab. note that by attaching inside ready event, this becomes tab-centric: i...
...s or the content is reloaded. after this event has been emitted, all properties relating to the tab's content can be used. arguments tab : listeners are passed the tab object. load this event is emitted when the page for the tab's content is loaded. it is equivalent to the load event for the given content page. at this point the document and its resources, such as images and stylesheets, have finished loading. this event can be used for pages that do not have a domcontentloaded event, like images. for pages that have a domcontentloaded event, load is fired after ready. a single tab will emit this event every time the page is loaded: so it will be emitted again if the tab's location changes or the content is reloaded. after this event has been emitted, all properties relating to the tab's c...
Creating Reusable Modules - Archive of obsolete content
var s = array.from(hash, (c, i) => tohexstring(hash.charcodeat(i))).join(""); return s; } putting it together the complete add-on adds a button to firefox: when the user clicks the button, we ask them to select a file, compute the hash, and log the hash to the console: var {cc, ci} = require("chrome"); // return the two-dig...
... var s = array.from(hash, (c, i) => tohexstring(hash.charcodeat(i))).join(""); return s; } function promptforfile() { var window = require("sdk/window/utils").getmostrecentbrowserwindow(); const nsifilepicker = ci.nsifilepicker; var fp = cc["@mozilla.org/filepicker;1"] .createinstance(nsifilepicker); fp.init(...
... var s = array.from(hash, (c, i) => tohexstring(hash.charcodeat(i))).join(""); return s; } exports.hashfile = md5file; index.js finally, update index.js to import these two new modules and use them: var filepicker = require("./filepicker.js"); var md5 = require("./md5.js"); require("sdk/ui/button/action").actionbutton({ i...
Enhanced Extension Installation - Archive of obsolete content
nning app disagrees with the info held by this file, a compatibility check is run on all installed items. when changes are made to the extensions datasource - new items are installed, old items uninstalled, enabled or disabled, a .autoreg file is written to the profile directory as well, which tells the startup code that the system has been modified, so that it destroys the component registries, finishes pending transactions and regenerates metadata appropriately. datasource structure the extension manager implements a rdf datasource which contains a composite of the two xml/rdf datasources at the two install locations. the composite datasource handles all read-only information requests, and when data must be written the extension manager determines the appropriate datasource to write and flu...
...escribed above (metadata written, added to container). finalization for themes, the item is immediately installed fully, rather than awaiting the next restart, since themes do not supply xpcom components, preferences defaults etc. for extensions, on the next startup, the startup system notices the presence of the .autoreg file and starts the extension manager with a "dirty" flag, telling it to finish any install operations that may be pending. the extension manager loads the xml/rdf datasources (this is allowable and necessary because a major change has happened) and gets a list of all items that need to be installed (tracked using a tobeinstalled flag on the item in the datasource). it locates the staged copy of the xpi file, extracts its contents (logging file additions as it goes into {gu...
...arrays hashed by operation key, each entry having a locationkey and id properties. the startup cache data structure is used to reflect the extensions-startup.manifest file over the lifetime of the running application, the extensions-startup.manifest file is written from the current state of the cache. the pending operations list is used by the install operation finalization routine (|_finishoperations|) to get a list of items that are to be operated on. since all metadata is now stored in the profile directory, there is no longer any need for special extension system handling of the -register command line flag, so support for that has been removed. datasource structure since there is now only a single rdf/xml datasource for storage of all installed items, the staggered datasource...
Chapter 5: Let's build a Firefox extension - Archive of obsolete content
.xul chrome://helloworld/skin/overlay.css style chrome://global/content/customizetoolbar.xul chrome://helloworld/skin/overlay.css that completes the process of xpi packaging. one point you need to take special note of is that in step 4, you updated chrome.manifest so that the files it refers to have paths pointing inside the zip archive. in order to go back into development mode after you’ve finished packaging the extension as an xpi, you need to revert the chrome.manifest you edited in step 4 to point to the backup files in step 3. if you forget to do this, any subsequent changes you make to your source files during development will not be reflected. you may want to write a batch file to automate this task. there’s a simpler way to package an extensions as an xpi. create a zip archive c...
...sifileoutputstream); stream.init(afile, 0x02 | 0x08 | 0x20, 0600, 0); // convert to utf-8 var converter = components.classes["@mozilla.org/intl/scriptableunicodeconverter"]. createinstance(components.interfaces.nsiscriptableunicodeconverter); converter.charset = "utf-8"; var converteddata = converter.convertfromunicode(adata); converteddata += converter.finish(); // write and close stream stream.write(converteddata, converteddata.length); if (stream instanceof components.interfaces.nsisafeoutputstream) { stream.finish(); } else { stream.close(); } }, createmenu method this event handler is called when the session store submenu opens. first, it deletes the menuitem elements that were dynamically generated the last ti...
... sessions—all work correctly. phase 3: creating a preference panel you don’t need to use ini files, registries, or anything like that to give users options they can set through a preference panel. firefox lets you read and write preference values using handy xpcom services and create preference panels with interface widgets. in phase 3, we’ll try this out (figure 15). fixme: figure 15: finished preference panel directory structure figure 16 shows the directory structure we’ll be using in phase 3. table 5 explains the new files being used. table 5: files used in phase 3 fixme: make the table cleaner name purpose sessionstore-prefs.js file sets defaults for preferences. this should always be located inside defaults\preferenc...
Migrate apps from Internet Explorer to Mozilla - Archive of obsolete content
script differently. for example, the following code assumes that the div node already exists in the dom by the time the script block executes: ... <div id="foo">loading...</div> <script> document.getelementbyid("foo").innerhtml = "done."; </script> however, this is not guaranteed. to be sure that all elements exist, you should use the onload event handler on the <body> tag: <body onload="dofinish();"> <div id="foo">loading...</div> <script> function dofinish() { var element = document.getelementbyid("foo"); element.innerhtml = "done."; } </script> ... such timing-related issues are also hardware-related -- slower systems can reveal bugs that faster systems hide. one concrete example is window.open, which opens a new window: <script> function doopenwindow(){ var mywi...
...slower systems can reveal bugs that faster systems hide. one concrete example is window.open, which opens a new window: <script> function doopenwindow(){ var mywindow = window.open("about:blank"); mywindow.location.href = "http://www.ibm.com"; } </script> the problem with the code is that window.open is asynchronous -- it does not block the javascript execution until the window has finished loading. therefore, you may execute the line after the window.open line before the new window has finished. you can deal with this by having an onload handler in the new window and then call back into the opener window (using window.opener). differences in javascript-generating html javascript can, through document.write, generate html on the fly from a string. the main issue here is when jav...
... description 0 uninitialized - open() has not been called yet. 1 loading - send() has not been called yet. 2 loaded - send() has been called, headers and status are available. 3 interactive - downloading, responsetext holds the partial data. 4 completed - finished with all operations. string responsetext string containing the response. domdocument responsexml dom document containing the response. void send(variant body) initiates the request. if body is defined, it is sent as the body of the post request. body can be an xml document or a string serialized xml document. void setrequesthead...
Monitoring downloads - Archive of obsolete content
if the download's state, indicated by the adownload.state field, is components.interfaces.nsidownloadmanager.download_downloading, the file has begun to do...
...n that case, we create a new row in our database for the new file by opening the database and building a replace into sqlite command. the first three rows are set to the values of the source uri, file size, and start time fields from the download object. the remaining rows are set to zeroes since that's not information we have at the moment. if the download's state indicates that the download is finished, canceled, or failed, we call our logtransfercompleted routine to update the log to indicate that state change. that code looks like this: logtransfercompleted: function(adownload) { var endtime = new date(); // current time is the end time // issue the replace sqlite command to update the record. we find a // record for the same source uri and start time, then...
... add searching. see also storage, nsidownloadmanager, nsidownload, nsidownloadprogresslistener ...
Index - Game development
2d, beginner, canvas, games, javascript, phaser, tutorial we have the ball moving and bouncing off the walls, but it quickly gets boring — there's no interactivity! we need a way to introduce gameplay, so in this article we'll create a paddle to move around and hit the ball with. 55 randomizing gameplay 2d, beginner, canvas, games, javascript, phaser, tutorial you've finished all the lessons — congratulations! by this point you would have learnt the basics of phaser and the logic behind simple 2d games. 56 scaling 2d, beginner, canvas, games, javascript, phaser, tutorial scaling refers to how the game canvas will scale on different screen sizes. we can make the game scale to fit on any screen size automatically during the preload stage, so we ...
...em. we need to think about adding collision detection so it can bounce off the bricks and break them. 63 create the canvas and draw on it 2d, beginner, canvas, games, html, javascript, tutorial before we can start writing the game's functionality, we need to create a basic structure to render the game inside. this can be done using html and the <canvas> element. 64 finishing up beginner, canvas, games, javascript, tutorial, lives, requestanimationframe there's always room for improvements in any game we write. for example, we can offer more than one life to the player. they could make a mistake or two and still be able to finish the game. we could also improve our code rendering. 65 game over beginner, canvas, games, graphics, javascript, ...
...g and doesn't have any progression or end goal. it would be good from the gameplay point of view to be able to lose. the logic behind losing in breakout is simple. if you miss the ball with the paddle and let it reach the bottom edge of the screen, then it's game over. 66 mouse controls beginner, canvas, controls, games, javascript, tutorial, mouse the game itself is actually finished, so let's work on polishing it up. we have already added keyboard controls, but we could easily add mouse controls too. 67 move the ball 2d, beginner, canvas, games, javascript, loop, tutorial, movement you already know how to draw a ball from working through the previous article, so now let's make it move. technically, we will be painting the ball on the screen, clearing i...
Test your skills: floats - Learn web development
or glitch to work on the tasks. if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page. floats one in this task you need to float the two elements with a class of float1 and float2 left and right respectively. the text should then appear between the two boxes as in the image below. try updating the live code below to recreate the finished example: for assessment or further work purposes, download the starting point for this task to work in your own editor or in an online editor. float two in this example the element with a class of float should be floated left. then we want the first line of text to display next to that element, but the following line of text (which has a class of .below) to display underneath it. you can...
...is task to work in your own editor or in an online editor. float two in this example the element with a class of float should be floated left. then we want the first line of text to display next to that element, but the following line of text (which has a class of .below) to display underneath it. you can see the desired result in this image. try updating the live code below to recreate the finished example: for assessment or further work purposes, download the starting point for this task to work in your own editor or in an online editor. float three finally, we have a floated element in this example. the box wrapping the float and text is displaying behind the float. use the most up to date method available to cause the box background to extend to below the float as in the image. ...
...ses, download the starting point for this task to work in your own editor or in an online editor. float three finally, we have a floated element in this example. the box wrapping the float and text is displaying behind the float. use the most up to date method available to cause the box background to extend to below the float as in the image. try updating the live code below to recreate the finished example: for assessment or further work purposes, download the starting point for this task to work in your own editor or in an online editor. assessment or further help you can practice these examples in the interactive editors mentioned above. if you would like your work assessed, or are stuck and want to ask for help: put your work into an online shareable editor such as codepen, ...
Test your skills: Grid Layout - Learn web development
f you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page. grid layout one in this task you should create a grid into which the four child elements will auto-place. the grid should have three columns sharing the available space equally, and a 20-pixel gap between the column and row tracks. try updating the live code below to recreate the finished example: for assessment or further work purposes, download the starting point for this task to work in your own editor or in an online editor. grid layout two in this example we already have a grid defined. by editing the css rules for the two child elements, cause them to span over several grid tracks each; the second item should overlay the first as in the image below. try updating ...
...rther work purposes, download the starting point for this task to work in your own editor or in an online editor. grid layout two in this example we already have a grid defined. by editing the css rules for the two child elements, cause them to span over several grid tracks each; the second item should overlay the first as in the image below. try updating the live code below to recreate the finished example: additional questions: can you now cause the first item to display on top without changing the order of items in the source? for assessment or further work purposes, download the starting point for this task to work in your own editor or in an online editor. grid layout three there are four direct children in this grid; the starting point has them displayed using auto-placem...
...sment or further work purposes, download the starting point for this task to work in your own editor or in an online editor. grid layout three there are four direct children in this grid; the starting point has them displayed using auto-placement. use the grid-area and grid-template-areas properties to lay the items out as shown in the image. try updating the live code below to recreate the finished example: for assessment or further work purposes, download the starting point for this task to work in your own editor or in an online editor. grid and flex layout 4 you will need to use both grid layout and flexbox to recreate the example as seen in the image. you do not need to make any changes to the html in order to do this. try updating the code below to create your example: ...
Test your skills: Multicol - Learn web development
, however it may be helpful to download the code and use an online tool such as codepen, jsfiddle, or glitch to work on the tasks. if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page. multicol one in this task you need to create three columns, with a 50px gap between each column. try updating the live code below to recreate the finished example: for assessment or further work purposes, download the starting point for this task to work in your own editor or in an online editor. multicol two create columns which have a minimum width of 200px. then, add a 5px, grey rule between each column, ensuring there is 10px of space between the edge of the rule and the column content. try updating the live code below to recreate ...
...xample: for assessment or further work purposes, download the starting point for this task to work in your own editor or in an online editor. multicol two create columns which have a minimum width of 200px. then, add a 5px, grey rule between each column, ensuring there is 10px of space between the edge of the rule and the column content. ...
... assessment or further help you can practice these examples in the interactive editors mentioned above. ...
Practical positioning examples - Learn web development
y common feature used when you want to pack a lot of information into a small area. this includes information-heavy apps like strategy/war games, mobile versions of websites where the screen is narrow and space is limited, and compact information boxes where you might want to make lots of information available without having it fill the whole ui. our simple example will look like this once we are finished: note: you can see the finished example running live at info-box.html (source code). check it out to get an idea of what you will be building in this section of the article. you might be thinking "why not just create the separate tabs as separate webpages, and just have the tabs clicking through to the separate pages to create the effect?" this code would be simpler, yes, but then each se...
... be adding to it in the second one. a fixed position tabbed info-box in our second example, we will take our first example — our info-box — and add it into the context of a full web page. but not only that — we'll give it fixed position so that it stays in the same position in the browser window. when the main content scrolls, the info-box will stay in the same position on the screen. our finished example will look like this: note: you can see the finished example running live at fixed-info-box.html (source code). check it out to get an idea of what you will be building in this section of the article. as a starting point, you can use your completed example from the first section of the article, or make a local copy of info-box.html from our github repo. html additions first of al...
...'ll find the third just as interesting. a sliding hidden panel the final example we'll present here is a panel that slides on and off the screen at the press of an icon — as mentioned earlier, this is popular for situations like mobile layouts, where the available screen spaces is small, so you don't want to use up most of it by showing a menu or info panel instead of the useful content. our finished example will look like this: note: you can see the finished example running live at hidden-info-panel.html (source code). check it out to get an idea of what you will be building in this section of the article. as a starting point, make a local copy of hidden-info-panel-start.html from our github repo. this doesn't follow on from the previous example, so a fresh start file is required. le...
Test your skills: Basic controls - Learn web development
ask starts you off nice and gently by asking you to create two <input> elements, for a user's id and password, along with a submit button. create appropriate inputs for user id and password. you should also associate them with their text labels semantically. create a submit button inside the remaining list item, with button text of "log in". try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor. basic controls 2 the next task requires you to create working sets of checkboxes and radio buttons, from the provided text labels. turn the first <fieldset>'s contents into a set of radio buttons — you should only be able to select one pony character at once. make it so that the fi...
...ons, from the provided text labels. turn the first <fieldset>'s contents into a set of radio buttons — you should only be able to select one pony character at once. make it so that the first radio button is selected upon page load. turn the second <fieldset>'s content into a set of checkboxes. add a couple more hotdog choices of your own. ...
... assessment or further help you can practice these examples in the interactive editors above. if you would like your work assessed, or are stuck and want to ask for help: put your work into an online shareable editor such as codepen, jsfiddle, or glitch. ...
Test your skills: Other controls - Learn web development
age. other controls 1 in our first "other controls" assessment, we'll get you to create a multi-line text input. create a basic multi-line text input. associate it semantically with the provided "comment" label. give the input 35 columns, and 10 rows of space in which to add comments. give the comments a maximum length of 100 characters. try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor. other controls 2 now it's time to have a go at implementing a drop-down select menu, to allow a user to pick their favourite food from the choices provided. create your basic select box structure. associate it semantically with the provided "comment" label. inside the list, split th...
.... other controls 2 now it's time to have a go at implementing a drop-down select menu, to allow a user to pick their favourite food from the choices provided. create your basic select box structure. associate it semantically with the provided "comment" label. inside the list, split the choices up into 2 subgroups — "mains" and "snacks". try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor. other controls 3 in our final task of this set, we start with much the same list of food choices. however, this time we want to do things differently: create a basic text input that is semantically associated with the provided label. put the food choices into a list that can be assoc...
...eate a basic text input that is semantically associated with the provided label. put the food choices into a list that can be associated with a form input. associate the list with your text input, so that when you type characters, any of the list options that match the character sequence are given in a dropdown list as autocomplete suggestions. try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor. assessment or further help you can practice these examples in the interactive editors above. if you would like your work assessed, or are stuck and want to ask for help: put your work into an online shareable editor such as codepen, jsfiddle, or glitch. you can write the code yoursel...
Test your skills: HTML text basics - Learn web development
helpful to download the code and use an online tool such as codepen, jsfiddle, or glitch to work on the tasks. if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page. html text basics 1 in this task we want you to mark up the provided html using semantic heading and paragraph elements. ...
...antic heading and paragraph elements. try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor. html text basics 2 in this task we want you to turn the first un-marked up list into an unordered list, and the second one into an ordered list. try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor. ...
... assessment or further help you can practice these examples in the interactive editors above. if you would like your work assessed, or are stuck and want to ask for help: put your work into an online shareable editor such as codepen, jsfiddle, or glitch. ...
Test your skills: Links - Learn web development
filled in as "question about whales". note: the first link in the example has the target="_blank" attribute set on it, so that when you click on it, it opens the page in a new tab. this is not strictly best practice, but we've done it here so that the page doesn't open in the embedded <iframe>, getting rid of your example code in the process! try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor. links 2 in this task we want you to fill in the four links so that they link to the appropriate places: the first link should link to an image called blue-whale.jpg, which is located in a directory called blue inside the current directory. the second link should link to an image call...
...as an id of bottom. note: the first three links in the example have the target="_blank" attribute set on them, so that when you click on them, they open the linked page in a new tab. this is not strictly best practice, but we've done it here so that the pages don't open in the embedded <iframe>, getting rid of your example code in the process! try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor. links 3 the following links link to an info page about narwhals, a support email address, and a pdf factfile that is 4mb in size. in this task we want you to: take the existing paragraphs with poorly-written link text, and rewrite them so that they have good link text. add a warning ...
... warning added. note: the first and third links in the example have the target="_blank" attribute set on them, so that when you click on them, they open the linked page in a new tab. this is not strictly best practice, but we've done it here so that the pages don't open in the embedded <iframe>, getting rid of your example code in the process! try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor. assessment or further help you can practice these examples in the interactive editors above. if you would like your work assessed, or are stuck and want to ask for help: put your work into an online shareable editor such as codepen, jsfiddle, or glitch. you can write the code yoursel...
Test your skills: HTML images - Learn web development
the current folder called images. add some alternative text to an appropriate attribute to describe the image, for people that cannot see it. give the <img> element an appropriate width and height so that it displays at the correct aspect ratio, and enough space is left on the page to display it. the image's intrinsic size is 615 x 419 pixels. ...
...e below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor. html images 2 in this task you already have a full-featured image, but we'd like you to add a tooltip that appears when the image is moused over. you should put some appropriate information into the tooltip. try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor. html images 3 in this final task you are provided with both a full-featured image and some caption text. what you need to do here is add elements that will associate the image with the caption. ...
... assessment or further help you can practice these examples in the interactive editors above. ...
Test your skills: Multimedia and embedding - Learn web development
to the page. you need to: add the path to the audio file to an appropriate attribute to embed it on the page. the audio is called audio.mp3, and it is in a folder inside the current folder called media. add an attribute to make browsers display some default controls. add some appropriate fallback text for browsers that don't support <audio>. try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor. multimedia and embedding 2 in this task we want you to mark up a slightly more complex video player, with multiple sources, subtitles, and other features besides. you need to: add an attribute to make browsers display some default controls. add some appropriate fallback text for brow...
...o download ahead of time. give the <video> a width and height equal to its intrinsic size (320 by 240 pixels). make the video muted by default. display the text tracks contained in the media folder, in a file called subtitles_en.vtt, when the video is playing. you must explicitly set the type as subtitles, and the subtitle language to english. try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor. multimedia and embedding 3 for this final task you have two tasks to do: embed a pdf into the page. the pdf is called mypdf.pdf, and is contained in the media folder. go to a sharing site like youtube or google maps, and embed a video or other media item into the page. try updating...
... point for this task to work in your own editor or in an online editor. multimedia and embedding 3 for this final task you have two tasks to do: embed a pdf into the page. the pdf is called mypdf.pdf, and is contained in the media folder. go to a sharing site like youtube or google maps, and embed a video or other media item into the page. try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor. assessment or further help you can practice these examples in the interactive editors above. if you would like your work assessed, or are stuck and want to ask for help: put your work into an online shareable editor such as codepen, jsfiddle, or glitch. you can write the code yoursel...
HTML table advanced features and accessibility - Learn web development
k at the result. if the <tbody> and <tfoot> elements weren't in place, you'd have to write much more complicated selectors/rules to apply the same styling. note: we don't expect you to fully understand the css right now. you'll learn more about this when you go through our css modules (introduction to css is a good place to start; we also have an article specifically on styling tables). ...
... nesting tables it is possible to nest a table inside another one, as long as you include the complete structure, including the <table> element. this is generally not really advised, as it makes the markup more confusing and less accessible to screenreader users, and in many cases you might as well just insert extra cells/rows/columns into the existing table. it is ho...
... for this final exercise, we'd like you to first make local copies of items-sold.html and minimal-table.css, in a new directory. now try adding in the appropriate scope attributes to make this table more appropriate. finally, try making another copy of the starter files, and this time make the table more accessible using id and headers attributes. note: you can check your work against our finished examples — see items-sold-scope.html (also see this live) and items-sold-headers.html (see this live too). summary there are a few other things you could learn about table html, but we have really given all you need to know at this moment in time. at this point, you might want to go and learn about styling html tables — see styling tables. previous overview: tables next in thi...
HTML table basics - Learn web development
Learn › HTML › Tables › Basics
e above on this page has minimal styling, whereas the github version has more significant css applied. be under no illusion; for tables to be effective on the web, you need to provide some styling information with css, as well as good solid structure with html. in this module we are focusing on the html part; to find out about the css part you should visit our styling tables article after you've finished here. we won't focus on css in this module, but we have provided a minimal css stylesheet for you to use that will make your tables more readable than the default you get without any styling. you can find the stylesheet here, and you can also find an html template that applies the stylesheet — these together will give you a good starting point for experimenting with html tables. when should...
...ntically, you can use the <th> element ('th' stands for 'table header'). this works in exactly the same way as a <td>, except that it denotes a header, not a normal cell. go into your html, and change all the <td> elements surrounding the table headers into <th> elements. save your html and load it in a browser, and you should see that the headers now look like headers. note: you can find our finished example at dogs-table-fixed.html on github (see it live also). why are headers useful? we have already partially answered this question — it is easier to find the data you are looking for when the headers clearly stand out, and the design just generally looks better. note: table headings come with some default styling — they are bold and centered even if you don't add your own styling ...
...-table.html and minimal-table.css files in a new directory on your local machine. the html contains the same animals example as you saw above. next, use colspan to make "animals", "hippopotamus", and "crocodile" span across two columns. finally, use rowspan to make "horse" and "chicken" span across two rows. save and open your code in a browser to see the improvement. note: you can find our finished example at animals-table-fixed.html on github (see it live also). providing common styling to columns there is one last feature we'll tell you about in this article before we move on. html has a method of defining styling information for an entire column of data all in one place — the <col> and <colgroup> elements. these exist because it can be a bit annoying and inefficient having to s...
Making asynchronous programming easier with async and await - Learn web development
keyword blocks execution of all the code that follows until the promise fulfills, exactly as it would with a synchronous operation. it does allow other tasks to continue to run in the meantime, but your own code is blocked. this means that your code could be slowed down by a significant number of awaited promises happening straight after one another. each await will wait for the previous one to finish, whereas actually what you want is for the promises to begin processing simultaneously, like they would do if we weren't using async/await. there is a pattern that can mitigate this problem — setting off all the promise processes by storing the promise objects in variables, and then awaiting them all afterwards. let's have a look at some examples that prove the concept. we've got two examples...
...e"); }, interval); }); }; then each one includes a timetest() async function that awaits three timeoutpromise() calls: async function timetest() { ... } each one ends by recording a start time, seeing how long the timetest() promise takes to fulfill, then recording an end time and reporting how long the operation took in total: let starttime = date.now(); timetest().then(() => { let finishtime = date.now(); let timetaken = finishtime - starttime; alert("time taken in milliseconds: " + timetaken); }) it is the timetest() function that differs in each case. in the slow-async-await.html example, timetest() looks like this: async function timetest() { await timeoutpromise(3000); await timeoutpromise(3000); await timeoutpromise(3000); } here we simply await all three timeo...
...s the timetest() function that differs in each case. in the slow-async-await.html example, timetest() looks like this: async function timetest() { await timeoutpromise(3000); await timeoutpromise(3000); await timeoutpromise(3000); } here we simply await all three timeoutpromise() calls directly, making each one alert for 3 seconds. each subsequent one is forced to wait until the last one finished — if you run the first example, you'll see the alert box reporting a total run time of around 9 seconds. in the fast-async-await.html example, timetest() looks like this: async function timetest() { const timeoutpromise1 = timeoutpromise(3000); const timeoutpromise2 = timeoutpromise(3000); const timeoutpromise3 = timeoutpromise(3000); await timeoutpromise1; await timeoutpromise2;...
Test your skills: Events - Learn web development
ully answer the questions. a good starting place is our manipulating documents tutorial. events 1 in our first events-related task, you need to create a simple event handler that causes the text inside the button (btn) to change when it is clicked on, and change back when it is clicked again. the html should not be changed; just the javascript. try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor. events 2 now we'll look at keyboard events. to pass this assessment you need to build an event handler that moves the circle around the provided canvas when the wasd keys are pressed on the keyboard. the circle is drawn with the function drawcircle(), which takes the folllowing parameter...
...you need to build an event handler that moves the circle around the provided canvas when the wasd keys are pressed on the keyboard. the circle is drawn with the function drawcircle(), which takes the folllowing parameters as inputs: x — the x coordinate of the circle. y — the y coordinate of the circle. size — the radius of the circle. try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor. events 3 in our final events-related task, you need to set an event listener on the <button>s' parent element (<div class="button-bar"> ... </div>), which when invoked by clicking any of the buttons will set the background of the button-bar to the color contained in the button's data-col...
...nt listener on the <button>s' parent element (<div class="button-bar"> ... </div>), which when invoked by clicking any of the buttons will set the background of the button-bar to the color contained in the button's data-color attribute. we want you to solve this without looping through all the buttons and giving each one their own event listener. try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor. assessment or further help you can practice these examples in the interactive editors above. if you would like your work assessed, or are stuck and want to ask for help: put your work into an online shareable editor such as codepen, jsfiddle, or glitch. you can write the code yoursel...
Test your skills: Functions - Learn web development
o some research into what dom apis you need to successfully answer the questions. a good starting place is our manipulating documents tutorial. functions 1 for the first task, you have to create a simple function — choosename() — that prints a random name from the provided array (names) to the provided paragraph (para), and then run it once. try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor. functions 2 for our second functions-related task, you need to create a function that draws a rectangle on the provided <canvas> (reference variable canvas, context available in ctx), based on the five provided input variables: x — the x coordinate of the rectangle. y — the y coo...
...rectangle. y — the y coordinate of the rectangle. width — the width of the rectangle. height — the height of the rectangle. color — the color of the rectangle. you'll want to clear the canvas before drawing, so that when the code is updated in the case of the live version, you don't get lots of rectangles drawn on top of one another. try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor. functions 3 in this task, you return to the problem posed in task 1, with the aim of improving it. the three improvements we want you to make are: refactor the code that generates the random number into a separate function called random(), which takes as parameters two generic bounds ...
... parameters two generic bounds that the random number should be between, and returns the result. update the choosename() function so that it makes use of the random number function, takes the array to choose from as a parameter (making it more flexible), and returns the result. print the returned result into the paragraph (para)'s textcontent. try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor. assessment or further help you can practice these examples in the interactive editors above. if you would like your work assessed, or are stuck and want to ask for help: put your work into an online shareable editor such as codepen, jsfiddle, or glitch. you can write the code yoursel...
Fetching data from the server - Learn web development
rver. to find out how to do this, read how do you set up a local testing server? fetch the fetch api is basically a modern replacement for xhr; it was introduced in browsers recently to make asynchronous http requests easier to do in javascript, both for developers and other apis that build on top of fetch. let's convert the last example to use fetch instead. make a copy of your previous finished example directory. (if you didn't work through the previous exercise, create a new directory and inside it make copies of xhr-basic.html and the four text files — verse1.txt, verse2.txt, verse3.txt, and verse4.txt.) inside the updatedisplay() function, find the xhr code: let request = new xmlhttprequest(); request.open('get', url); request.responsetype = 'text'; request.onload = fun...
...ook at the promise structure from above again to see if we can make some more sense of it: fetch(url).then(function(response) { response.text().then(function(text) { poemdisplay.textcontent = text; }); }); the first line is saying "fetch the resource located at url" (fetch(url)) and "then run the specified function when the promise resolves" (.then(function() { ... })). "resolve" means "finish performing the specified operation at some point in the future". the specified operation, in this case, is to fetch a resource from a specified url (using an http request), and return the response for us to do something with. effectively, the function passed into then() is a chunk of code that won't run immediately. instead, it will run at some point in the future when the response has been retu...
...promise then(). about the best equivalent to fetch's response.ok in xhr is to check whether request.status is equal to 200, or if request.readystate is equal to 4. the properties for getting the status and status message are the same, but they are found on the request (xhr) object, not the response object. note: if you have trouble with this, feel free to check your code against the finished version on github (see the source here, and also see it running live). summary this article shows how to start working with both xhr and fetch to fetch data from the server. ...
Video and Audio APIs - Learn web development
t api part of the html5 spec, the htmlmediaelement api provides features to allow you to control video and audio players programmatically — for example htmlmediaelement.play(), htmlmediaelement.pause(), etc. this interface is available to both <audio> and <video> elements, as the features you'll want to implement are nearly identical. let's go through an example, adding features as we go. our finished example will look (and function) something like the following: getting started to get started with this example, download our media-player-start.zip and unzip it into a new directory on your hard drive. if you downloaded our examples repo, you'll find it in javascript/apis/video-audio/start/ at this point, if you load the html you should see a perfectly normal html5 video player, with the ...
...users focus on the elements that contain them. there is also a timer <div>, which will report the elapsed time when the video is playing. just for fun, we are providing two reporting mechanisms — a <span> containing the elapsed time in minutes and seconds, and an extra <div> that we will use to create a horizontal indicator bar that gets longer as the time elapses. to get an idea of what the finished product will look like, check out our finished version. exploring the css now open the css file and have a look inside. the css for the example is not too complicated, but we'll highlight the most interesting bits here. first of all, notice the .controls styling: .controls { visibility: hidden; opacity: 0.5; width: 400px; border-radius: 10px; position: absolute; bottom: 20p...
...et's add functionality to handle stopping the video. add the following addeventlistener() lines below the previous one you added: stop.addeventlistener('click', stopmedia); media.addeventlistener('ended', stopmedia); the click event is obvious — we want to stop the video by running our stopmedia() function when the stop button is clicked. we do however also want to stop the video when it finishes playing — this is marked by the ended event firing, so we also set up a listener to run the function on that event firing too. next, let's define stopmedia() — add the following function below playpausemedia(): function stopmedia() { media.pause(); media.currenttime = 0; play.setattribute('data-icon','p'); } there is no stop() method on the htmlmediaelement api — the eq...
Test your skills: Arrays - Learn web development
basic array practice. in this task we'd like you to create an array of three items, stored inside a variable called myarray. the items can be anything you want — how about your favourite foods or bands? next, modify the first two items in the array using simple bracket notation and assignment. then add a new item to the beginning of the array. try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor. arrays 2 now let's move on to another task. here you are provided with a string to work with. we'd like you to: convert the string into an array, removing the + characters in the process. save the result in a variable called myarray. store the length of the array in a variable called...
... move on to another task. here you are provided with a string to work with. we'd like you to: convert the string into an array, removing the + characters in the process. save the result in a variable called myarray. store the length of the array in a variable called arraylength. store the last item in the array in a variable called lastitem. try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor. arrays 3 for this final array task, we provide you with a starting array, and you will work in somewhat the opposite direction. you need to: remove the last item in the array. add two new names to the end of the array. go over each item in the array and add its index number after th...
...ew names to the end of the array. go over each item in the array and add its index number after the name inside parentheses, for example ryu (0). note that we don't teach how to do this in the arrays article, so you'll have to do some research. finally, join the array items together in a single string called mystring, with a separator of " - ". try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor. assessment or further help you can practice these examples in the interactive editors above. if you would like your work assessed, or are stuck and want to ask for help: put your work into an online shareable editor such as codepen, jsfiddle, or glitch. you can write the code yoursel...
Test your skills: variables - Learn web development
browser's javascript console, in the case of the downloadable version). variables 1 in this task we want you to: declare a variable called myname. initialize myname with a suitable value, on a separate line (you can use your actual name, or something else). declare a variable called myage and initialize it with a value, on the same line. ...
... variables 3 the final task for now — in this case you are provided with some existing code, which has two errors present in it. ...
...ork in your own editor or in an online editor. variables 3 the final task for now — in this case you are provided with some existing code, which has two errors present in it. the results panel should be outputting the name chris, and a statement about how old chris will be in 20 years' time. how can you fix the problem and correct the output? try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor. assessment or further help you can practice these examples in the interactive editors above. if you would like your work assessed, or are stuck and want to ask for help: put your work into an online shareable editor such as codepen, jsfiddle, or glitch. you can write the code yoursel...
Inheritance in JavaScript - Learn web development
the easiest way to do this is to define it on teacher()'s prototype — add the following at the bottom of your code: teacher.prototype.greeting = function() { let prefix; if (this.gender === 'male' || this.gender === 'male' || this.gender === 'm' || this.gender === 'm') { prefix = 'mr.'; } else i...
...on() constructor (class). the query on line 4 accesses a member that is available only on the more specialized teacher() constructor (class). the query on line 5 would have accessed a member inherited from person(), except for the fact that teacher() has its own member with the same name, so the query accesses that member. note: if you have trouble getting this to work, compare your code to our finished version (see it running live also). the technique we covered here is not the only way to create inheriting classes in javascript, but it works ok, and it gives you a good idea about how to implement inheritance in javascript. you might also be interested in checking out some of the new ecmascript features that allow us to do inheritance more cleanly in javascript (see classes). we didn't cov...
...n, and also has a different greeting() method from person that is much more informal than the teacher's greeting. have a look at what the student's greeting looks like in that section, and try implementing your own student() constructor that inherits all the features of person(), and implements the different greeting() function. note: if you have trouble getting this to work, have a look at our finished version (see it running live also). object member summary to summarize, you've got four types of property/method to worry about: those defined inside a constructor function that are given to object instances. these are fairly easy to spot — in your own custom code, they are the members defined inside a constructor using the this.x = x type lines; in built in browser code, they are the m...
Object-oriented JavaScript for beginners - Learn web development
me: 'bob', greeting: function() { alert('hi! i\'m ' + this.name + '.'); } } { name: 'sarah', greeting: function() { alert('hi! i\'m ' + this.name + '.'); } } note that when we are calling our constructor function, we are defining greeting() every time, which isn't ideal. to avoid this, we can define functions on the prototype instead, which we will look at later. creating our finished constructor the example we looked at above was only a simple example to get us started. let's now get on and create our final person() constructor function. remove the code you inserted so far, and add in this replacement constructor — this is exactly the same as the simple example in principle, with just a bit more complexity: function person(first, last, age, gender, interests) { th...
...stance from it: let person1 = new person('bob', 'smith', 32, 'male', ['music', 'skiing']); you can now see that you can access the properties and methods just like we did previously — try these in your js console: person1['age'] person1.interests[1] person1.bio() // etc. note: if you are having trouble getting this to work, try comparing your code against our version — see oojs-class-finished.html (also see it running live). further exercises to start with, try adding a couple more object creation lines of your own, and try getting and setting the members of the resulting object instances. in addition, there are a couple of problems with our bio() method — the output always includes the pronoun "he", even if your person is female, or some other preferred gender classification.
... one place, then create instances as needed, and it is clear where they came from. however, some people prefer to create object instances without first creating constructors, especially if they are creating only a few instances of an object. javascript has a built-in method called create() that allows you to do that. with it, you can create a new object based on any existing object. with your finished exercise from the previous sections loaded in the browser, try this in your javascript console: let person2 = object.create(person1); now try these: person2.name; person2.greeting(); you'll see that person2 has been created based on person1—it has the same properties and method available to it. one limitation of create() is that ie8 does not support it. so constructors may be more...
Object building practice - Learn web development
s (see introduction to objects). objective: to get some practice with using objects and object-oriented techniques in a real world context. let's bounce some balls in this article we will write a classic "bouncing balls" demo, to show you how useful objects can be in javascript. our little balls will bounce around on the screen, and change color when they touch each other. the finished example will look a little something like this: this example will make use of the canvas api for drawing the balls to the screen, and the requestanimationframe api for animating the whole display — you don't need to have any previous knowledge of these apis, and we hope that by the time you've finished this article you'll be interested in exploring them more. along the way we'll make us...
...the start and end number of degrees around the circle that the arc is drawn between. here we specify 0 degrees, and 2 * pi, which is the equivalent of 360 degrees in radians (annoyingly, you have to specify this in radians). that gives us a complete circle. if you had specified only 1 * pi, you'd get a semi-circle (180 degrees). last of all, we use the fill() method, which basically states "finish drawing the path we started with beginpath(), and fill the area it takes up with the color we specified earlier in fillstyle." you can start testing your object out already. save the code so far, and load the html file in a browser. open the browser's javascript console, and then refresh the page so that the canvas size changes to the smaller visible viewport that remains when the console o...
...y such as physicsjs, matter.js, phaser, etc. you also need to call this method in each frame of the animation. add the following below the balls[i].update(); line: balls[i].collisiondetect(); save and refresh the demo again, and you'll see your balls change color when they collide! note: if you have trouble getting this example to work, try comparing your javascript code against our finished version (also see it running live). summary we hope you had fun writing your own real world random bouncing balls example, using various object and object-oriented techniques from throughout the module! this should have given you some useful practice in using objects, and good real world context. that's it for object articles — all that remains now is for you to test your skills in the ob...
Test your skills: Object-oriented JavaScript - Learn web development
re. give it a name of square and a sidelength of 5. call your calcperimeter() method on the instance, to see whether it logs the calculation result to the browser devtools' console as expected. create a new instance of shape called triangle, with a name of triangle and a sidelength of 3. call triangle.calcperimeter() to check that it works ok. try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor. oojs 2 next up we want you to take the shape class you saw in task #1 (including the calcperimeter() method) and recreate it using es class syntax instead. test that it works by creating the square and triangle object instances as before (using new shape() for both), and then calling th...
...ditor or in an online editor. oojs 2 next up we want you to take the shape class you saw in task #1 (including the calcperimeter() method) and recreate it using es class syntax instead. test that it works by creating the square and triangle object instances as before (using new shape() for both), and then calling their calcperimeter() methods. try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor. oojs 3 finally, we'd like you to start with the es shape class you created in the last task. we'd like you to create a square class that inherits from shape, and adds a calcarea() method that calculates the square's area. also set up the constructor so that the name property of square o...
...ces is automatically set to square, and the sides property is automatically set to 4. when invoking the constructor, you should therefore just need to provide the sidelength property. create an instance of the square class called square with appropriate property values, and call its calcperimeter() and calcarea() methods to show that it works ok. try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor. assessment or further help you can practice these examples in the interactive editors above. if you would like your work assessed, or are stuck and want to ask for help: put your work into an online shareable editor such as codepen, jsfiddle, or glitch. you can write the code yoursel...
Test your skills: Object basics - Learn web development
version). object basics 1 in this task you are provided with an object literal, and your tasks are to store the value of the name property inside the catname variable, using bracket notation. run the greeting() method using dot notation (it will log the greeting to the browser devtools' console). update the color property value to black. try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor. object basics 2 in our next task, we want you to have a go at creating your own object literal to represent one of your favourite bands. the required members are: name: a string representing the band name. nationality: a string representing the country the band comes from. genre: wh...
...sed: a number representing the year the album was released. include at least two albums in the albums array. once you've done this, you should then write a string to the variable bandinfo, which will contain a small biography detailing their name, nationality, years active, and style, and the title and release date of their first album. try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor. object basics 3 finally for our object basics assessment, we want you to return to the cat object literal from task #1. we want you to rewrite the greeting() method so that it logs "hello, said bertie the cymric." to the browser devtools' console, but in a way that will work across any c...
...() methods to check that they log appropriate greetings to the console. the code is not very dry (each bit of code should only be defined once) — you've got the same method defined twice, for example. describe how you'd make it more dry? if you are not sure, then don't worry — this is what we'll be looking at in future articles in the series! try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor. assessment or further help you can practice these examples in the interactive editors above. if you would like your work assessed, or are stuck and want to ask for help: put your work into an online shareable editor such as codepen, jsfiddle, or glitch. you can write the code yoursel...
Strategies for carrying out testing - Learn web development
etting up google analytics first of all, you'll need a google account. use this account to sign into google analytics. choose the google analytics (web) option, and click the sign up button. enter your web site/app details into the signup page. this is fairly intuitive to set up; the most important field to get right is the website url. this needs to be your site/app's root url. once you've finished filling in everything, press the get tracking id button, then accept the terms of service that appear. the next page provides you with some code snippets and other instructions. for a basic website, what you need to do is copy the website tracking code block and paste it into all the different pages you want to track using google analytics on your site. you could place the snippets below your ...
... are also commercial tools available such as sauce labs, browser stack and lambdatest that do this kind of thing for you, without you having to worry about the setup, if you wish to invest some money in your testing. another alternative is to use no-code test automation tools such as endtest. we will look at how to use such tools later on in the module. user testing before we move on, we'll finish this article off by talking a bit about user testing — this can be a good option if you have a willing user group to test your new functionality on. bear in mind that this can be as lo-fi or as sophisticated as you like — your user group could be a group of friends, a group of colleagues, or a group of unpaid or paid volunteers, depending on whether you have any money to spend on testing. ge...
...as sophisticated as you like — your user group could be a group of friends, a group of colleagues, or a group of unpaid or paid volunteers, depending on whether you have any money to spend on testing. generally you'll get your users to look at the page or view containing the new functionality on some kind of a development server, so you are not putting the final site or change live until it is finished. you should get them to follow some steps and report the results they get. it is useful to provide a set of steps (sometimes called a script) so that you get more reliable results pertaining to what you were trying to test. we mentioned this in the what are you going to test section above — it is easy to turn the test criteria detailed there into steps to follow. for example, the following wo...
Gecko info for Windows accessibility vendors
ntent window, you may use accessibleobjectfromwindow() to get the root iaccessible for the content, and begin traversing the tree from there. gecko also helps determine when to load a new window by firing two event_state_change's on the root role_document accessible -- the first state change indicates the document pane is now busy loading. the second state change indicates the document pane has finished. when handling the event, use get_accstate() to check the state_busy flag. when the document has finished loading the busy flag will be cleared. msaa support: iaccessible methods to use msaa with gecko, you'll need the tools and docs that come with the active accessibility 2.0 sdk tools. the method accessibleobjectfromwindow() will get you the root iaccessible corresponding to the top level...
...ed for focus changes on any kind of focusable object event_statechange is used in check boxes, radio buttons, text fields, combo boxes and list boxes. it's also used in the root pane object to show when the state_busy flag changes from loading new content. event_scrollingend is used to indicate when a document has scrolled, even if only 1 line. gecko fires this event when the scrolling is finished, rather than fire excessive events. event_scrollingstart is fired when the user has jumped to a named anchor within the page. the event is fired on the first accessible object in the part of the document that has been jumped to. event_menupopupstart and event_menupopupend are fired when xul menus are opened or closed. event_menustart and event_menuend are fired when the xul menubar ...
...nique features role_document default role for root object of document dhtml: role="wairole:document" sets state_readonly indicates it is a normal document, otherwise we're in an editor. sets state_busy when a new document is loading in this space. fires event_state_change when busy flag is set or cleared due to document load starting or finishing. accvalue() exposes the url of the current pane. accname() exposes the <title> of the current pane. role_pane the first child of a <frame> or <iframe> accvalue() exposes the url of the current document. accname() exposes the <title> of the current pane. sets state_readonly unless it's an editable frame via designmode. ...
UpdateListener
you like. for each individual update check, the following methods will be called on the listener: either oncompatibilityupdateavailable() or onnocompatibilityupdateavailable(), depending on whether compatibility information for the requested application version was seen. either onupdateavailable() or onnoupdateavailable(), depending on whether a newer version of the addon was found. ...
...ther a newer version of the addon was found. onupdatefinished() to signal that the update check has completed. method overview void oncompatibilityupdateavailable(in addon addon) void onnocompatibilityupdateavailable(in addon addon) void onupdateavailable(in addon addon, in addoninstall install) void onnoupdateavailable(in addon addon) void onupdatefinished(in addon addon, in integer error) methods oncompatibilityupdateavailable() called when the update check found compatibility information for the application and platform version that the update check was being performed for. void oncompatibilityupdateavailable( in addon addon ) parameters addon the addon that was being checked for updates onnocompatibilityupdateavailable() c...
...d onupdateavailable( in addon addon, in addoninstall install ) parameters addon the addon that was being checked for updates install an addoninstall for the updated version onnoupdateavailable() called when no new version of an add-on has been found for install. void onnoupdateavailable( in addon addon ) parameters addon the addon that was being checked for updates onupdatefinished() called when the update check is complete. void onupdatefinished( in addon addon, in integer error ) parameters addon the addon that was being checked for updates error any error from the update checkaddon ...
Sqlite.jsm
y. these functions receive the following arguments: sql (required) string sql statement to execute. the trailing semicolon is not required. params (optional) parameters to bind to this statement. this can be an array or an object. see notes below. onrow (optional) function that is called when a row has been received. the return value is a promise that is resolved when the statement has finished execution. when a statement is executed via executecached(), the prepared statement object is cached inside the opened connection. the next time this same sql statement is executed (the sql argument is identical to one passed in before), the old statement object is reused. this saves time associated with parsing the sql statement and creating a new statement object. the downside is the cached ...
...the sql argument is identical to one passed in before), the old statement object is reused. this saves time associated with parsing the sql statement and creating a new statement object. the downside is the cached statement object lingers in the opened connection, taking up memory. when a statement is executed via execute(), the underlying statement object is thrown away as soon as the statement finishes execution. executecached() is recommended for statements that will be executed many times. execute() is recommended for statements that will be executed seldomly or once. please note that callers don't need to prepare statements manually before execution. just call executecached() and the statement will be prepared for you automatically. parameters can be bound to the statement by defining t...
...he execution of the statement. when cancelled, subsequent rows will not be processed and no more onrow invocations will be made. if an exception is thrown by the onrow handler, the exception is logged and processing of subsequent rows occurs as if nothing happened. the promise is still resolved (not rejected). the return promise will be rejected with an error instance if the statement did not finish execution fully. the error may have an errors property. if defined, it will be an array of objects describing individual errors. each object has the properties result and message. result is a numeric error code and message is a string description of the problem. if onrow is specified, the returned promise will be resolved with a boolean indicating whether the onrow handler was called. else, the ...
Localizing with Mercurial
open your command line tool and navigate to your l10n directory. inside your l10n directory, init your repo with mq by running hg init --mq. to create a new patch, run hg qnew -m "your commit message" patch-name.patch. the commit message should take the form of "bug 123456 - change this thing to work better by doing something; r=reviewers" if you are to fix a bug. make your change. once you finish making your change, run hg qrefresh to commit your changes to the patch. navigate to your <repository>/.hg/patches to find your .patch. you may repeat from step 4 to create another patch. your patches will be incremental, i.e. new patches are created based on old patches. if you want to commit all the patches to the repository and cleanup the patch queue, run hg qfinish. please refer to mqtut...
...es to mozilla now that you have hg account privileges, you can send your work to mozilla all by yourself. here are the steps to send your l10n work using mercurial: since your l10n work takes place in your own local repository, you should ensure that there are no changes made to the remote repository before committing your work. to do this, update your locale, as per the section above. after finishing a change or set of changes and checking you have updated to the latest, you should commit by entering this command: hg commit -m "your message identifying the change (bug 555)" committing won’t send your changes to mozilla’s repository, but prepares them for it. the next step will send your changes to your remote repo via push. to push to mozilla-hosted repositories, you have to have...
...take a break and grab a snack, you deserve it ...
Shell global objects
le object. it should be implemented by the module loader. getmoduleloadpath() return any --module-load-path argument passed to the shell. used by the module loader. parse(code) parses a string, potentially throwing. syntaxparse(code) check the syntax of a string, returning success value offthreadcompilescript(code[, options]) compile code on a helper thread. to wait for the compilation to finish and run the code, call runoffthreadscript. if present, options may have properties saying how the code should be compiled: noscriptrval use the no-script-rval compiler option (default: false) filename filename for error messages and debug info linenumber starting line number for error messages and debug info columnnumber starting column number for error messages and debug info ...
...fined, the name of property of element that holds this code. this is what debugger.source.prototype.elementattributename returns. runoffthreadscript() wait for off-thread compilation to complete. if an error occurred, throw the appropriate exception; otherwise, run the script and return its value. offthreadcompilemodule(code) compile code on a helper thread. to wait for the compilation to finish and get the module object, call finishoffthreadmodule. finishoffthreadmodule() wait for off-thread compilation to complete. if an error occurred, throw the appropriate exception; otherwise, return the module object timeout([seconds], [func]) get/set the limit in seconds for the execution time for the current context. a negative value (default) means that the execution time is unlimited. if a ...
...2: (alloc) collect when every n allocations (default: 100) 3: (framegc) collect when the window paints (browser only) 4: (verifierpre) verify pre write barriers between instructions 5: (frameverifierpre) verify pre write barriers between paints 6: (stackrooting) verify stack rooting 7: (generationalgc) collect the nursery every n nursery allocations 8: (incrementalrootsthenfinish) incremental gc in two slices: 1) mark roots 2) finish collection 9: (incrementalmarkallthenfinish) incremental gc in two slices: 1) mark all 2) new marking and finish 10: (incrementalmultipleslices) incremental gc in multiple slices 11: (incrementalmarkingvalidator) verify incremental marking 12: (elementsbarrier) always use the individual element post-write barrier, regardless...
nsIAlertsService
pointer. prior to gecko 32 the text was made to look like a link. cookie optional a blind cookie the alert passes back to the consumer during alert listener callbacks. alertlistener optional an object to receive callbacks from the alert; may be null if you don't care about callbacks. it must implement an observe() method that accepts three parameters: subject: always null. topic: "alertfinished" when the alert disappears, "alertclickcallback" if the user clicks the text or "alertshow" (since gecko 22) when the alert is shown. data: the value of the cookie parameter passed into the showalertnotification method. name optional a name for the notification; this is not displayed in the alert. however, certain notification systems (such as growl on mac os x) allow the user to disab...
...click here to focus the tab', true, null, notiflistener, 'stackoverflow notifier'); closealert() closes alerts created by the service. void closealert( in astring name, optional in nsiprincipal p...
...click here to focus the tab', true, null, notiflistener, 'stackoverflow notifier'); closealert() closes alerts created by the service. void closealert( in astring name, optional in nsiprincipal principal optional ); parameters name the n...
nsIScriptableUnicodeConverter
irefox 1.5 / thunderbird 1.5 / seamonkey 1.0) implemented by: @mozilla.org/intl/scriptableunicodeconverter. ...
... octet adata); nsiinputstream converttoinputstream(in astring astring); attributes attribute type description charset string current character set. throws ns_error_uconv_noconv if the requested charset is not supported. methods convertfromunicode() converts the data from unicode to one charset. returns the converted string. after converting, finish should be called and its return value appended to this return value. acstring convertfromunicode( in astring asrc ); finish() returns the terminator string. should be called after convertfromunicode() and appended to that function's return value. acstring finish(); converttounicode() converts the data from one charset to unicode. astring converttounicode( in acstring asrc ); conver...
... void converttobytearray(in astring astring, out unsigned long alen, optional [array, size_is(alen),retval] out octet adata ); converttoinputstream() converts a unicode string to an input stream. the bytes in the stream are encoded according to the charset attribute. the returned stream is non-blocking. ...
NS_CStringContainerInit
de. remarks this function is equivalent to ns_cstringcontainerinit2(container, nsnull, 0, 0). the nscstringcontainer structure has private members that should not be accessed directly. after a nscstringcontainer object has been initialized via ns_cstringcontainerinit, it may be used as an ordinary nsacstring object. with ns_cstringcontainerinit, the coder is required to call ns_cstringcontainerfinish when done with the nscstringcontainer object. therefore, it is generally better to use nsembedcstring, to instantiate a nsacstring object, since it automatically releases allocated memory when the object goes out of scope. example nscstringcontainer str; if (ns_succeeded(ns_cstringcontainerinit(str))) { // now, |str| can be used with any function taking a nsacstring parameter. // call thi...
... to use nsembedcstring, to instantiate a nsacstring object, since it automatically releases allocated memory when the object goes out of scope. ...
...out of scope. example nscstringcontainer str; if (ns_succeeded(ns_cstringcontainerinit(str))) { // now, |str| can be used with any function taking a nsacstring parameter. ...
NS_StringContainerInit
t returns an error code. remarks the nsstringcontainer structure has unspecified size and layout. its members may not be accessed directly. after a nsstringcontainer object has been initialized, it may be used as an ordinary nsastring object. the internal buffer allocated by a nsstringcontainer is always null-terminated. with ns_stringcontainerinit, the coder is required to call ns_stringcontainerfinish when done with the nsstringcontainer object. therefore, it is generally better to use nsembedstring, to instantiate a nsastring object, since it automatically releases allocated memory when the object goes out of scope. example code nsstringcontainer str; if (ns_succeeded(ns_stringcontainerinit(str))) { // now, |str| can be used with any function taking a nsastring parameter. // be...
...ng, to instantiate a nsastring object, since it automatically releases allocated memory when the object goes out of scope. ...
...example code nsstringcontainer str; if (ns_succeeded(ns_stringcontainerinit(str))) { // now, |str| can be used with any function taking a nsastring parameter. ...
XPCOM string functions
; however, it's often better to use one of the string classes rather than directly using these functions. ns_cstringappenddatathe ns_cstringappenddata function appends data to the existing value of a nsacstring instance. ...
...to use one of the string classes rather than directly using these functions. ns_cstringappenddatathe ns_cstringappenddata function appends data to the existing value of a nsacstring instance. ...
...16 function converts the value of a nsacstring instance to utf-16 and stores the result in a nsastring instance. ns_stringappenddatathe ns_stringappenddata function appends data to the existing value of a nsastring instance. this is a low-level api.ns_stringclonedatathe ns_stringclonedata function returns a null-terminated, heap allocated copy of the string's internal buffer.ns_stringcontainerfinishthe ns_stringcontainerfinish function releases any memory allocated by a nsstringcontainer instance. this is a low-level api.ns_stringcontainerinitthe ns_stringcontainerinit function initializes a nsstringcontainer instance for use as a nsastring. this is a low-level api.ns_stringcopythe ns_stringcopy function copies the value from one nsastring instance to another. this is a low-level api.ns_stri...
MailNews fakeserver
esults. server.start(port); // set up a nsimsgincomingserver locally localserver.someactionrequiringconnection(); server.performtest(); // nothing will be executed until the connection is closed // localserver.closecachedconnections() is generally a good way to do so server.resettest(); // set up second test server.performtest(); transaction = server.playtransaction(); // finished with tests server.stop(); } currently, fakeserver provides no means to keep a persistent connection past a test, requiring connections to be closed, possibly forcibly. alternatively, one can wait for the timeout, which occurs after 3 minutes, so not closing connections would make the tests take unbearably long. the server provides the following api to xpcshell tests: <caption> nsmailserver ...
...ich occurs after 3 minutes, so not closing connections would make the tests take unbearably long. ...
...o not closing connections would make the tests take unbearably long. ...
Debugger - Firefox Developer Tools
hould proceed. if it returns undefined, the exception continues to propagate as normal: if control in frame is in a try block, control jumps to the corresponding catch or finally block; otherwise,frame is popped, and the exception propagates toframe’s caller. when an exception’s propagation causes control to enter a finally block, the exception is temporarily set aside. if the finally block finishes normally, the exception resumes propagation, and the debugger’s onexceptionunwind handler is called again, in the same frame. (the other possibility is for the finally block to exit due to a return, continue, or break statement, or a new exception. in those cases the old exception does not continue to propagate; it is discarded.) this handler is not called when unwinding a frame due to an o...
...must have been evaluated in the scope of the given global object. if this property’s value is a debugger.object instance belonging to this debugger instance, then its referent is used. if the object is not a global object, then the global in whose scope it was allocated is used. note that the result may include sources that can no longer ever be used by the debuggee: say, eval code that has finished running, or source for unreachable functions. whether such sources appear can be affected by the garbage collector’s behavior, so this function’s result is not entirely deterministic. findscripts([query]) return an array of debugger.script instances for all debuggee scripts matchingquery. each instance appears only once in the array.query is an object whose properties restrict which s...
...is debugger instance, then its referent is used. if the object is not a global object, then the global in whose scope it was allocated is used. all properties ofquery are optional. passing an empty object returns all debuggee code scripts. note that the result may include debugger.script instances for scripts that can no longer ever be used by the debuggee, say, those for eval code that has finished running, or unreachable functions. whether such scripts appear can be affected by the garbage collector’s behavior, so this function’s behavior is not entirely deterministic. findobjects([query]) return an array of debugger.object instances referring to each live object allocated in the scope of the debuggee globals that matches query. each instance appears only once in the array. que...
DevTools API - Firefox Developer Tools
cified target has been destroyed. {toolid}-init(toolbox, iframe) a tool with the given id has began to load in the given toolbox to the given frame. {toolid}-build(toolbox, panel) a tool with the given id has began to initialize in the given toolbox. the panel is the object returned by the tooldefinition.build() method. {toolid}-ready(toolbox, panel) a tool with the given id has finished its initialization and is ready to be used. the panel is the object returned by the tooldefinition.build() method. {toolid}-destroy(toolbox, panel) a tool with the given id is about to be destroyed. the panel is the object returned by the tooldefinition.build() method. toolbox a toolbox is a frame for the toolpanels that is debugging a specific target. properties target target...
...ve, otherwise undefined. getpanelwhenready(toolid) similar to getpanel() but waits for the tool to load first. if the tool is not already loaded or currently loading the returned promise won't be fulfilled until something triggers the tool to load. parameters: toolid {string} - the tool identifier. return value: a promise that is fulfilled with the toolpanel object once the tool has finished loading. gettoolpanels() returns a toolid → toolpanel map for currently loaded tools. getnotificationbox() returns a <xul:notificationbox> element for the toolbox that can be used to display notifications to the user. loadtool(toolid) loads the tool with the given toolid in the background but does not activate it. parameters: toolid {string} - the tool identifier. ret...
... parameters: toolid {string} - the tool to unhighlight. opensplitconsole() opens the split console to the bottom of the toolbox. return value: a promise that is fulfilled once the console has loaded. closesplitconsole() closes the split console. togglesplitconsole() toggles the state of the split console. return value: a promise that is fulfilled once the operation has finished. switchhost(hosttype) switches the location of the toolbox parameters: hosttype {toolbox.hosttype} - the type of the new host. return value: a promise that is fulfilled once the new host is ready. reloadtarget(force) reloads the current target of the toolbox. parameters: force {boolean} - if true the target is shift-reloaded i.e. the cache is bypassed during the reloa...
Waterfall - Firefox Developer Tools
script engine must be paused, so your program is suspended and will be completely unresponsive. to help reduce the length of pauses, spidermonkey implements incremental gc: this means that it can perform garbage collection in fairly small increments, letting the program run in between. sometimes, though, it needs to perform a full non-incremental collection, and the program has to wait for it to finish. in trying to avoid gc events, and especially non-incremental gc events, it's wise not to try to optimize for the specific implementation of the javascript engine. spidermonkey uses a complex set of heuristics to determine 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 u...
...e resolution of a promise, it will also display "(async: promise)", under which it will show the "async stack": that is, the call stack at the point the promise was made. ...
...t will also display "(async: promise)", under which it will show the "async stack": that is, the call stack at the point the promise was made. for example, consider code like this: var timerbutton = document.getelementbyid("timer"); timerbutton.addeventlistener("click", handleclick, false); function handleclick() { console.time("timer"); runtimer(1000).then(timerfinished); } function timerfinished() { console.timeend("timer"); console.log("ready!"); } function runtimer(t) { return new promise(function(resolve) { settimeout(resolve, t); }); } the waterfall will display a marker for the period between time() and timeend(), and if you select it, you'll see the async stack in the sidebar: timestamp markers timestamps enable you to mark an instant in the recording. to make ...
EventTarget.addEventListener() - Web APIs
); // expected value: 'data' (will never output 'data again') note: although inner scopes have access to const, let variables from outer scopes, you cannot expect any changes to these variables to be accessible after the event listener definition, within the same outer scope. why? simply because by the time the event listener would execute, the scope in which it was defined would have already finished executing. getting data into and out of an event listener using objects unlike most functions in javascript, objects are retained in memory as long as a variable referencing them exists in memory. this, and the fact that objects can have properties, and that they can be passed around by reference, makes them likely candidates for sharing data among scopes. let's explore this. note: functio...
...are retained in memory as long as a variable referencing them exists in memory. this, and the fact that objects can have properties, and that they can be passed around by reference, makes them likely candidates for sharing data among scopes. let's explore this. note: functions in javascript are actually objects. (hence they too can have properties, and will be retained in memory even after they finish executing if assigned to a variable that persists in memory.) because object properties can be used to store data in memory as long as a variable referencing the object exists in memory, you can actually use them to get data into an event listener, and any changes to the data back out after an event handler executes. consider this example. const mybutton = document.getelementbyid('my-button-id...
...when one changes the data, the other can respond to the change). note: objects are stored in variables by reference, meaning only the memory location of the actual data is ...
Using IndexedDB - Web APIs
y have duplicates // so we can't use a unique index. objectstore.createindex("name", "name", { unique: false }); // create an index to search customers by email. we want to ensure that // no two customers have the same email, so use a unique index. objectstore.createindex("email", "email", { unique: true }); // use transaction oncomplete to make sure the objectstore creation is // finished before adding data into it. objectstore.transaction.oncomplete = function(event) { // store values in the newly created objectstore. var customerobjectstore = db.transaction("customers", "readwrite").objectstore("customers"); customerdata.foreach(function(customer) { customerobjectstore.add(customer); }); }; }; as indicated previously, onupgradeneeded is the only pla...
... you want to write to it here you need to pass the "readwrite" flag. now that you have a transaction you need to understand its lifetime. transactions are tied very closely to the event loop. if you make a transaction and return to the event loop without using it then the transaction will become inactive. the only way to keep the transaction active is to make a request on it. when the request is finished you'll get a dom event and, assuming that the request succeeded, you'll have another opportunity to extend the transaction during that callback. if you return to the event loop without extending the transaction then it will become inactive, and so on. as long as there are pending requests the transaction remains active. transaction lifetimes are really very simple but it might take a little tim...
...this means that a function (e.g. opendb()) that calls open() and onsuccess will return before the onsuccess handler has run. this issue is also true of other request methods such as transaction() and get(). ...
Key Values - Web APIs
vk_escape (0x1b) kvk_escape (0x35) gdk_key_escape (0xff1b) qt::key_escape (0x01000000) keycode_escape (111) "execute" the execute key. vk_execute (0x2b) qt::key_execute (0x01020003) "find" the find key. opens an interface (typically a dialog box) for performing a find/search operation. appcommand_find gdk_key_find (0xff68) "finish" [5] the finish key. vk_oem_finish (0xf1) "help" the help key. opens or toggles the display of help information. vk_help (0x2f) appcommand_help kvk_help (0x72) gdk_key_help (0xff6a) qt::key_help (0x01000058) keycode_help (259) "pause" the pause key. pauses the current application or state, if applicable. note: this shouldn't be con...
... [3] internet explorer (tested on release 9 and 11) and firefox 36 and earlier report "apps" instead of "contextmenu" for the context menu key. [4] the attn key generates the key code "unidentified" on internet explorer (tested on release 9 and 11). firefox and google chrome report the same, unless the japanese keyboard layout is in effect, in which case it generates "kanamode" instead. [5] the finish key gemerates the key code "unidentified" on internet explorer (tested on release 9 and 11). firefox reports the same, unless the japanese keyboard layout is in effect, in which case it generates "katakana" instead. [6] firefox didn't support the "zoomin" and "zoomout" keys until firefox 37. device keys keyboardevent.key value description virtual keycode windows mac ...
... gdk_key_kana_shift (0xff2e) qt::key_kana_lock (0x0100112d) qt::key_kana_shift (0x0100112e) "kanjimode" the kanji mode key. enables entering japanese text using the ideographic characters of chinese origin. vk_kanji [2] kvk_jis_kana (0x68) gdk_key_kanji (0xff21) qt::key_kanji (0x01001121) keycode_kana (218) "katakana" the katakana key. vk_oem_finish (0xf1) gdk_key_katakana (0xff26) qt::key_katakana (0x01001126) "romaji" [5] the romaji key; selects the roman character set. vk_oem_backtab (0xf5) gdk_key_romaji (0xff24) qt::key_romaji (0x01001124) "zenkaku" [4] the zenkaku (full width) characters key. vk_oem_enlw (0xf4) gdk_key_zenkaku (0xff28) qt::key_zenkaku (0x01001128) ...
RTCDTMFToneChangeEvent - Web APIs
constructors rtcdtmftonechangeevent() returns a new rtcdtmftonechangeevent. ...
... constructors rtcdtmftonechangeevent() returns a new rtcdtmftonechangeevent. it takes two parameters, the first being a domstring representing the type of the event (always "tonechange"); the second a dictionary containing the initial state of the properties of the event. ...
...tmftonechangeevent. it takes two parameters, the first being a domstring representing the type of the event (always "tonechange"); the second a dictionary containing the initial state of the properties of the event. methods supports the methods defined in event. there are no additional methods. examples this snippet is derived loosely from the full, working example you'll find in when a tone finishes playing in using dtmf with webrtc. it appends each tone to a display box as it's played, and, once all tones have been sent, re-enabled a previously-disabled "send" button, allowing the next dmtf string to be entered. dtmfsender.addeventlistener("change", function(event) { if (event.tone !== "") { dialstringbox.innertext += event.tone; } else { senddtmfbutton.disabled = false; } ...
RTCIceTransport: gatheringstatechange event - Web APIs
a gatheringstatechange event is sent to an rtcicetransport when its ice candidate gathering state changes. the gathering state, whose actual status can be found in the transport object's gatheringstate property, indicates whether or not the ice agent has begun gathering candidates, and if so, if it has finished doing so. bubbles no cancelable no interface event event handler property ongatheringstatechange the key difference between gatheringstatechange and icegatheringstatechange is that the latter represents the overall state of the connection including every rtcicetransport used by every rtcrtpsender and every rtcrtpreceiver on the entire connection. in contrast, gatheringstatechange represents changes to the candidate gathering state f...
...techange events on each rtcrtpsender associated with a given rtcpeerconnection. ...
...this transport has finished gathering candidates, but others may still be working on it */ } }, false); likewise, you can use the ongatheringstatechange event handler property: pc.getsenders().foreach(sender => { sender.transport.icetransport.ongatheringstatechange = ev => { let transport = ev.target; if (transport.gatheringstate === "complete") { /* this transport has finished gathering candidates, but others may still be working on it */ } }; }); specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'gatheringstatechange' in that specification. candidate recommendation ...
RTCIceTransportState - Web APIs
er, and there may still be gathering underway on one or both of the two devices. the transport may revert from the "connected" state to the "checking" state if either peer decides to cancel consent to use the selected candidate pair, and may revert to "disconnected" if there are no candidates left to check but one or both clients are still gathering candidates. "completed" the transport has finished gathering local candidates and has received a notification from the remote peer that no more candidates will be sent. in addition, all candidate pairs have been considered and a pair has been selected for use. if consent checks fail on all successful candidate pairs, the transport state will change to "failed". "disconnected" the ice agent has determined that connectivity has been lost for th...
...ent has determined that connectivity has been lost for this rtcicetransport. this is not a failure state (that's "failed"). a value of "disconnected" means that a transient issue has occurred that has broken the connection, but that should resolve itself automatically without your code having to take any action. see the disconnected state for additional details. "failed" the rtcicetransport has finished the gathering process, has received the "no more candidates" notification from the remote peer, and has finished checking pairs of candidates, without successfully finding a pair that is both valid and for which consent can be obtained. this is a terminal state, indicating that the connection cannot be achieved or maintained. "closed" the transport has shut down and is no longer responding to...
...he connection had been working but at the moment is not. every user agent and platform may have its own scenarios that can trigger the "disconnected" state. possible causes include: the network interface being used by the connection has gone offline. stun requests being sent to the remote device have gone unanswered repeatedly. the "disconnected" state can also occur when the transport has finished checking all existing candidate pairs and has not found a pair that will work—or a valid pair was found but rejected due to consent to use the pair being denied. in this scenario, the transport is still continuing to gather candidates, and/or to wait for candidates to be sent by the remote peer. specifications specification status comment webrtc 1.0: real-time commun...
SpeechSynthesisUtterance: end event - Web APIs
the end event of the web speech api speechsynthesisutterance object is fired when the utterance has finished being spoken. ...
...of the web speech api speechsynthesisutterance object is fired when the utterance has finished being spoken. ...
... draft ...
Using textures in WebGL - Web APIs
but the same technique can be used for any number of textures. note: it's important to note that the loading of textures follows cross-domain rules; that is, you can only load textures from sites for which your content has cors approval. see cross-domain textures below for details. the code that loads the texture looks like this: // // initialize a texture and load an image. ...
...n image. // when the image finished loading copy it into the texture. // function loadtexture(gl, url) { const texture = gl.createtexture(); gl.bindtexture(gl.texture_2d, texture); // because images have to be download over the internet // they might take a moment until they are ready. // until then put a single pixel in the texture so we can // use it immediately. when the image has finished downloading // we'll update the texture with the contents of the image. const level = 0; const internalformat = gl.rgba; const width = 1; const height = 1; const border = 0; const srcformat = gl.rgba; const srctype = gl.unsigned_byte; const pixel = new uint8array([0, 0, 255, 255]); // opaque blue gl.teximage2d(gl.texture_2d, level, internalformat, width, hei...
...uploads a single blue pixel using teximage2d(). this makes the texture immediately usable as a solid blue color even though it may take a few moments for our image to download. to load the texture from the image file, it then creates an image object and assigns the src to the url for our image we wish to use as our texture. the function we assign to image.onload will be called once the image has finished downloading. at that point we again call teximage2d() this time using the image as the source for the texture. after that we setup filtering and wrapping for the texture based on whether or not the image we download was a power of 2 in both dimensions or not. webgl1 can only use non power of 2 textures with filtering set to nearest or linear and it can not generate a mipmap for them. their wra...
WebGL best practices - Web APIs
dle's ref-pointer to the object) only once the object is unused in the implementation is it actually freed. for example, if you never want to access your shader objects directly again, just delete their handles after attaching them to a program object. eagerly lose contexts too webgl_lose_context.losecontext() can be used to release a webgl context and its resources eagerly. use this if you are finished with any contexts, such as probe contexts, or if you hit a fallback case. flush when expecting results (like queries or rendering frame completion) flush tells the implementation to push all pending commands out for execution, flushing them out of the queue, instead of waiting for more commands to enqueue before sending for execution. for example, it is possible for the following to never co...
...ly followed by the frame boundary, an explicit webgl.flush() isn't really needed with raf. avoid blocking api calls in production (e.g. geterror, getparameter) certain webgl entry points cause synchronous stalls on the calling thread. even basic requests can take as long as 1ms, but they can take even longer if they need to wait for all graphics work to be completed (with an effect similar to glfinish() in native opengl). in production code, avoid such entry points, especially on the browser main thread where they can cause the entire page to jank (often including scrolling or even the whole browser). geterror(): causes a flush + round-trip to fetch errors from the gpu process). for example, within firefox, the only time glgeterror is checked is after allocations (bufferdata, *texima...
...aders/programs: flush + shader compile + round-trip, if not done after shader compilation is complete. (see also parallel shader compilation below.) get*parameter() in general: possible flush + round-trip. in some cases, these will be cached to avoid the round-trip, but try to avoid relying on this. checkframebufferstatus(): possible flush + round-trip. getbuffersubdata(): usual finish + round-trip. (this is okay for read buffers in conjunction with fences - see async data readback below.) readpixels() to the cpu (i.e. without an unpack buffer bound): finish + round-trip. instead, use gpu-gpu readpixels in conjunction with async data readback. always keep vertex attrib 0 array-enabled if you draw with vertex attrib 0 array disabled, you will force the browser to do c...
Window - Web APIs
Web › API › Window
document. window.scrollby() scrolls the document in the window by the given amount. window.scrollbylines() scrolls the document by the given number of lines. window.scrollbypages() scrolls the current document by the specified number of pages. window.scrollto() scrolls to a particular set of coordinates in the document. window.setimmediate() executes a function after the browser has finished other heavy tasks window.setresizable() toggles a user's ability to resize a window. window.sizetocontent() sizes the window according to its content. window.stop() this method stops window loading. window.updatecommands() updates the state of commands of the current chrome window (ui). methods implemented from elsewhere eventtarget.addeventlistener() register an event handl...
...e part of the url after the hash mark ("#") changes. globaleventhandlers.oninput called when the value of an <input> element changes globaleventhandlers.onkeydown called when you begin pressing any key. see keydown event. globaleventhandlers.onkeypress called when a key (except shift, fn, and capslock) is in pressed position. see keypress event. globaleventhandlers.onkeyup called when you finish releasing any key. see keyup event. windoweventhandlers.onlanguagechange an event handler property for languagechange events on the window. globaleventhandlers.onload called after all resources and the dom are fully loaded. will not get called when the page is loaded from cache, such as with back button. windoweventhandlers.onmessage is an eventhandler representing the code to be called whe...
...active history entry changes. also available using the onpopstate event handler property. load & unload events beforeunload fired when the window, the document and its resources are about to be unloaded. also available via the onbeforeunload property. domcontentloaded fired when the document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading. load fired when the whole page has loaded, including all dependent resources such as stylesheets images. also available via the onload property. unload fired when the document or a child resource is being unloaded. also available via the onunload property. manifest events appinstalled fired when the browser has successfully installed a page as an application. also available ...
linear-gradient() - CSS: Cascading Style Sheets
ong a straight line. its result is an object of the <gradient> data type, which is a special kind of <image>. 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. ...
...tive 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. ...
...d us a pull request. ...
Overview of events and handlers - Developer guides
ent api: the theory of the dom, which shows the change in flow from the original browser flow to the event driven browser. the latter approach changes the last steps from a single flow into a perpetual loop, where waiting for and handling the incidence of new events follows painting. the innovation of the dynamic approach allows for a page to be partially rendered even when the browser has not finished retrieving all resources; this approach also allows for event driven actions, which javascript leverages. (the talk is available from several sources, including this one.) currently, all execution environments for javascript code use events and event handling. the event design pattern the event system, at its core, is simply a programming design pattern. the pattern starts with an agreement o...
...table events are: note: this list of events will need work to make relevant; that work is awaiting some global reorganization work on the documents. this will also need finding a good explanation of the events involved during page loading, such as discussed partially in this web page or in this stack overflow question. ...
... the event object hierarchy the web browser defines many events of different kinds. ...
HTTP Index - HTTP
Web › HTTP › Index
clear-site-data header clears browsing data (cookies, storage, cache) associated with the requesting website. it allows web developers to have more control over the data stored locally by a browser for their origins. 69 connection http, headers, reference, web the connection general header controls whether or not the network connection stays open after the current transaction finishes. if the value sent is keep-alive, the connection is persistent and not closed, allowing for subsequent requests to the same server to be done. 70 content-disposition http, reference, header in a multipart/form-data body, the http content-disposition general header is a header that can be used on the subpart of a multipart body to give information about the field it applies ...
...: informational responses (100–199),successful responses (200–299),redirects (300–399),client errors (400–499),and server errors (500–599). 218 100 continue http, informational, status code the http 100 continue informational status response code indicates that everything so far is ok and that the client should continue with the request or ignore it if it is already finished. 219 101 switching protocols http, http status code, informational, reference, websockets the http 101 switching protocols response code indicates the protocol the server is switching to as requested by a client which sent the message including the upgrade request header. 220 103 early hints draft, http, informational, needscompattable, needscontent, status c...
... to authenticate to gain network access. 271 link prefetching faq gecko, html, http, link, necko, performance, prefetch, web development link prefetching is a browser mechanism, which utilizes browser idle time to download or prefetch documents that the user might visit in the near future. a web page provides a set of prefetching hints to the browser, and after the browser is finished loading the page, it begins silently prefetching specified documents and stores them in its cache. when the user visits one of the prefetched documents, it can be served up quickly out of the browser's cache. 272 protocol upgrade mechanism guide, http, http/2, networking, protocols, upgrade, websocket, websockets the http/1.1 protocol provides a special mechanism that can b...
Link prefetching FAQ - HTTP
when the user visits one of the prefetched documents, it can be served up quickly out of the browser's cache. ...
...top notifications, and we approximate idle time as the period between the last document stop and the next document start. the last document stop notification occurs roughly when the onload handler would fire for the toplevel document. this is when we kick off prefetch requests. if a subframe contains prefetching hints, prefetching will not begin until the top-most frame and all its "child" frames finish loading. what happens if i click on a link while something is being prefetched? when the user clicks on a link, or initiates any kind of page load, link prefetching will stop and any prefetch hints will be discarded. if a prefetched document is partially downloaded, then the partial document will still be stored in the cache provided the server sent an "accept-ranges: bytes" response header. th...
...t if i'm downloading something in the background? will link prefetching compete for bandwidth? yes and no. if you are downloading something using mozilla, link prefetching will be delayed until any background downloads complete. for example, if you load a bookmark group (which opens several tabs), any prefetch requests initiated by one of the bookmarked pages will not begin until all of the tabs finish loading. if you are using another application which uses the network, link prefetching in mozilla may compete for bandwidth with the other application. this is a problem that we hope to address in the future by leveraging operating system services to monitor network idle time. are there any restrictions on what is prefetched? yes, only http:// (and, starting in gecko 1.9.1 https://) urls can be...
Navigation and resource timings - Web Performance
, is terminated. connectstart when the request to open a connection is sent to the network. if the transport layer reports an error and the connection establishment is started again, the last connection establishment start time is given. if a persistent connection is used, the value will be the same as performancetiming.fetchstart. domainlookupend when the domain lookup is finished. if a persistent connection is used, or the information is stored in a cache or a local resource, the value will be the same as performancetiming.fetchstart. domainlookupstart when the domain lookup starts. if a persistent connection is used, or the information is stored in a cache or a local resource, the value will be the same as performancetiming.fetchstart. fetchstart ...
...orresponding readystatechange event is thrown. unloadeventstart when the unload> event has been thrown, indicating the time at which the previous document in the window began to unload. if there is no previous document, or if the previous document or one of the needed redirects is not of the same origin, the value returned is 0. unloadeventend when the unload event handler finishes. if there is no previous document, or if the previous document, or one of the needed redirects, is not of the same origin, the value returned is 0. dominteractive when the parser finished its work on the main document, that is when its document.readystate changes to 'interactive' and the corresponding readystatechange event is thrown. domcontentloadedeventstart right bef...
...ent is thrown. domcontentloadedeventstart right before the parser sent the domcontentloaded event, that is right after all the scripts that need to be executed right after parsing have been executed. domcontentloadedeventend right after all the scripts that need to be executed as soon as possible, in order or not, have been executed. domcomplete when the parser finished its work on the main document, that is when its document.readystate changes to 'complete' and the corresponding readystatechange event is thrown. loadeventstart when the load event was sent for the current document. if this event has not yet been sent, it returns 0. loadeventend when the load event handler terminated, that is when the load event is completed. if this eve...
cfx - Archive of obsolete content
path relative to the current directory. --logfile=logfile log console output to the file specified by logfile. logfile may be specified as a full path or as a path relative to the current directory. --profile-memory=profilememory if this option is given and profilememory is any non-zero integer, then cfx dumps detailed memory usage information to the console when the tests finish. --test-runner-pkg=test_runner_pkg name of package containing test runner program. defaults to test-harness. cfx xpi this tool is used to package your add-on as an xpi file, which is the install file format for mozilla add-ons. called with no options, this command looks for a file called package.json in the current directory and creates the corresponding xpi file. once you h...
... --harness-option=key=value extra properties added to harness-options.json. --manifest-overload add fields to, or override selected fields in, package.json. this option takes an argument which is a path to a file containing json, and overloads any property of package.json with the properties found in the specified file. --output-file=output_file where to put the finished xpi file. --templatedir=templatedir the cfx xpi command constructs the add-on using a extension template which you can find under the sdk root, in app-extension. use the --templatedir option to specify a different template. templatedir may be specified as a full path or as a path relative to the current directory. internal options --keydir=keydir supply ...
Miscellaneous - Archive of obsolete content
example for firefox: services.startup.quit(services.startup.eforcequit|services.startup.erestart); mouse and keyboard detecting mouse wheel...
...if you wish to block selected scripts based on their uri, implement nsicontentpolicy. using string bundles from javascript assuming the extension has myext.properties with name/value pairs such as: invalid.url=the speficied url, %s, is invalid. that was attempt number %s. these properties can be accessed from javascript in the following manner: var common = { _bundle: components.cla...
JavaScript Object Management - Archive of obsolete content
getelementbyid("xulschoolhello-string-bundle"); // you can make changes to the window dom here. } // more stuff }; window.addeventlistener( "load", function() { 〈namespace〉.browseroverlay.init(); }, false); there are some things you can't (or shouldn't) do inside load handlers, such as closing the window being loaded, or opening new windows, alerts or dialogs. the window has to finish loading before it can do any of these things. they are bad ui practices anyway and you should avoid them. if you really need to do something like this anyway, one way to do it is to have a timeout execute the code after a delay: init : function(aevent) { let that = this; this._stringbundle = document.getelementbyid("xs-hw-string-bundle"); window.settimeout( function() { window...
...abel")); }, 0); } the settimeout function executes the function in the first parameter, after a delay in miliseconds specified by the second parameter. in this case we set the delay to 0, which means the function should be executed as soon as possible. firefox has a minimum delay of 10-15ms (taken from this blog post), so it won't really run instantly. it is more than enough to let the window finish its load. use window.settimeout and window.setinterval to control timed code execution. in case you're using javascript code modules or xpcom objects, where a window object is not readily available, use an nsitimer instead. this post suggests a way to achieve a true zero ms timeout, as a simple way to achieve parallelism in js code. notice the way we send callback functions as parameters,...
Setting Up a Development Environment - Archive of obsolete content
lar to this: creating xpi file. adding: install.rdf (deflated 50%) adding: chrome.manifest (deflated 50%) adding: content/browseroverlay.js (deflated 42%) adding: content/browseroverlay.xul (deflated 69%) adding: skin/browseroverlay.css (stored 0%) adding: locale/browseroverlay.dtd (deflated 52%) adding: locale/browseroverlay.properties (stored 0%) creating xpi file. done! build finished successfully. if you inspect the bin directory, you should see the xulschoolhello2.xpi file. if you run make again, you'll only see the last line of the build process. that is because make can tell that the file in the bin directory is up to date, and nothing needs to be done. making changes on source files will make make run the necessary steps to build the xpi again. you can clean up th...
...the automator application, choosing run shell script and then entering the profile-loading script in the textbox: /applications/firefox.app/contents/macos/firefox-bin -no-remote -p myprofile > /dev/null & you can change "/dev/null" to a file location, in case you want to see dump output from firefox, or other extensions. the last & prevents automator from waiting for your firefox session to finish. save this as an application, not a workflow. and you probably want to have these on your desktop or dock, for easy access. there are also some configuration changes you should make in your testing profiles, so that you get detailed error information in case something fails. the firefox error console (tools > error console) normally displays javascript errors that occur on web pages, but with so...
Session store API - Archive of obsolete content
); }; document.addeventlistener("sstabrestoring", myextensionhandlerestore, false); simply replace the contents of the function myextensionhandlerestore() with whatever you need to do when the tab is restored. in this example, nsiconsoleservice is used to display a message to the console. this event is sent just before a tab is restored. an event of type sstabrestored fires each time a tab has finished restoring. it's worth noting that this event is sent even if tab loading at startup is deferred until the user selects the tab. firefox 3 note in firefox 3 and later, if you need to detect when a tab is about to be closed so that you can update data associated with the tab before it is closed, you can watch for the "sstabclosing" event, which is sent to the tab. restoring without restartin...
...hat, the following steps are taken for each tab being restored: either an existing tab is reused or a new tab is created. in the latter case, a tabopen event is sent. the tab's persistent xul attributes (those saved due to calls to persisttabattribute()) and permissions are restored. the sstabrestoring event is sent. the tab is told to load the url it should be displaying. when the page is finished loading, text fields and scroll state are restored. finally, the sstabrestored event is sent. if you want to set permissions or otherwise manipulate a restored tab before the page is loaded into it, you should watch sstabrestoring. if you want to do something after the page is loaded, you should watch sstabrestored. both events are always sent for each tab being restored. you can determine ...
Enabling the behavior - retrieving tinderbox status - Archive of obsolete content
ll); } xmlhttprequest is an interface in mozilla for retrieving documents via http. although it is designed to retrieve xml content and parse it into a dom, it can retrieve (but not parse) other kinds of content as well. in this case we use it to retrieve an html page containing a brief summary of the current tinderbox state. ...
... xmlhttprequest will retrieve the document located at the given url and call the updatetinderboxstatus() function when it is done. ...
Abc Assembler Tests - Archive of obsolete content
/utils/abcasm. tests can be found in /test/acceptance/abcasm and end with the .abs extension. the tests are run using the same runtests.py script that is used for the actionscript tests. when run, the assembler tests include the abcasm/abs_helper.as file which defines the following functions: start(summary:string):void - start a new test section described by summary end():void - test section finished compare_stricteq(name:string, expected:*, actual:*):void - compare the results of a testcase where name is the testcase name compare_typeerror(name:string, expected:*, actual:*):void - special function for comparing typeerrors (runtimeerrors) - will only compare the first 22 chars of expected and actual so that test can be run in release and releasedebugger configurations. compare_numbereq(...
...ricteq 3 // use .try / .catch to catch typeerror // convert_o null .try { pushnull convert_o pop findproperty fail pushstring "convert_o null" pushstring "exception should have been thrown: typeerror: error #1009: cannot access a property or method of a null object reference." getlocal1 callpropvoid fail 3 jump finished_convert_o_null } .catch { getlocal0 pushscope setlocal2 // save typeerror findproperty compare_typeerror pushstring "convert_o null" // test name pushstring "typeerror: error #1009" // expected getlocal2 // actual callpropvoid compare_typeerror 3 } finished_convert_o_null: } ...
Venkman Introduction - Archive of obsolete content
inspection, and variable/object inspection are available from the user interface and from console commands, letting you work in the way you are most accustomed to. the interactive console also allows for execution of arbitrary javascript code. venkman's keyboard shortcuts are the same as leading visual debugging environments, and gdb users should be familiar with venkman's /break, /step, /next, /finish, /frame, and /where commands. on windows, the javascript debugger compares favorably with visual interdev and other large web development tools. on other platforms, including mac os and unix, it is alone in offering this degree of flexibility, depth, and power in a visual debugging environment. starting the debugger the javascript debugger is automatically pre-installed in mozilla 1.x but must...
...be "stopped for breakpoint" in red in the interactive session, along with the file name, line number, and snippet source code from where it stopped. figure 13. (from step 5) stopped at a breakpoint. in the interactive session's input field, enter this.fpaused venkman evaluates the expression, giving you [boolean] false back. press step into to follow the steps until you have finished debugging the function, and the fishes have paused. in addition to step in, which will execute a single line of javascript and stop, step over can be used to step over a impending function call, and return control to the debugger when the call returns. step out executes until the current function call exits. click the "pause" link again on the fishcam page to resume the demo. this s...
execute - Archive of obsolete content
ing]); parameters the execute method has the following parameters: xpisourcepath the pathname of the file to extract and execute. (note that this path points into the xpi itself.) args a parameter string that is passed to the executable. (ignored on mac os). see note below. blocking a boolean value that specifies whether the installation should wait for the execution of the file to finish before it resumes. default is false. see note below. the blocking parameter is not available as part of this method in versions of netscape before 6.1/mozilla 0.9.3. returns an integer error code. for a list of possible values, see return codes. description the execute method extracts the named file from the xpi file to a temporary file name. your code must call the performinstall method to...
...hat you plan to delete once it runs), then use the execute method on the file object instead. file.execute() executes an installed file (such as a browser) after it has been installed, and is typically placed at the end of an install script and outside of the main install block. the install object's execute method, on the other hand, deletes the executable from its temporary location once it has finished. the optional blocking argument, when set to true, specifies that the installation should wait for this executable to finish before processing the next queued install command. if you do not set this flag and launch an executable that is not a part of the installation, you will raise an error when you restart the browser. passing arguments to the executable the args parameter, when present, pas...
XUL Events - Archive of obsolete content
a key is released. attribute: onkeyup load this event is sent to the window after it has been fully loaded. you should place this event handler on the window element. this event may also be used on the image element, or an element that accepts an image attribute, and will be fired when the image has finished loading. for images, this event does not bubble up the element tree, so it will not conflict with the window's load event. attribute: onload mousedown this event is sent when the mouse is pressed on an element but not released. attribute: onmousedown ...
...he user releases the mouse button to drop an object being dragged. the element, if it accepts the drop, should respond in some manner such inserting the dragged object into itself. attribute: ondragdrop dragend the dragend event is sent to the source node (the node that was dragged) when the drag is finished. attribute: ondragend dragenter the dragenter event is sent when the mouse pointer first moves over an element during a drag. it is similar to the mouseover event but occurs while dragging. attribute: ondragenter dragexit ...
Template Logging - Archive of obsolete content
"logging"/> the flags attribute on the root element of the template should include the logging flag. if other flags are used as well, separate them with spaces. enabling logging will output details to the error console for each result. the error console can be found on the firefox tools menu. this logging of results can be very useful for debugging, but remember to remove this flag when you have finished and the template works correctly, as the logging can take up extra time that is not necessary when the template is working. each result is logged in a form much like the following: in template with id root using ref http://www.some-fictitious-zoo.com/birds new active result for query 2 matching rule 1: http://www.some-fictitious-zoo.com/birds/emperorpenguin in the example above, a new result h...
...ether the xml data was loaded and parsed correctly. if null, then the datasource could not be loaded, or hasn't yet been loaded. if the datasource load and parsing was successful, the datasource will be set to the xml document. for example: if (root.builder.datasource instanceof xmldocument) alert("xml datasource loaded ok"); be careful, as the datasource will only be set once the document has finished loading and has been parsed, so don't check this property too early. you may also get an error if you manipulate or analyze the template while the datasource is loading. you could iterate and wait using a timer. future versions may include other features to make it easier to debug problems with data loading. « previous ...
Mouse controls - Game development
we have already added keyboard controls, but we could easily add mouse controls too. listening for mouse movement listening for mouse movement is even easier than listening for key presses: all we need is the listener for the mousemove event. ...
...rsor, but since we're restricting the movement to the size of the canvas, it won't disappear completely off either side. compare your code this is the latest state of the code to compare against: exercise: adjust the boundaries of the paddle movement, so the whole paddle will be visible on both edges of the canvas instead of only half of it. next steps now we've got a complete game we'll finish our series of lessons with some more small tweaks — finishing up. « previousnext » ...
Animations and tweens - Game development
nes the state of the object at the end of the tween. it takes an object containing the chosen parameter's desired ending values (scale takes a scale value, 1 being 100% of size, 0 being 0% of size, etc.), the time of the tween in milliseconds and the type of easing to use for the tween. we will also add the optional oncomplete event handler, which defines a function to be executed when the tween finishes. the last thing do to is to start the tween right away using start(). that's the expanded version of the tween definition, but we can also use the shorthand syntax: game.add.tween(brick.scale).to({x:2,y:2}, 500, phaser.easing.elastic.out, true, 100); this tween will double the brick's scale in half a second using elastic easing, will start automatically, and have a delay of 100 milisecond...
... tween right away using start(). that's the expanded version of the tween definition, but we can also use the shorthand syntax: game.add.tween(brick.scale).to({x:2,y:2}, 500, phaser.easing.elastic.out, true, 100); this tween will double the brick's scale in half a second using elastic easing, will start automatically, and have a delay of 100 miliseconds. compare your code you can check the finished code for this lesson in the live demo below, and play with it to understand better how it works: next steps animations and tweens look very nice, but we can add even more to our game — in the next section we'll look at handling button inputs. « previousnext » ...
Visual JS GE - Game development
ing section provides information about the tools involved in visual-js game engine. in page editor found at server_instance/editor.js. build_from_editor_to_visual_js found at server_instance/build_from_editor_to_visual_js_file.js. this is a node.js app for local use. if you use editor.js to visually create game objects, you must start the build_from_editor_to_visual_js_file.js when you have finished. this tool will create visual.js in the starter/ directory along with all your game objects. it takes data from the system folder lib/visual_scripts/ and generates your code. resource js objects used for adding images for animation purposes. this is done using server_instance/res.js. you need to put your images in a folder, for example test_res/ , inside project_instance/res/. next, ru...
...ry along with all your game objects. it takes data from the system folder lib/visual_scripts/ and generates your code. resource js objects used for adding images for animation purposes. this is done using server_instance/res.js. you need to put your images in a folder, for example test_res/ , inside project_instance/res/. next, run the command server_instance/node res.js. after this has finished processing, restart the web page by entering the following in the console: resource.test_res. resource objects contain the path data for all your images. the actual image objects will be created after you add animation to the game objects. this is good because it is memory safe. visual js.exe windows gui freeware only for windows users. contains the following tools. visual_js.exe versi...
Index - MDN Web Docs Glossary: Definitions of Web-related terms
called http/2. 197 http header glossary, http header, webmechanics an http header is a field of an http request or response that passes additional information, altering or precising the semantics of the message or of the body. headers are case-insensitive, begins at the start of a line and are immediately followed by a ':' and a value depending of the header itself. the value finish at the next crlf or at the end of the message. 198 http/2 glossary, http, infrastructure, reference, web performance, l10n:priority http/2 is a major revision of the http network protocol 199 http/3 http, intro, needscontent http/3 is the upcoming major revision of the http network protocol 200 https glossary, https, infrastructure, securit...
...of information from the server. this time includes dns lookup and establishing the connection using a tcp handshake and ssl handshake if the request is made over https. 459 time to interactive glossary, performance, reference, web performance time to interactive (tti) is a non-standardized web performance 'progress' metric defined as the point in time when the last long task finished and was followed by 5 seconds of network and main thread inactivity. 460 transmission control protocol (tcp) glossary, networking, ssl, security, tcp, tls, web performance tcp (transmission control protocol) is a transport layer host-to-host protocol for connection-oriented communication between two computers on an ip network. tcp uses virtual ports to create a virtual end-...
Test your skills: CSS and JavaScript accessibility - Learn web development
tell that they are links, or to tell which one the user is focussed on. we'd like you to assume that the existing ruleset with the a selector is supplied by some cms, and that you can't change it — instead, you need to create new rules to make the links look and behave like links, and for the user to be able to tell where they are in the list. try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor. css accessibility 2 in this next task you are presented with a simple bit of content — just headings and paragraphs. there are accessibility issues with the colors and sizing of the text; we'd like you to: 1. explain what the problems are, and what the guidelines are that state the a...
...at the guidelines are that state the acceptable values for color and sizing. 2. select new values for the color and font-size that fix the problem. 3. update the css with these new values to fix the problem. 4. test the code to make sure the problem is now fixed. explain what tools or methods you used to select the new values and test the code. try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor. javascript accessibility 1 in our final task here, you have some javascripting to do. we have a simple app that presents a list of animal names. clicking one of the animal names causes a further description of that animal to appear in a box below the list. but it is not very accessible ...
Mobile accessibility - Learn web development
ate the url bar. enter a web page that has a bunch of headings on it, such as the front page of bbc.co.uk. to enter the text of the url: select the url bar by swiping left/right till you get to it, and then double-tapping. hold your finger down on the virtual keyboard until you get the character you want, and then release your finger to type it. repeat for each character. once you've finished, find the enter key and press it. swipe left and right to move between different items on the page. swipe up and right with a smooth motion to enter the local content menu. swipe right until you find the "headings and landmarks" option. double-tap to select it. now you'll be able to swipe left and right to move between headings and aria landmarks. to go back to the default mode, enter...
...nter a web page that has a bunch of headings on it, such as the front page of bbc.co.uk. to enter the text of the url: select the url bar by swiping left/right until you get to it, and then double-tapping. for each character, hold your finger down on the virtual keyboard until you get the character you want, and then release your finger to select it. double-tap to type it. once you've finished, find the enter key and press it. swipe left and right to move between items on the page. you can double-tap an item to select it (e.g., follow a link). by default, the selected rotor option will be speaking rate; you can currently swipe up and down to increase or decrease the speaking rate. now turn two fingers around the screen like a dial to show the rotor and move between its option...
Test your skills: WAI-ARIA - Learn web development
, then ask us for help — see the assessment or further help section at the bottom of this page. wai-aria 1 in our first aria task, we present you with a section of non-semantic markup, which is obviously meant to be a list. assuming you are not able to change the elements used, how can you allow screenreader users to recognize this as a list? try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor. wai-aria 2 in our second wai-aria task, we present a simple search form, and we want you to add in a couple of wai-aria features to improve its accessibility: how can you allow the search form to be called out as a separate landmark on the page by screenreaders, to make it easily find...
... wai-aria 3 for this final wai-aria task, we return to an example we previously saw in the css and javascript skilltest. as before, we have a simple app that presents a list of animal names. clicking one of the animal names causes a further description of that animal to appear in a box be...
WAI-ARIA basics - Learn web development
the heading too, so the user can remember what is being read out. to do this, we can add the aria-atomic property to the section. update your <section> tag again, like so: <section aria-live="assertive" aria-atomic="true"> the aria-atomic="true" attribute tells screenreaders to read out the entire element contents as one atomic unit, not just the bits that were updated. note: you can see the finished example at aria-live.html (see it running live). note: the aria-relevant property is also quite useful for controlling what gets read out when a live region is updated. you can for example only get content additions or removals read out. enhancing keyboard accessibility as discussed in a few other places in the module, one of the key strengths of html with respect to accessibility is the ...
... but these currently don't seem very well supported; a better supported feature is the html5 placeholder attribute, which can contain a message that is shown in the input when no value is entered, and is read out by a number of screenreaders. update your number input like this: <input type="number" name="age" id="age" placeholder="enter 1 to 150" aria-required="true"> note: you can see the finished example live at form-validation-updated.html. wai-aria also enables some advanced form labelling techniques, beyond the classic <label> element. we already talked about using the aria-label property to provide a label where we don't want the label to be visible to sighted users (see the signposts/landmarks section, above). there are some other labelling techniques that use other properties su...
Fundamental CSS comprehension - Learn web development
erhaps double as a gamer card or social media profile. the following sections describe what you need to do. basic setup: first of all, create a new file in the same directory as your html and image files. call it something really imaginative like style.css. link your css to your html file via a <link> element. the first two rulesets in the css resource file are yours, for free! after you've finished rejoicing at your good fortune, copy and paste them into the top of your new css file. use them as a test to make sure your css is properly applied to your html. above the two rules, add a css comment with some text inside it to indicate that this is a set of general styles for the overall page. "general page styles" would do. also add three more comments at the bottom of the css file to indic...
...html in any way, except to apply the css to your html. when trying to work out the em value you need to represent a certain pixel length, think about what base font size the root (<html>) element has, and what it needs to be multiplied by to get the desired value. that'll give you your em value, at least in a simple case like this. example the following screenshot shows an example of what the finished design should look like: assessment or further help if you would like your work assessed, or are stuck and want to ask for help: put your work into an online shareable editor such as codepen, jsfiddle, or glitch. write a post asking for assessment and/or help at the mdn discourse forum learning category. your post should include: a descriptive title such as "assessment wanted for ...
Test your skills: The Box Model - Learn web development
further help section at the bottom of this page. the box model one with the two boxes below, one is using the standard box model, the other the alternate box model. change the width of the second box by adding rules to the .alternate class, so that it matches the visual width of the first box. your final result will look like the image below. try updating the live code below to recreate the finished example: for assessment or further work purposes, download the starting point for this task to work in your own editor or in an online editor. the box model two in this task, add to the box: a 5px, black, dotted border. a top margin of 20px. a right margin of 1em. a bottom margin of 40px. a left margin of 2em. padding on all sides of 1em. try updating the live code below to r...
...k in your own editor or in an online editor. the box model three in this example the inline element has a margin, padding and border however the lines above and below are overlapping it. what can you add to your css to cause the size of the margin, padding, and border to be respected by the other lines, while still keeping the element inline? try updating the live code below to recreate the finished example: for assessment or further work purposes, download the starting point for this task to work in your own editor or in an online editor. assessment or further help you can practice these examples in the interactive editors mentioned above. if you would like your work assessed, or are stuck and want to ask for help: put your work into an online shareable editor such as codepen, ...
Test your skills: backgrounds and borders - Learn web development
he bottom of this page. backgrounds and borders 1 in this task we want you to add a background, border, and some simple styling to a page header: give the box a 5px black solid border, with rounded corners of 10px. add a background image (use the url balloons.jpg) and size it so that it covers the box. give the <h2> a semi-transparent black background color, and make the text white. the finished example should look like the image below. try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor. backgrounds and borders 2 in this task we want you to add background images, a border, and some other styling to a decorative box: give the box a 5px lightblue border, and round the ...
...blue border, and round the top left corner 20px and the bottom right corner 40px the heading uses the star.png image as a background image, with a single centered star on the left and a repeating pattern of stars on the right. make sure that the heading text does not overlay the image, and that it is centered — you will need to use techniques learned in previous lessons to achieve this. the finished example should look like the image below: try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor. assessment or further help you can practice these examples in the interactive editors above. if you would like your work assessed, or are stuck and want to ask for help: put your wo...
Test your skills: Writing Modes and Logical Properties - Learn web development
sks. if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page. task one the box in the example is displayed with a horizontal writing mode. can you add a line of css to change it so it uses a vertical writing mode with right to left text? your example should look like the image below. try updating the live code below to recreate the finished example: for assessment or further work purposes, download the starting point for this task to work in your own editor or in an online editor. task two in the example below use logical properties to replace width and height in order to maintain the aspect ratio of the box as it is turned vertically. your end result should look like the image below. try updating the live code below to ...
...urther work purposes, download the starting point for this task to work in your own editor or in an online editor. task three use logical versions of the margin, border, and padding properties so that the edges of the box relate to the text rather than following top, left, bottom and right. you can see how this should look in the image below. try updating the live code below to recreate the finished example: for assessment or further work purposes, download the starting point for this task to work in your own editor or in an online editor. assessment or further help you can practice these examples in the interactive editors mentioned above. if you would like your work assessed, or are stuck and want to ask for help: put your work into an online shareable editor such as codepen, ...
Test your skills: position - Learn web development
e an online tool such as codepen, jsfiddle, or glitch to work on the tasks. if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page. positioning one in this task you need to position the item with a class of target to the top and right of the container, which has the 5px grey border. try updating the live code below to recreate the finished example: as an extra challenge, can you change the target to display underneath the text? for assessment or further work purposes, download the starting point for this task to work in your own editor or in an online editor. position two in the below example if you scroll the box the sidebar scrolls with the content. change it so that the sidebar stays in place and only the content scrol...
... target to display underneath the text? for assessment or further work purposes, download the starting point for this task to work in your own editor or in an online editor. position two in the below example if you scroll the box the sidebar scrolls with the content. change it so that the sidebar stays in place and only the content scrolls. try updating the live code below to recreate the finished example: for assessment or further work purposes, download the starting point for this task to work in your own editor or in an online editor. assessment or further help you can practice these examples in the interactive editors mentioned above. if you would like your work assessed, or are stuck and want to ask for help: put your work into an online shareable editor such as codepen, ...
Positioning - Learn web development
f the screen). z-index values affect where positioned elements sit on that axis; positive values move them higher up the stack, and negative values move them lower down the stack. by default, positioned elements all have a z-index of auto, which is effectively 0. to change the stacking order, try adding the following declaration to your p:nth-of-type(1) rule: z-index: 1; you should now see the finished example, with the lime paragraph on top: <h1>z-index</h1> <p>i am a basic block level element. my adjacent block level elements sit on new lines below me.</p> <p class="positioned">now i'm absolutely positioned relative to the <code>&lt;body&gt;</code> element, not the <code>&lt;html&gt;</code> element!</p> <p>we are separated by our margins. because of margin collapsing, we are separated ...
... improve this more — at the moment some of the content starts off underneath the heading. this is because the positioned heading no longer appears in the document flow, so the rest of the content moves up to the top. we need to move it all down a bit; we can do this by setting some top margin on the first paragraph. add this now: p:nth-of-type(1) { margin-top: 60px; } you should now see the finished example: <h1>fixed positioning</h1> <p>i am a basic block level element. my adjacent block level elements sit on new lines below me.</p> <p class="positioned">i'm not positioned any more...</p> <p>we are separated by our margins. because of margin collapsing, we are separated by the width of one of our margins, not both.</p> <p>inline elements <span>like this one</span> and <span>this one...
Styling lists - Learn web development
<p> elements we've included for reference have a top and bottom margin of 16px (1em), the same as the different list types. ...
...image property allows you to use a custom image for your bullet. the syntax is pretty simple: ul { list-style-image: url(star.svg); } however, this property is a bit limited in terms of controlling the position, size, etc. of the bullets. you are better off using the background family of properties, which you've learned in the backgrounds and borders article. ...
Web fonts - Learn web development
t, follow these steps: make sure you have satisfied any licensing requirement, if you are going to use this in a commercial and/or web project. go to the fontsquirrel webfont generator. upload your two font files using the upload fonts button. check the checkbox labeled "yes, the fonts i'm uploading are legally eligible for web embedding." click download your kit. after the generator has finished processing, you should get a zip file to download — save it in the same directory as your html and css. implementing the code in your demo at this point, unzip the webfont kit you just generated. inside the unzipped directory you'll see three useful items: multiple versions of each font: (for example .ttf, .woff, .woff2, etc.; the exact fonts provided will be updated over time as browser...
...eb safe or default system font. for example: font-family: 'zantrokeregular', serif; you should end up with a demo page with some nice fonts implemented on them. because different fonts are created at different sizes, you may have to adjust the size, spacing, etc., to sort out the look and feel. note: if you have any problems getting this to work, feel free to compare your version to our finished files — see web-font-finished.html and web-font-finished.css (run the finished example live). using an online font service online font services generally store and serve fonts for you, so you don't have to worry about writing the @font-face code, and generally just need to insert a simple line or two of code into your site to make everything work. examples include adobe fonts and cloud.typ...
Test your skills: Advanced styling - Learn web development
lass icon. we've made one available in the same directory as our html files — see search-24px.png — plus a <div> element after the search input to help you attach it, should you need it. can you figure out a sensible way to attach it, and can you use some css to get it to sit to the right of the search box, and be lined up vertically as well? try updating the live code below to recreate 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 ...
...yle — 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 recreate the finished example: download the starting point for this task to work in your own editor or in an online editor. advanced form styling 3 in our final task for this assessment series, we provide you with a feedback form that is already nicely-styled — you've already seen something similar if you've worked through our ui pseudo-classes article, and now we want you to come up with your own solution.
Test your skills: HTML5 controls - Learn web development
jsfiddle, or glitch to work on the tasks. if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page. html5 controls 1 first let's explore some of the new html5 input types. create appropriate inputs for a user to update their details for: email website phone number favourite color try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor. html5 controls 2 next, we want you to implement a slider control to allow the user to choose a maximum number of people to invite to their party. implement a basic slider control to go along with the provided label. give it a minimum value of 1, maximum value of 30, and initial value...
...e of 1, maximum value of 30, and initial value of 10. create a corresponding output element to put the current value of the slider into. give it a class of invite-output, and semantically associate it with the input. if you do this correctly, the javascript included on the page will automatically update the output value when the slider is moved. try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor. assessment or further help you can practice these examples in the interactive editors above. if you would like your work assessed, or are stuck and want to ask for help: put your work into an online shareable editor such as codepen, jsfiddle, or glitch. you can write the code yoursel...
UI pseudo-classes - Learn web development
abled-label { color: #aaa; } we've directly selected the inputs we want to disable using input[type="text"]:disabled, but we also wanted to gray out the corresponding text labels. these weren't quite as easy to select, so we've used a class to provide them with that styling. ...
... 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 :user-invalid when the element loses focus. if the value was originally invalid,...
HTML text fundamentals - Learn web development
the ingredients into a paste if you want a coarse "chunky" hummus, process it for a short time if you want a smooth hummus, process it for a longer time for a different flavour, you could try blending in a small measure of lemon and coriander, chili pepper, lime and chipotle, harissa and mint, or spinach and feta cheese. experiment and see what works for you. storage refrigerate the finished hummus in a sealed container. you should be able to use it for about a week after you've made it. if it starts to become fizzy, you should definitely discard it. hummus is suitable for freezing; you should thaw it and use it within a couple of months.</textarea> <div class="playable-buttons"> <input id="reset" type="button" value="reset"> <input id="solution" type="button" value="show s...
...nt a coarse "chunky" hummus, process it for a short time.</li>\n<li>if you want a smooth hummus, process it for a longer time.</li>\n</ol>\n\n<p>for a different flavour, you could try blending in a small measure of lemon and coriander, chili pepper, lime and chipotle, harissa and mint, or spinach and feta cheese. experiment and see what works for you.</p>\n\n<h2>storage</h2>\n\n<p>refrigerate the finished hummus in a sealed container. you should be able to use it for about a week after you\'ve made it. if it starts to become fizzy, you should definitely discard it.</p>\n\n<p>hummus is suitable for freezing; you should thaw it and use it within a couple of months.</p>'; var solutionentry = htmlsolution; textarea.addeventlistener('input', updatecode); window.addeventlistener('load', updatecode); ...
Test your skills: Advanced HTML text - Learn web development
pful to download the code and use an online tool such as codepen, jsfiddle, or glitch to work on the tasks. if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page. advanced html text 1 in this task we want you to turn the provided animals and their definitions into a description list. try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor. advanced html text 2 in this task we want you to add some semantics to the provided html as follows: turn the second paragraph into a block-level quote, and semantically indicate that the quote is taken from accessibility. semantically mark up "html" and "css" as acronyms, providing ...
...ally indicate that the quote is taken from accessibility. semantically mark up "html" and "css" as acronyms, providing expansions as tooltips. semantically associate machine-readable dates with the dates in the text. use subscript and superscript to provide correct semantics for the chemical formulae and dates, and make them display correctly. try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor. assessment or further help you can practice these examples in the interactive editors above. if you would like your work assessed, or are stuck and want to ask for help: put your work into an online shareable editor such as codepen, jsfiddle, or glitch. you can write the code yoursel...
Images in HTML - Learn web development
ver whether the image is removed or replaced with something embarrassing. our above code would give us the following result: note: elements like <img> and <video> are sometimes referred to as replaced elements. this is because the element's content and size are defined by an external resource (like an image or video file), not by the contents of the element itself. note: you can find the finished example from this section running on github (see the source code too.) alternative text the next attribute we'll look at is alt. its value is supposed to be a textual description of the image, for use in situations where the image cannot be seen/displayed or takes a long time to render because of a slow internet connection. for example, our above code could be modified like so: <img src="im...
...dent unit of content that: expresses your meaning in a compact, easy-to-grasp way. could go in several places in the page's linear flow. provides essential information supporting the main text. a figure could be several images, a code snippet, audio, video, equations, a table, or something else. active learning: creating a figure in this active learning section, we'd like you to take the finished code from the previous active learning section, and turn it into a figure: wrap it in a <figure> element. copy the text out of the title attribute, remove the title attribute, and put the text inside a <figcaption> element below the image. if you make a mistake, you can always reset it using the reset button. if you get really stuck, press the show solution button to see an answer: play...
Video and audio content - Learn web development
previous overview: multimedia and embedding next now that we are comfortable with adding simple images to a webpage, the next step is to start adding video and audio players to your html documents! in this article we'll look at doing just that with the <video> and <audio> elements; we'll then finish off by looking at how to add captions/subtitles to your videos. prerequisites: basic computer literacy, basic software installed, basic knowledge of working with files, familiarity with html fundamentals (as covered in getting started with html) and images in html. objective: to learn how to embed video and audio content into a webpage, and add captions/subtitles to video. video and audio on the web web developers have wanted to use video and audio on the we...
...ll grow to fill the space horizontally, and the unfilled space will just be given a solid background color by default. autoplay makes the audio or video start playing right away, while the rest of the page is loading. you are advised not to use autoplaying video (or audio) on your sites, because users can find it really annoying. loop makes the video (or audio) start playing again whenever it finishes. this can also be annoying, so only use if really necessary. muted causes the media to play with the sound turned off by default. poster the url of an image which will be displayed before the video is played. it is intended to be used for a splash screen or advertising screen. preload used for buffering large files; it can take one of three values: "none" does not buffer the file ...
Function return values - Learn web development
console.log(newstring); // should print "the weather is warm" // the replace() string function takes a string, // replaces one substring with another, and returns // a new string with the replacement made the replace() function is invoked on the mytext string, and is passed two parameters: the substring to find ('cold'). the string to replace it with ('warm'). when the function completes (finishes running), it returns a value, which is a new string with the replacement made. in the code above, the result of this return value is saved in the variable newstring. if you look at the replace() function mdn reference page, you'll see a section called return value. it is very useful to know and understand what values are returned by functions, so we try to include this information wherever pos...
... number. therefore, a sentence is printed out inside the paragraph element that states the square, cube, and factorial values of the number. the sentence calls the squared(), cubed(), and factorial() functions to calculate the required values. save your code, load it in a browser, and try it out. note: if you have trouble getting the example to work, feel free to check your code against the finished version on github (see it running live also), or ask us for help. now it's your turn! at this point, we'd like you to have a go at writing out a couple of functions of your own and adding them to the library. how about the square or cube root of the number? or the circumference of a circle with a given radius? some extra function related tips: look at another example of writing error han...
Third-party APIs - Learn web development
play when the marker is clicked. finally, we chain .addto(map) to the end of the chain to actually add the marker to the map. have a play with the other options shown in the documentation and see what you can come up with! mapquest provides some pretty advanced functionality, such as directions, searching, 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 g...
...ve to take the extra step of checking that pagenumber is not already zero before decrementing it — if the fetch request runs with a minus page url parameter, it could cause errors. if the pagenumber is already 0, we simply return out of the function, to avoid wasting processing power (if we are already at the first page, we don't need to load the same results again). note: you can find our finished nytimes api example code on github (also see it running live here). youtube example we also built another example for you to study and learn from — see our youtube video search example. this uses two related apis: the youtube data api to search for youtube videos and return results. the youtube iframe player api to display the returned video examples inside iframe video players so you ...
A first splash into JavaScript - Learn web development
it inside addeventlistener(). try saving and refreshing your code now, and your example should work — to a point. the only problem now is that if you guess the correct answer or run out of guesses, the game will break because we've not yet defined the setgameover() function that is supposed to be run once the game is over. let's add our missing code now and complete the example functionality. finishing the game functionality let's add that setgameover() function to the bottom of our code and then walk through it. add this now, below the rest of your javascript: function setgameover() { guessfield.disabled = true; guesssubmit.disabled = true; resetbutton = document.createelement('button'); resetbutton.textcontent = 'start new game'; document.body.append(resetbutton); resetbutton...
...y one: guesses.style.backgroundcolor = 'yellow'; guesses.style.fontsize = '200%'; guesses.style.padding = '10px'; guesses.style.boxshadow = '3px 3px 6px black'; every element on a page has a style property, which itself contains an object whose properties contain all the inline css styles applied to that element. this allows us to dynamically set new css styles on elements using javascript. finished for now... so that's it for building the example. you got to the end — well done! try your final code out, or play with our finished version here. if you can't get the example to work, check it against the source code. previous overview: first steps next in this module what is javascript? a first splash into javascript what went wrong? troubleshooting javascript storing the i...
Test your skills: Math - Learn web development
math 1 let's start out by testing your knowledge of basic math operators. you will have to create four numeric values, then add the first two together, then subtract the fourth from the third, then multiply the two secondary results together to get a result of 48. finally, we need to write a test that proves that this value is an even number. so, try updating the live code below to recreate the finished example, following these steps: create four variables that contain numbers. call the variables something sensible. add the first two variables together and store the result in another variable. subtract the fourth variable from the third and store the result in another variable. multiply the results from the last two steps together, storing the result in a variable called finalresult. the...
...ovided with two calculations, with the results stored in the variables result and result2. but these results aren't what we want; you'll need to take the calculations and change them to give us what we want. what do we want? after multiplying the two results together and formatting the result to 2 decimal places, the final result should be 10.42. try updating the live code below to recreate the finished example, following these steps: write a calculation that multiplies result and result2 together and assigns the result back to result. this will require assignment shorthand. write a line of code that takes result and formats it to 2 decimal places, storing the result of this in a variable called finalresult. check the data type of finalresult using typeof; you'll probably see that it is a...
Adding features to our bouncing balls demo - Learn web development
revious article as a starting point, and add some new and interesting features to it. prerequisites: before attempting this assessment you should have already worked through all the articles in this module. objective: to test comprehension of javascript objects and object-oriented constructs starting point to get this assessment started, make a local copy of index-finished.html, style.css, and main-finished.js from our last article in a new directory in your local computer. alternatively, you could use a site like jsbin or glitch to do your assessment. you could paste the html, css and javascript into one of these online editors. if the online editor you are using doesn't have separate javascript/css panels, feel free to put them inline <script>/<style> elements...
...ake it a little bit more interactive by adding a user-controlled evil circle, which will eat the balls if it catches them. we also want to test your object-building skills by creating a generic shape() object that our balls and evil circle can inherit from. finally, we want to add a score counter to track the number of balls left to capture. the following screenshot gives you an idea of what the finished program should look like: to give you more of an idea, have a look at the finished example (no peeking at the source code!) steps to complete the following sections describe what you need to do. creating our new objects first of all, change your existing ball() constructor so that it becomes a shape() constructor and add a new ball() constructor: the shape() constructor should defi...
Working with JSON - Learn web development
the <ul> element (mylist) using appendchild(). the very last thing we do is to append the <h2>, <p>s, and <ul> inside the <article> (myarticle), then append the <article> inside the <section>. the order in which things are appended is important, as this is the order they will be displayed inside the html. note: if you are having trouble getting the example to work, try referring to our heroes-finished.html source code (see it running live also.) note: if you are having trouble following the dot/bracket notation we are using to access the javascript object, it can help to have the superheroes.json file open in another tab or your text editor, and refer to it as you look at our javascript. you should also refer back to our javascript object basics article for more information on dot and bra...
...uckily, these two problems are so common in web development that a built-in json object is available in browsers, which contains the following two methods: parse(): accepts a json string as a parameter, and returns the corresponding javascript object. stringify(): accepts an object as a parameter, and returns the equivalent json string form. you can see the first one in action in our heroes-finished-json-parse.html example (see the source code) — this does exactly the same thing as the example we built up earlier, except that we set the xhr to return the raw json text, then used parse() to convert it to an actual javascript object. the key snippet of code is here: request.open('get', requesturl); request.responsetype = 'text'; // now we're getting a string! request.send(); request.onlo...
The "why" of web performance - Learn web development
loading this on a desktop computer connected to a fibre optic network. this would seem relatively fast, and the file size would be largely irrelevant. imagine loading that same site using tethered mobile data on a 9 year-old ipad while commuting home on public transportation. the same site will be slow to load, possibly verging on unusable depending on cell coverage. you might give up before it finishes loading. imagine loading that same site on a $35 huawei device in a rural india with limited coverage or no coverage. the site will be very slow to load—if it loads at all—with blocking scripts possibly timing out, and adverse cpu impact causing browser crashes if it does load. a 22.6 mb site could take up to 83 seconds to load on a 3g network, with domcontentloaded (meaning the site's b...
... to build websites and applications people want to use; to attract and retain site visitors, you need to create an accessible site that provides a good user experience. building websites requires html, css, and javascript, typically including binary file types such as images and video. the decisions you make and the tools you choose as you build your site can greatly affect the performance of the finished work. good performance is an asset. bad performance is a liability. site speed directly affects bounce rates, conversion, revenue, user satisfaction, and search engine ranking. performant sites have been shown to increase visitor retention and user satisfaction. slow content has been shown to lead to site abandonment, with some visitors leaving to never return. reducing the amount of data that...
Accessibility in React - Learn web development
klength]); we only try to focus on our list heading if we have fewer tasks now than we did before. the dependencies passed into this hook ensure it will only try to re-run when either of those values (the number of current tasks, or the number of previous tasks) changes. now, when you delete a task in your browser, you will see our dotted focus outline appear around the heading above the list. finished! you've just finished building a react app from the ground up! congratulations! the skills you’ve learned here will be a great foundation to build on as you continue working with react. most of the time, you can be an effective contributor to a react project even if all you do is think carefully about components and their state and props. remember to always write the best html you can. use...
...l you can. useref() and useeffect() are somewhat advanced features, and you should be proud of yourself for using them! look out for opportunities to practice them more, because doing so will allow you to create inclusive experiences for users. remember: our app would have been inaccessible to keyboard users without them! note: if you need to check your code against our version, you can find a finished version of the sample react app code in our todo-react repository. for a running live version, see https://mdn.github.io/todo-react-build/. in the very last article we'll present you with a list of react resources that you can use to go further in your learning. previous overview: client-side javascript frameworks next in this module introduction to client-side frameworks framew...
React interactivity: Editing, filtering, conditional rendering - Learn web development
this includes allowing you to edit existing tasks, and filtering the list of tasks between all, completed, and incomplete tasks. we'll look at conditional ui rendering along the way. prerequisites: familiarity with the core html, css, and javascript languages, knowledge of the terminal/command line. ...
...different buttons have been given their respective names. when you press a filter button, you should see its text take on a new outline — this tells you it has been selected. and if you look at your devtool’s page inspector while clicking the buttons, you'll see the aria-pressed attribute values change accordingly. however, our buttons still don't actually filter the todos in the ui! let's finish this off. filtering tasks in the ui right now, our tasklist constant in app() maps over the tasks state and returns a new <todo /> component for all of them. this is not what we want! a task should only render if it is included in the results of applying the selected filter. before we map over the tasks state, we should filter it (with array.prototype.filter()) to eliminate objects we don't wan...
Deployment and next steps - Learn web development
s://vercel.com/opensas/mdn-svelte-tutorial/[...] [1s] ✅ production: https://mdn-svelte-tutorial.vercel.app [copied to clipboard] [19s] deployed to production. run `vercel --prod` to overwrite later (https://vercel.link/2f). to change the domain or build command, go to https://zeit.co/opensas/mdn-svelte-tutorial/settings accept all the defaults, and you'll be fine. once it has finished deploying, go to the "production" url in your browser, and you'll see the app deployed! you can also import a svelte git project into vercel from github, gitlab, or bitbucket. note: you can globally install vercel with npm i -g vercel so you don't have to use npx to run it. automatic deployment to gitlab pages for hosting static files there are several online services that allow you to...
...3), reused 0 (delta 0) to gitlab.com:opensas/mdn-svelte-todo.git 7dac9f3..5725f46 master -> master whenever there's a job running gitlab will display an icon showing the process of the job. clicking on it will let you inspect the output of the job. you can also check the progress of the current and previous jobs from the ci / cd > jobs menu option of your gitlab project. once gitlab finishes building and publishing your app, it will be accessible at https://your-user.gitlab.io/mdn-svelte-todo/; in my case it's https://opensas.gitlab.io/mdn-svelte-todo/. you can check your page's url in gitlab's ui — see the settings > pages menu option. with this configuration, whenever you push changes to the gitlab repo, the application will be automatically rebuilt and deployed to gitlab page...
Advanced Svelte: Reactivity, lifecycle, accessibility - Learn web development
tions...>, check the svelte options documentation. all of these solutions involve an assignment in which the updated variable is on the left side of the equation. any of this techniques will allow svelte to notice that our todos array has been modified. choose one, and update your checkalltodos() function as required. now you should be able to check and uncheck all your todos at once. try it! finishing our moreactions component we will add one usability detail to our component. we'll disable the buttons when there are no tasks to be processed. to create this we'll receive the todos array as a prop, and set the disabled property of each button accordingly. update your moreactions.svelte component like this: <script> import { createeventdispatcher } from 'svelte' const dispatch =...
... our repo like this: cd mdn-svelte-tutorial/06-stores or directly download the folder's content: npx degit opensas/mdn-svelte-tutorial/06-stores remember to run npm install && npm run dev to start your app in development mode. repl to see the current state of the code in a repl, visit: https://svelte.dev/repl/d1fa84a5a4494366b179c87395940039?version=3.23.2 summary in this article we have finished adding all the required functionality to our app, plus we've taken care of a number of accessibility and usability issues. we also finished splitting our app into manageable components, each one with a unique responsibility. in the meantime, we saw a few advanced svelte techniques, like: dealing with reactivity gotchas when updating objects and arrays. working with dom nodes using bind:thi...
Introduction to automated testing - Learn web development
http://mdn.github.io/learning-area/javascript/building-blocks/events/show-video-box-fixed.html, for example), then choose a browser/os combination you want to test by using the different buttons and lists. there is a lot of choice, as you'll see! when you click start session, a loading screen will then appear, which spins up a virtual machine running the combination you chose. when loading has finished, you can then start to remotely test the web site running in the chosen browser. from here you can see the layout as it would look in the browser you are testing, move the mouse around and try clicking buttons, etc. the top menu allows you to: stop the session give someone else a url so they can observe the test remotely. copy text/notes to a remote clipboard. take a screenshot.
... lists the various options you can choose from. for now, make sure you are on the live web testing tab. enter the url of the page you want to test. choose the browser/os combination you want to test by selecting the combination in the grid. when you click start browser, a loading screen will then appear, which spins up a virtual machine running the combination you chose. when loading has finished, you can then start to remotely test the web site running in the chosen browser. from here you can see the layout as it would look in the browser you are testing, move the mouse around and try clicking buttons, etc. the side menu allows you to: stop the session change the screen resolution copy text/notes to a remote clipboard take, edit, and download screenshots test in full...
Setting up your own test automation environment - Learn web development
e we used this construct to tab out of the form input before submitting it: driver.sleep(1000).then(function() { driver.findelement(by.name('q')).sendkeys(webdriver.key.tab); }); waiting for something to complete there are times where you'll want to make webdriver wait for something to complete before carrying on. for example if you load a new page, you'll want to wait for the page's dom to finish loading before you try to interact with any of its elements, otherwise the test will likely fail. in our google_test.js test for example, we included this block: driver.sleep(2000).then(function() { driver.gettitle().then(function(title) { if(title === 'webdriver - google search') { console.log('test passed'); } else { console.log('test failed'); } }); }); the sleep...
...bute() to retrieve it's value attribute value, and print a message to the console if it is not empty. note: there is also a method called wait(), which repeatedly tests a condition for a certain length of time, and then carries on executing the code. this also makes use of the util library, which defines common conditions to use along with wait(). shutting down drivers after use after you've finished running a test, you should shut down any driver instances you've opened, to make sure that you don't end up with loads of rogue browser instances open on your machine! this is done using the quit() method. simply call this on your driver instance when you are finished with it. add this line to the bottom of your quick_test.js test now: driver.quit(); when you run it, you should now see the te...
Command line crash course - Learn web development
for example man ls. this will open up the man page in the terminal’s default text file viewer (for example, less in my terminal), and you should then be able to scroll through the page using the arrow keys, or some similar mechanism. the man page lists all the options in great detail, which may be a bit intimidating to begin with, but at least you know it’s there if you need it. once you are finished looking through the man page, you need to quit out of it using your text viewer’s quit command ("q" in less; you may have to search on the web to find it if it isn’t obvious). note: to run a command with multiple options at the same time, you can usually put them all in a single string after the dash character, for example ls -lah, or ls -ltrh. try looking at the ls man page to work out ...
..., ensuring that colleagues and friends who work on your code use the code style you’re using. be configured to run upon save, as you type, or even before publishing your code (with additional tooling that we’ll see later on in the module). once you've installed node, open up the terminal and run the following command to install prettier: npm install --global prettier once the command has finished running, the prettier tool is now available in your terminal, at any location in your file system. running the command without any arguments, as with many other commands, will offer up usage and help information. try this now: prettier your output should look something like this: usage: prettier [options] [file/glob ...] by default, output is written to stdout. stdin is read if it is piped...
Deploying our app - Learn web development
t-side tools in the final article in our series, we take the example toolchain we built up in the previous article and add to it so that we can deploy our sample app. we push the code to github, deploy it using netlify, and even show you how to add a simple test into the process. prerequisites: familiarity with the core html, css, and javascript languages. objective: to finish working through our complete toolchain case study, focusing on deploying the app. post development there's potentially a large range of problems to be solved in this section of the project's lifecycle. as such, it's important to create a toolchain that handles these problems in a way that requires as little manual intervention as possible. here's just a few things to consider for this pa...
...to the next step. since we've connected netlify to our github account and given it access to deploy the project repository, netlify will ask how to prepare the project for deployment and what to deploy. you should enter the command npm run build for the build command, and specify the dist directory for the publish directory — this contains the code that we want to make public. to finish up, click deploy site. after a short wait for the deployment to occur, you should get a url that you can go to, to see your published site — try it out! and even better, whenever we make a change and push the change to our remote git repository (on github), this will trigger a notification to netlify which will then run our specified build task and then deploy the resulting dist...
Debugging Frame Reflow
general overview the frame reflow can be logged with the debug capabilities implemented in nsframe.cpp. it provides the following information for each frame at the start of its reflow reflow reason available width, available height computed width, computed height the previous and the next frame in flow and a count number. when the frame's reflow is finished the following information is displayed : reflow metric (desired) width, height max. element width maximum width frame status overflow area getting the log make sure that your build is a debug build (in short you need ac_add_options --enable-debug in your .mozconfig file). create a text file (for instance reflow_rules.txt). enter this line in the text file * 1 this should look like: point the...
...the max. element size only once and it reports now: block 02d7bcf8 d=1410,300 the block shows the same address as the previous one. frames with children that overflow the parent have the ns_frame_outside_children flag set. for these frames the overflow area is displayed as block 025ed8f0 d=8940,1020 o=(0,0) 9180 x 1020. the overflow area is specified as (x,y) origin and width x height. the reflow finishes at the same level where it started. advanced reflow debugging the previously described technique dumps the data for every frame. sometimes the log is clearer if only the main frames are shown. the entries in the reflow log can be controlled on a frame level. for instance adding text 0 to the rules in reflow_rules.txt would hide the text entries from the reflow. the display of the following fram...
How Mozilla's build system works
ectories. as the moz.build files are read, data structures describing the overall build system definition are emitted. these data structures are then read by a build backend generator, which then converts them into files, function calls, and so on. in the case of a make backend, the generator writes out makefiles. when config.status runs, you'll see the following output: reticulating splines... finished reading 1096 moz.build files into 1276 descriptors in 2.40s backend executed in 2.39s 2188 total backend files. 0 created; 1 updated; 2187 unchanged total wall time: 5.03s; cpu time: 3.79s; efficiency: 75% what this is saying is that a total of 1,096 moz.build files were read. altogether, 1,276 data structures describing the build configuration were derived from them. it took 2.40s wall time j...
.... the build system stream describing class instances emitted from treemetadataemitter is then fed into a build backend. a build backend is simply an instance of a child class of a buildbackend from base.py (in the mozbuild.backend package now, not mozbuild.frontend). the child class implements methods for processing individual class instances as well as common hook points, such as processing has finished. see recursivemake.py for an implementation of a buildbackend. although we call the base class buildbackend, the class doesn't need to be focused with building at all. if you wanted to create a consumer that performed a line count of all c++ files or generated a clang compilation database, for example, this would be an acceptable use of a buildbackend. technically, we don't need to feed the t...
Eclipse CDT
e preferences, you may want to go to "c/c++ > debug > gdb" and deselect "stop on startup at", so that eclipse won't automatically break in main() when it launches firefox for debugging. to debug, click the debug button on the toolbar, or select "run > debug" from the menu bar. it's not obvious, but you can get a gdb prompt in the console so that you can type gdb commands directly. after you've finished debugging, you can get back to the c/c++ perspective (i.e. window layout) via the menubar by selecting "window > open perspective > c/c++". upgrading gdb on mac the ancient, barely maintained apple fork of gdb that comes with xcode on mac is really horrible. if you use mac, you may want to build the latest fsf version of gdb and set eclipse to use that gdb for debugging. one suggested configu...
...k "ok", then "ok" again. type "nightly" into the "work with" field and select the repository that you just added. (if it doesn't appear, close the window, reopen it from the help menu, and try again.) a "cdt main features" option should now have been added in the area below. tick this (all of its sub-options should then be ticked), click "next" twice, accept the license agreement, and then click "finish". eclipse should now update itself and ask you to restart. troubleshooting: if you get an error when trying to update, try clicking "available software sites" in the "install" window, make sure "juno" is still unticked, that "nightly" is ticked, highlight "nightly", click "reload", "ok", and then try again. troubleshooting here is a list of problems people have encountered, and suggestions for...
Multiple Firefox profiles
et. you can also choose where to store the profile on your computer. to select storage location, click choose folder.... if you choose your folder location for the profile, select a new or empty folder. if you choose a folder that isn't empty, and you later remove the profile and choose the \"delete files\" option, everything inside that folder will be deleted. to create the new profile, click finish. creating a profile through the firefox browser you can create a new firefox profile directly from the browser. type about:profiles into the browser url search bar on the page, click create a new profile button read the introduction, and click next enter a profile name for your new profile. use a profile name that is descriptive, such as your personal name. this name is not exposed to th...
... the browser url search bar on the page, click create a new profile button read the introduction, and click next enter a profile name for your new profile. use a profile name that is descriptive, such as your personal name. this name is not exposed to the internet. optionally, to change where the profile will be stored on your computer, click choose folder... to create the new profile, click finish. deleting a profile in the profile manager, select the profile to remove, and click delete profile.... confirm that you wish to delete the profile: don't delete files removes the profile from the profile manager yet retains the profile data files on your computer in the storage folder so that your information is not lost. "don't delete files" is the preferred option, because it saves ...
Performance best practices for Firefox front-end engineers
ly scoped to the entire document, the cost of doing these style calculations is proportional to the number of dom nodes in the document (and the number of styles being applied). it is expected that over time, script will update the dom, requiring us to recalculate styles. normally, the changes to the dom just result in the standard style calculation occurring immediately after the javascript has finished running during the 16ms window, inside the "style" step. that's the ideal scenario. however, it's possible for script to do things that force multiple style calculations (or style flushes) to occur synchronously during the javascript part of the 16 ms window. the more of them there are, the more likely they'll exceed the 16ms frame budget. if that happens, some of them will be postponed until ...
...layout step can be seen in the “16ms” pipeline graphic above, and occurs just before we paint things to be composited for the user to see. it is expected that over time, script will update the dom, requiring us to recalculate styles, and then update layout. normally, however, the changes to the dom just result in the standard style calculation that occurs immediately after the javascript has finished running during the 16ms window. interruptible reflow since the early days, gecko has had the notion of interruptible reflow. this is a special type of content-only reflow that checks at particular points whether or not it should be interrupted (usually to respond to user events). because interruptible reflows can only be interrupted when laying out content, and not chrome ui, the rest of thi...
Using the Browser API
Mozilla › Gecko › Chrome › API › Browser API › Using
1; ... zoomin.addeventlistener('touchend',function() { zoomfactor += 0.1; browser.zoom(zoomfactor); }); zoomout.addeventlistener('touchend',function() { zoomfactor -= 0.1; browser.zoom(zoomfactor); }); controlling the stop/reload button next, let's talk about the stop/reload button. as in a traditional browser, this is a single button that acts as a reload button when the page has finished loading, and a stop button while the page is loading (each with a different icon displayed). this is implemented in our sample app with the following functions: browser.addeventlistener('mozbrowserloadstart',function() { stopreload.textcontent = 'x'; }); browser.addeventlistener('mozbrowserloadend',function(e) { canmovebwd(); canmovefwd(); stopreload.textcontent = 'r'; console.log(e...
...loadend',function(e) { canmovebwd(); canmovefwd(); stopreload.textcontent = 'r'; console.log(e.detail.backgroundcolor); controls.style.background = e.detail.backgroundcolor; }); when the mozbrowserloadstart event fires, the latest page request has started loading, and we change the button to a cross to indicate "stop". when the mozbrowserloadend event fires, the latest page request has finished loading, and at this point we want to change the icon back to the reload icon (in this case we are just using a capital "r"). notice that this is also where we call the canmovebwd() and canmovefwd() functions we discussed earlier — it makes sense to update the status of the back and forward buttons after each page reload. in addition, the background of the controls ui bar is changed to the b...
Embedding Tips
t flags, and from the nsirequest argument qi fornsihttpchanne and call methods on that to determine response codes and other information from the server. it is left as an exercise to make this sample synchronous, i.e. wait for persistence to complete before returning. hint, add a native message processing loop after the call to saveuri that terminates when onstatechange indicates persistence has finished.. how do i print a page? query the web browser object for nsiwebbrowserprint. call the nsiwebbrowserprint::print() method supplying a print settings object (e.g. that returned from nsiwebbrowserprint::getglobalprintsettings) that you wish to print the page with. how do i print preview a page? query the web browser object for the nsiwebbrowserprint interface. call the nsiwebbrowserprint::pri...
...th. how do i print preview a page? query the web browser object for the nsiwebbrowserprint interface. call the nsiwebbrowserprint::printpreview() method supplying a print settings object (e.g. that returned from nsiwebbrowserprint::getglobalprintsettings()) that you wish to preview the page with. the nsiwebbrowserprint::printpreviewnavigate() method can be used to step through the pages. when finished with preview mode, call nsiwebbrowserprint::exitprintpreview(). how do i get popup windows working? implement and register a nsiwindowcreator object with the window watcher service. the nsiwindowcreator::createchromewindow method will be called whenever gecko needs to open a new window. this method should create the new browser window in the specified style and hand back the nsiwebbrowserchro...
Downloads.jsm
file. alternatively, may be an nsifile or a downloadtarget object. aoptions optional an optional object used to control the behavior of this function. you may pass an object with a subset of the following fields: isprivate: optional indicates whether the download originated from a private window. if omitted, the download is public. promise resolves to undefined when the download has finished successfully and you can access the target file. promise can be rejected with downloaderror if the download failed. getlist() retrieves the specified type of downloadlist object. there is one download list for each type, and this method always retrieves a reference to the same download list when called with the same argument. calling this function may cause the download list to be reloaded...
...emoveview(view); } }).then(null, components.utils.reporterror); conversion from nsidownloadmanager starting in firefox for desktop version 26, the nsidownloadmanager and nsidownload interfaces are not available anymore. the new module works differently from the old component. in general, you should be aware of the following highlights: there is no difference between active downloads and finished downloads. the download object can be used without requiring direct database access. observer notifications (for example, "dl-done") and download listeners are replaced by views on the downloadlist object returned by the getlist() method. object identity replaces the use of numeric identifiers. you can use download objects as keys in a set or map to associate your own state to them for the se...
OS.File for the main thread
tion mode, as per windows function createfile. this also requires option winaccess and this replaces argument mode. if unspecified, value is built from mode. promise resolves to an instance of os.file representing the expected file. note that the operating system limits the number of files that can be opened simultaneously by one process, so do not forget to close that file once you have finished it, to ensure that you are not blocking the rest of the process. when opening files for writing, they will be opened for appending unless you specify append: false in gecko 27 and later. in gecko 26 and earlier, on platforms other than windows, the files will be opened for appending unless you specify explicit unixflags or open the file with either create or truncate flags. in gecko 26 and ea...
...a file and release any associated resource. once the file is closed, any attempt to call methods of the file object will raise an error. an example is seen here. in this example the contents is not written to file until .close is called. note that the operating system limits the number of files that can be opened simultaneously by one process, so do not forget to close that file once you have finished it to make sure that you are not blocking the rest of the process. promise<void> close() flush() flushes the file's internal buffers, ensuring that all data still in these buffers is now written to disk. disk flushes are very expensive and therefore should be used carefully, sparingly, and only in scenarios where it is vital that data survives system crashes. even though the function will ...
Examples
"you have file.txt in your temporary directory."); } else { console.log("you don't have file.txt in your temporary directory."); } }); // unexpected errors should always be reported at the end of a promise chain. let lastpromise = newpromise.then(null, components.utils.reporterror); in this case, if the file existence check succeeds, the onfulfill callback is invoked. when the callback finishes execution, newpromise will be fulfilled with an undefined fulfillment value, because the callback does not return any value. when newpromise is fulfilled, nothing happens, because no fulfillment callback is specified and the return value of the last then method is ignored. if the file existence check fails, for example because access is denied, promise is rejected with an os.file.error instanc...
...this value: " + avalue); }, function onreject(areason) { console.log("rejected with this reason: " + areason); }); // unexpected errors should always be reported at the end of a promise chain. newpromise.then(null, components.utils.reporterror); note: more examples for consuming promises are available in the promise object documentation. make user defined promise return after multiple images finish loading (promise.all and promise.defer) this example shows how to use promise.all to wait to create multiple promises with promise.defer() and return at the end of it. components.utils.import("resource://gre/modules/promise.jsm"); var mypromise = myuserdefinedpromise(); mypromise.then( function(asuccessreason) { alert('mypromise was succesful and reason was = "' + asuccessreason + '"'); ...
QA phase
mpile-environment ac_add_options --with-l10n-base=../l10n-central # path relative to moz_objdir ac_add_options --enable-application=[browser or mail] you will need to specify which application you're localizing in the fourth line (e.g., for firefox, that's browser, thunderbird would be mail). enter the following command to perform the configuration: $ ./mach configure once your command-line finishes spitting out the config command's output, navigate to the newly created directory: $ cd ../firefox-build/browser/locales now you're ready to build! at this point you can choose between two build options. you can either: create a langpack, which is installed on top of your mozilla application, or repack the application's binary (aka, a l10n repack), which allows you to install next to your...
...s adding file changes added 1 changesets with 2 changes to 2 files bb/acl: your_id is allowed. accepted payload. quota: 979.7 kb in use, 150.0 mb available (0.64% used) your changeset has been successfully pushed to your repository! as you begin to move through your translations, you should commit the changes locally and push your work to this experimental repository. for instance, if you have finished translating all the .dtd and .properties files in your x-testing/browser/chrome/browser/ directory, then you should run these commands: $ hg status $ hg commit -m "translated browser/chrome/browser/" $ hg outgoing $ hg push http://hg.mozilla.org/l10n-central/x-testing note that due to the distributed nature of hg, hg commit saves the changes locally (i.e., in your computer's hg repository). y...
Gecko Profiler FAQ
that overall amount to something significant. how to go from a web-page to a micro-benchmark which is representative of the web-page? please let me know if you find a way to do this. it would make our job a lot easier. in the off-chance where we have been able to do this, it typically happens as one of the last stages of the work, since you’d typically have finished fully analyzing the issue and through that have managed to figure out how to write a micro-benchmark that reproduces the exact issue. it’s better to start getting used to profiling and analyzing real pages more. :-) what's the best way to profile startup performance? install the gecko profiler add-on. quit the browser. start the browser with the environme...
...s you double-check that the problems you find are actually present on windows, it doesn’t matter much what platform you find them on. [ehsan] that being said, we do see a lot of windows-specific issues that you will not find on other platforms, for example sometimes code calls into a windows api that requires loading a dll the first time you call it that takes 10s of milliseconds to finish, etc. unless if you profile on windows you will never find those specific issues. and when you get to the platform specific parts of the browser stack (such as graphics, media, etc.) then profiling on windows would be certainly a lot more valuable than on other platforms. should i profile known to be slow sites on slower hardware to get a better signal? [msta...
Enc Dec MAC Using Key Wrap CertReq PKCS10 CSR
etcertificaterequestextensions(certreq, &crexts); if (rv != secsuccess) { pr_fprintf(pr_stderr, "%s\n", port_errortostring(rv)); goto cleanup; } rv = cert_mergeextensions(exthandle, crexts); if (rv != secsuccess) { pr_fprintf(pr_stderr, "%s\n", port_errortostring(rv)); goto cleanup; } } cert_finishextensions(exthandle); /* self-signing a cert request, find the private key */ if (*selfsignprivkey == null) { *selfsignprivkey = pk11_findkeybydercert(slot, subjectcert, pwarg); if (!*selfsignprivkey) { pr_fprintf(pr_stderr, "failed to locate private key.\n"); rv = secfailure; goto cleanup; } } certder = signcer...
... goto cleanup; } arena = port_newarena(der_default_chunksize); if (!arena) { fprintf(stderr, "out of memory"); rv = secfailure; goto cleanup; } exthandle = cert_startcertificaterequestattributes(cr); if (exthandle == null) { port_freearena (arena, pr_false); rv = secfailure; goto cleanup; } cert_finishextensions(exthandle); cert_finishcertificaterequestattributes(cr); /* der encode the request */ encoding = sec_asn1encodeitem(arena, null, cr, sec_asn1_get(cert_certificaterequesttemplate)); if (encoding == null) { pr_fprintf(pr_stderr, "der encoding of request failed\n"); rv = secfailure; goto cleanup; }...
sample2
0 && secoid_findoidtag(&certreq->attributes[0]->attrtype) == sec_oid_pkcs9_extension_request) { rv = cert_getcertificaterequestextensions(certreq, &crexts); if (rv != secsuccess) { pr_fprintf(pr_stderr, "%s\n", port_errortostring(rv)); goto cleanup; } rv = cert_mergeextensions(exthandle, crexts); if (rv != secsuccess) { pr_fprintf(pr_stderr, "%s\n", port_errortostring(rv)); goto cleanup; } } cert_finishextensions(exthandle); /* self-signing a cert request, find the private key */ if (*selfsignprivkey == null) { *selfsignprivkey = pk11_findkeybydercert(slot, subjectcert, pwarg); if (!*selfsignprivkey) { pr_fprintf(pr_stderr, "failed to locate private key.\n"); rv = secfailure; goto cleanup; } } certder = signcert(handle, subjectcert, selfsign, hashalgtag, *selfsignprivkey, issuernickname,pwarg); ...
...spki, null); if (!cr) { pr_fprintf(pr_stderr, "unable to make certificate request\n"); rv = secfailure; goto cleanup; } arena = port_newarena(der_default_chunksize); if (!arena) { fprintf(stderr, "out of memory"); rv = secfailure; goto cleanup; } exthandle = cert_startcertificaterequestattributes(cr); if (exthandle == null) { port_freearena (arena, pr_false); rv = secfailure; goto cleanup; } cert_finishextensions(exthandle); cert_finishcertificaterequestattributes(cr); /* der encode the request */ encoding = sec_asn1encodeitem(arena, null, cr, sec_asn1_get(cert_certificaterequesttemplate)); if (encoding == null) { pr_fprintf(pr_stderr, "der encoding of request failed\n"); rv = secfailure; goto cleanup; } /* sign the request */ signalgtag = sec_getsignaturealgorithmoidtag(keytype, hashalgtag); if...
NSS PKCS11 Functions
te database or to the nickname in the token. passwordarg a pointer to application data for the password callback function. this pointer is set with ssl_setpkcs11pinarg during ssl configuration. to retrieve its current value, use ssl_revealpinarg. returns the function returns one of these values: if successful, a pointer to a certificate structure. if unsuccessful, null. description when you are finished with the certificate structure returned by pk11_findcertfromnickname, you must free it by calling cert_destroycertificate. the pk11_findcertfromnickname function calls the password callback function set with pk11_setpasswordfunc and passes it the pointer specified by the wincx parameter. pk11_findkeybyanycert finds the private key associated with a specified certificate in any available slot. s...
...icate structure in the certificate database. passwordarg a pointer to application data for the password callback function. this pointer is set with ssl_setpkcs11pinarg during ssl configuration. to retrieve its current value, use ssl_revealpinarg. returns the function returns one of these values: if successful, a pointer to a private key structure. if unsuccessful, null. description when you are finished with the private key structure returned by pk11_findkeybyanycert, you must free it by calling seckey_destroyprivatekey. the pk11_findkeybyanycert function calls the password callback function set with pk11_setpasswordfunc and passes it the pointer specified by the wincx parameter. pk11_getslotname gets the name of a slot. syntax #include <pk11pub.h> char *pk11_getslotname(pk11slotinfo *slot)...
PKCS 7 functions
2 and later sec_pkcs7createencrypteddata mxr 3.2 and later sec_pkcs7createenvelopeddata mxr 3.2 and later sec_pkcs7createsigneddata mxr 3.2 and later sec_pkcs7decodeitem mxr 3.2 and later sec_pkcs7decoderabort mxr 3.9 and later sec_pkcs7decoderfinish mxr 3.2 and later sec_pkcs7decoderstart mxr 3.2 and later sec_pkcs7decoderupdate mxr 3.2 and later sec_pkcs7decryptcontents mxr 3.2 and later sec_pkcs7destroycontentinfo mxr 3.2 and later sec_pkcs7encode mxr 3.3 and later sec_pkcs7...
... mxr 3.2 and later sec_pkcs7decryptcontents mxr 3.2 and later sec_pkcs7destroycontentinfo mxr 3.2 and later sec_pkcs7encode mxr 3.3 and later sec_pkcs7encodeitem mxr 3.9.3 and later sec_pkcs7encoderabort mxr 3.9 and later sec_pkcs7encoderfinish mxr 3.2 and later sec_pkcs7encoderstart mxr 3.2 and later sec_pkcs7encoderupdate mxr 3.2 and later sec_pkcs7getcertificatelist mxr 3.2 and later sec_pkcs7getcontent mxr 3.2 and later sec_pkcs7getencryptionalgorithm mxr 3.2 and later ...
FC_DigestFinal
if pdigest is null the length of the digest is returned and fc_digestfinal may be called again with pdigest set to retrieve the digest. a user may call fc_digestfinal without logging into the token (to assume the nss user role). ...
...if pdigest is null the length of the digest is returned and fc_digestfinal may be called again with pdigest set to retrieve the digest. a user may call fc_digestfinal without logging into the token (to assume the nss user role). ...
FC_SignFinal
if psignature is null the length of the signature is returned and fc_signfinal may be called again with psignature set to retrieve the signature. a user must log into the token (to assume the nss user role) before calling fc_signfinal. ...
...if psignature is null the length of the signature is returned and fc_signfinal may be called again with psignature set to retrieve the signature. a user must log into the token (to assume the nss user role) before calling fc_signfinal. ...
FC_VerifyFinal
a user must log into the token (to assume the nss user role) before calling fc_verifyfinal. ...
...a user must log into the token (to assume the nss user role) before calling fc_verifyfinal. ...
pkfnc.html
hese values: if successful, a pointer to a certificate structure. if unsuccessful, null. description a nickname is an alias for a certificate subject. there may be multiple certificates with the same subject, and hence the same nickname. this function will return the newest certificate that matches the subject, based on the notbefore / notafter fields of the certificate. when you are finished with the certificate structure returned by pk11_findcertfromnickname, you must free it by calling cert_destroycertificate. the pk11_findcertfromnickname function calls the password callback function set with pk11_setpasswordfunc and passes it the pointer specified by the wincx parameter. pk11_findkeybyanycert finds the private key associated with a specified certificate in any available s...
...cx a pointer to application data for the password callback function. this pointer is set with ssl_setpkcs11pinarg during ssl configuration. to retrieve its current value, use ssl_revealpinarg. returns the function returns one of these values: if successful, a pointer to a private key structure. if unsuccessful, null. description when you are finished with the private key structure returned by pk11_findkeybyanycert, you must free it by calling seckey_destroyprivatekey. the pk11_findkeybyanycert function calls the password callback function set with pk11_setpasswordfunc and passes it the pointer specified by the wincx parameter. pk11_getslotname gets the name of a slot. syntax #include <pk11func.h> char *pk11_getslotname(pk11slotinfo...
sslerr.html
ssl_error_rx_malformed_hello_done -12255 "ssl received a malformed server hello done handshake message." ssl_error_rx_malformed_cert_verify -12254 "ssl received a malformed certificate verify handshake message." ssl_error_rx_malformed_client_key_exch -12253 "ssl received a malformed client key exchange handshake message." ssl_error_rx_malformed_finished -12252 "ssl received a malformed finished handshake message." ssl_error_rx_malformed_new_session_ticket -12178 "ssl received a malformed new session ticket handshake message." received a malformed (too long or short) ssl record: all the error codes in the following block indicate that the local socket received an improperly formatted ssl3 record from the ...
..._error_rx_unexpected_hello_done -12241 "ssl received an unexpected server hello done handshake message." ssl_error_rx_unexpected_cert_verify -12240 "ssl received an unexpected certificate verify handshake message." ssl_error_rx_unexpected_client_key_exch -12239 "ssl received an unexpected client key exchange handshake message." ssl_error_rx_unexpected_finished -12238 "ssl received an unexpected finished handshake message." ssl_error_rx_unexpected_new_session_ticket -12179 "ssl received an unexpected new session ticket handshake message." received an ssl record that was inappropriate for the current state: all the error codes in the following block indicate that the local socket received an ssl3 record from the ...
S/MIME functions
ata mxr 3.2 and later nss_cmscontentinfo_setcontent_encrypteddata mxr 3.2 and later nss_cmscontentinfo_setcontent_envelopeddata mxr 3.2 and later nss_cmscontentinfo_setcontent_signeddata mxr 3.2 and later nss_cmsdecoder_cancel mxr 3.2 and later nss_cmsdecoder_finish mxr 3.2 and later nss_cmsdecoder_start mxr 3.2 and later nss_cmsdecoder_update mxr 3.2 and later nss_cmsdigestcontext_cancel mxr 3.2 and later nss_cmsdigestcontext_finishmultiple mxr 3.2 and later nss_cmsdigestcontext_finishsingle mxr 3.2 and late...
...and later nss_cmsdigesteddata_create mxr 3.2 and later nss_cmsdigesteddata_destroy mxr 3.2 and later nss_cmsdigesteddata_getcontentinfo mxr 3.2 and later nss_cmsderencode mxr 3.2 and later nss_cmsencoder_cancel mxr 3.2 and later nss_cmsencoder_finish mxr 3.2 and later nss_cmsencoder_start mxr 3.2 and later nss_cmsencoder_update mxr 3.2 and later nss_cmsencrypteddata_create mxr 3.2 and later nss_cmsencrypteddata_destroy mxr 3.2 and later nss_cmsencrypteddata_getcontentinfo mxr 3.2 and later ...
Utility functions
3.4 and later sec_asn1decodeinteger mxr 3.2 and later sec_asn1decodeitem mxr 3.2 and later sec_asn1decoderabort mxr 3.9 and later sec_asn1decoderclearfilterproc mxr 3.2 and later sec_asn1decoderclearnotifyproc mxr 3.2 and later sec_asn1decoderfinish mxr 3.2 and later sec_asn1decodersetfilterproc mxr 3.2 and later sec_asn1decodersetnotifyproc mxr 3.2 and later sec_asn1decoderstart mxr 3.2 and later sec_asn1decoderupdate mxr 3.2 and later sec_asn1encode mxr 3.2 and later sec_asn...
...later sec_asn1encodeitem mxr 3.2 and later sec_asn1encoderabort mxr 3.9 and later sec_asn1encoderclearnotifyproc mxr 3.2 and later sec_asn1encoderclearstreaming mxr 3.2 and later sec_asn1encodercleartakefrombuf mxr 3.2 and later sec_asn1encoderfinish mxr 3.2 and later sec_asn1encodersetnotifyproc mxr 3.2 and later sec_asn1encodersetstreaming mxr 3.2 and later sec_asn1encodersettakefrombuf mxr 3.2 and later sec_asn1encoderstart mxr 3.2 and later sec_asn1encoderupdate mxr 3.2 and later ...
NSS tools : signtool
e installed on the machines to which you are distributing it. before you can use netscape signing tool to sign files, you must have an object-signing certificate, which is a special certificate whose associated private key is used to create digital signatures. for testing purposes only, you can create an object-signing certificate with netscape signing tool 1.3. when testing is finished and you are ready to disitribute your software, you should obtain an object-signing certificate from one of two kinds of sources: * an independent certificate authority (ca) that authenticates your identity and charges you a fee. you typically get a certificate from an independent ca if you want to sign software that will be distributed over the internet. * ca server soft...
...if you are installing the keys and certificate in the communicator databases, you must exit communicator before using this option; otherwise, you risk corrupting the databases. in all cases, the certificate is also output to a file named x509.cacert, which has the mime-type application/x-x509-ca-cert. unlike certificates normally used to sign finished code to be distributed over a network, a test certificate created with -g is not signed by a recognized certificate authority. instead, it is self-signed. in addition, a single test signing certificate functions as both an object-signing certificate and a ca. when you are using it to sign objects, it behaves like an object-signing certifica...
JS::CompileOffThread
thread for execution. syntax bool js::cancompileoffthread(jscontext *cx, const js::readonlycompileoptions &options, size_t length); bool js::compileoffthread(jscontext *cx, const js::readonlycompileoptions &options, const char16_t *chars, size_t length, js::offthreadcompilecallback callback, void *callbackdata); jsscript * js::finishoffthreadscript(jscontext *maybecx, jsruntime *rt, void *token); typedef void (*js::offthreadcompilecallback)(void *token, void *callbackdata); name type description cx / maybe jscontext * pointer to a js context from which to derive runtime information. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. rt js...
...s is the string containing the text of the script. length indicates the size of the text version of the script in characters. after successfully triggering an off thread compile of a script, the callback will eventually be invoked with the specified data and a token for the compilation. the callback will be invoked while off the main thread, so its operations must be thread safe. afterwards, js::finishoffthreadscript must be invoked on the main thread to get the result script or nullptr. if maybecx is not specified, the resources will be freed, but no script will be returned. the characters passed in to js::compileoffthread must remain live until the callback is invoked, and the resulting script will be rooted until the call to finishoffthreadscript. see also the jsapi user guide contains ...
JSAPI reference
that has a corresponding spidermonkey release with the old scheme, where the jsapi has the version 1.8.5. ...
...nce jsapi 30 js_evaluatescriptforprincipalsversion obsolete since jsapi 30 js_evaluateucscriptforprincipalsversion obsolete since jsapi 30 you can instead compile javascript code into a jsscript which you can then execute multiple times. ...
nsICryptoHMAC
netwerk/base/public/nsicryptohmac.idlscriptable this interface provides hmac signature algorithms. 1.0 66 introduced gecko 1.9 inherits from: nsisupports last changed in gecko 1.9 (firefox 3) method overview acstring finish(in prbool aascii); void init(in unsigned long aalgorithm, in nsikeyobject akeyobject); void reset(); void update([const, array, size_is(alen)] in octet adata, in unsigned long alen); void updatefromstream(in nsiinputstream astream, in unsigned long alen); constants hashing algorithms. these values are to be used by the init() method to indicate which hashing function to use. these values map onto the values defined in mozilla/security/nss/lib/softoken/pkcs11t.h and are switched to ckm_*_hmac ...
.../pkcs11t.h and are switched to ckm_*_hmac constant. constant value description md2 1 message digest algorithm 2 md5 2 message-digest algorithm 5 sha1 3 secure hash algorithm 1 sha256 4 secure hash algorithm 256 sha384 5 secure hash algorithm 384 sha512 6 secure hash algorithm 512 methods finish() completes this hmac object and produces the actual hmac diegest data. note: this method may be called any time after init() is called. this call resets the object to its pre-init state. acstring finish( in prbool aascii ); parameters aascii if true then the returned value is a base-64 encoded string. if false, then the returned value is binary data. return value a hash of the data ...
nsIDocShell
void fireunloadnotification(); native code only! obsolete since gecko 1.8 nsisimpleenumerator getdocshellenumerator(in long aitemtype, in long adirection); nsidomstorage getsessionstorageforprincipal(in nsiprincipal principal, in domstring documenturi, in boolean create); ...
...ut nsidocshellloadinfo loadinfo ); parameters loadinfo the new nsidocshellloadinfo object. violates the xpcom interface guidelines detacheditorfromwindow() disconnects this docshell's editor from its window, and stores the editor data in the open document's session history entry. this should be called only during page transitions. void detacheditorfromwindow(); parameters none. finishrestore() finish firing webprogresslistener notifications and dom events for restoring a page presentation. this should only be called via beginrestore(). void finishrestore(); parameters none. native code only!firepagehidenotification notify the associated content viewer and all child docshells that they are about to be hidden. if isunload is true, then the document is being unloaded as well. v...
nsIProcess2
void runasync( [array, size_is(count)] in string args, in unsigned long count, in nsiobserver observer, optional in boolean holdweak optional ); parameters args an array of arguments to pass into the process, using the native character set. this array must have count entries. count the number of arguments passed in the args array. observer o...
...optional ); parameters args an array of arguments to pass into the process, using the native character set. this array must have count entries. count the number of arguments passed in the args array. observer optional an observer that will be notified when the process exits. the observer will receive this nsiprocess2 instance as the subject and "process-finished" or "process-failed" as the topic. the observer will be notified on the main thread. holdweak optional if true, a weak reference is used to hold the observer. see also nsiprocess nsiobserver ...
nsIWebBrowserPersist
append the downloaded data to the target file. this can only be used when persisting to a local file. persist_flags_force_allow_cookies 65536 force relevant cookies to be sent with this load even if normally they wouldn't be. persist_state_ready 1 persister is ready to save data. persist_state_saving 2 persister is saving data. persist_state_finished 3 persister has finished saving data. encode_flags_selection_only 1 output only the current selection as opposed to the whole document. encode_flags_formatted 2 for plain text output. convert html to plain text that looks like the html. implies wrap (except inside <pre>), since html wraps. html output: always do prettyprinting, ignoring existing formatting. ...
...annel( in nsichannel achannel, in nsisupports afile ); parameters achannel the nsichannel to save to a file. afile target local file. this may be a nsilocalfile object or an nsiuri object with a file scheme. savedocument() save the specified dom document to file and optionally all linked files (for example images, css, js & subframes). do not call this method until the document has finished loading! void savedocument( in nsidomdocument adocument, in nsisupports afile, in nsisupports adatapath, in string aoutputcontenttype, in unsigned long aencodingflags, in unsigned long awrapcolumn ); parameters adocument document to save to file. some implementations of this interface may also support nsnull to imply the currently loaded document. afile target local file. t...
NS_CStringContainerInit2
nit2 is a substring that is not null-terminated. return values the ns_cstringcontainerinit function returns ns_ok if successful. otherwise, it returns an error code. remarks after a nscstringcontainer object has been initialized via ns_cstringcontainerinit2, it may be used as an ordinary nsacstring object. when the string object is no longer needed, it should be passed to ns_cstringcontainerfinish to free any extra memory that the string object may have allocated. it is generally better to use one of the helper classes, such as nscstring, instead of coding directly to ns_cstringcontainerinit2 because those classes take care of cleaning up the string object when it goes out of scope. when ns_cstringcontainerinit2 is told to copy adata, the copy it creates is null-terminated. this is signifi...
...rminated. ...
Xptcall Porting Status
ont color="red">?</font> matthew wilcox <willy@bofh.ai> stefan's code is checked in and he says it is working. <font color="white">done</font> linux sparc anton blanchard <anton@progsoc.uts.edu.au>, roger lawrence <rogerl@netscape.com>, brandon ehle <ehle.3@osu.edu> anton contributed patches to roger's sparc code. anton says it works and passes the tests! (24-aug-1999) brandon writes: i've finished testing xptcall sparc linux on 12 different sparc machines and it checks out good. <font color="white">done</font> linux ppc patrick beard <beard@netscape.com> chris waterson <waterson@netscape.com> franz sirl <franz.sirl-kernel@lauterbach.com> <font color="red">?</font> jason y. sproul <jsproul@condor.fddi.wesleyan.edu> <font color="red">?</font> sean chitwood <darkmane@w-link.net> waters...
...r others to use too! <font color="white">help!</font> beos ppc - - <font color="white">done</font> compaq tru64 unix (digital unix) steve streeter <streeter@zk3.dec.com> code passes the tests and is checked in. <font color="black">working</font> neutrio x86 jerry l. kirk <jerry.kirk@nexwarecorp.com> patches for xptc*_unixish_x86.cpp checked in. waiting for verification that this is really finished. <font color="black">investigating</font> sco uw7 and osr5 j. kean johnston <jkj@sco.com> evan hunt <evanh@sco.com> recent (feb-2001) email from jkj@sco.com suggests that work will be occuring soon. <font color="black">works</font> netbsd/m68k dave huang <khym@bga.com> dave's changes are in the tree. waiting for verification that it is really finished. <font color="black">partially wor...
Intensive JavaScript - Firefox Developer Tools
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. ...
... then we need a new file "calculate.js", that looks like this: self.addeventlistener("message", go); function go(message) { var iterations = message.data.iterations; var multiplier = message.data.multiplier; primes = calculateprimes(iterations, multiplier); self.postmessage({ "command":"done", "primes": primes }); } function calculateprimes(iterations, multiplier) { va...
Background Tasks API - Web APIs
ent loop uses all available time, you're out of luck (again, unless you've used a timeout). idle callbacks should do their best not to overrun the time allotted. while the browser, your code, and the web in general will continue to run normally if you go over the specified time limit (even if you go way over it), the time restriction is intended to ensure that you leave the system enough time to finish the current pass through the event loop and get on to the next one without causing other code to stutter or animation effects to lag. currently, timeremaining() has an upper limit of 50 milliseconds, but in reality you will often have less time than that, since the event loop may already be eating into that time on complex sites, with browser extensions needing processor time, and so forth. avoi...
...effects to lag. currently, timeremaining() has an upper limit of 50 milliseconds, but in reality you will often have less time than that, since the event loop may already be eating into that time on complex sites, with browser extensions needing processor time, and so forth. avoid making changes to the dom within your idle callback. by the time your callback is run, the current frame has already finished drawing, and all layout updates and computations have been completed. if you make changes that affect layout, you may force a situation in which the browser has to stop and do recalculations that would otherwise be unnecessary. if your callback needs to change the dom, it should use window.requestanimationframe() to schedule that. avoid tasks whose run time can't be predicted. your idle callba...
Document: DOMContentLoaded event - Web APIs
bubbles yes cancelable yes (although specified as a simple event that isn't cancelable) interface event event handler property none a different event, load, should be used only to detect a fully-loaded page. it is a common mistake to use load where domcontentloaded would be more appropriate. synchronous javascript pauses parsing of the dom. ...
... script is going to delay parsing of the dom, // so the domcontentloaded event is going to launch later. </script> checking whether loading is already complete domcontentloaded may fire before your script has a chance to run, so it is wise to check before adding a listener. ...
Document.readyState - Web APIs
the document.readystate property describes the loading state of the document. when the value of this property changes, a readystatechange event fires on the document object. syntax var string = document.readystate; values the readystate of a document can be one of following: loading the document is still loading. ...
...hange event fires on the document object. syntax var string = document.readystate; values the readystate of a document can be one of following: loading the document is still loading. interactive the document has finished loading and the document has been parsed but sub-resources such as images, stylesheets and frames are still loading. complete the document and all sub-resources have finished loading. the state indicates that the load event is about to fire. examples different states of readiness switch (document.readystate) { case "loading": // the document is still loading. break; case "interactive": // the document has finished loading. we can now access the dom elements. // but sub-resources such as images, stylesheets and frames are still loading. va...
Document - Web APIs
Web › API › Document
.ontouchstart is an eventhandler representing the code to be called when the touchstart event is raised. globaleventhandlers.ontransitioncancel an eventhandler called when a transitioncancel event is sent, indicating that a css transition has been cancelled. globaleventhandlers.ontransitionend an eventhandler called when a transitionend event is sent, indicating that a css transition has finished playing. globaleventhandlers.ontransitionrun an eventhandler called when a transitionrun event is sent, indicating that a css transition is running, though not nessarilty started. globaleventhandlers.ontransitionstart an eventhandler called when a transitionstart event is sent, indicating that a css transition has started transitioning. globaleventhandlers.onwaiting is an eventhandler rep...
...le via the onkeydown property. keypress fired when a key that produces a character value is pressed down. also available via the onkeypress property. keyup fired when a key is released. also available via the onkeyup property. load & unload events domcontentloaded fired when the document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading. readystatechange fired when the readystate attribute of a document has changed. also available via the onreadystatechange property. pointer events gotpointercapture fired when when an element captures a pointer using setpointercapture(). also available via the ongotpointercapture property. lostpointercapture fired when a captured pointer is released. also available via the o...
GlobalEventHandlers.onload - Web APIs
there are also dom events like domcontentloaded and domframecontentloaded (which can be handled using eventtarget.addeventlistener()) which are fired af...
... console.log("load event detected!"); } window.onload = load; </script> </head> <body> <p>the load event fires when the document has finished loading!</p> </body> </html> notes the load event fires at the end of the document loading process. at this point, all of the objects in the document are in the dom, and all the images, scripts, links and sub-frames have finished loading. there are also dom events like domcontentloaded and domframecontentloaded (which can be handled using eventtarget.addeventlistener()) which are fired after the dom for the page has been constructed, but do not wait for other resources to finish loading. specifications specification status comment html living standardthe definition of 'onload' in that spec...
HTMLElement: transitionend event - Web APIs
tion has completed. in the case where a transition is removed before completion, such as if the transition-property is removed or display is set to none, then the event will not be generated. bubbles yes cancelable yes interface transitionevent event handler property ontransitionend the transitionend event is fired in both directions - as it finishes transitioning to the transitioned state, and when it fully reverts to the default or non-transitioned state. if there is no transition delay or duration, if both are 0s or neither is declared, there is no transition, and none of the transition events are fired. if the transitioncancel event is fired, the transitionend event will not fire. examples this code gets an element that has a transit...
... if there is no transition delay or duration, if both are 0s or neither is declared, there is no transition, and none of the transition events are fired. if the transitioncancel event is fired, the transitionend event will not fire. specifications specification status comment css transitionsthe defin...
HTMLMediaElement - Web APIs
ead only a read-only double-precision floating-point value indicating the total duration of the media in seconds. if no media data is available, the returned value is nan. if the media is of indefinite length (such as streamed live media, a webrtc call's media, or similar), the value is +infinity. htmlmediaelement.ended read only returns a boolean that indicates whether the media element has finished playing. htmlmediaelement.error read only returns a mediaerror object for the most recent error, or null if there has not been an error. htmlmediaelement.loop a boolean that reflects the loop html attribute, which indicates whether the media element should start over when it reaches the end. htmlmediaelement.mediagroup a domstring that reflects the mediagroup html attribute, which indica...
...empty; for example, when the media has already been loaded (or partially loaded), and the htmlmediaelement.load() method is called to reload it. ended fired when playback stops when end of the media (<audio> or <video>) is reached or because no further data is available. error fired when the resource could not be loaded due to an error. loadeddata fired when the first frame of the media has finished loading. loadedmetadata fired when the metadata has been loaded loadstart fired when the browser has started to load a resource. pause fired when a request to pause play is handled and the activity has entered its paused state, most commonly occurring when the media's htmlmediaelement.pause() method is called. play fired when the paused property is changed from true to false, as a resul...
Drag Operations - Web APIs
target. the following example returns the data associated with the best-supported format: function dodrop(event) { const supportedtypes = ["application/x-moz-file", "text/uri-list", "text/plain"]; const types = event.datatransfer.types.filter(type => supportedtypes.includes(type)); if (types.length) { const data = event.datatransfer.getdata(types[0]); } event.preventdefault(); } finishing a drag once the drag is complete, a dragend event is fired at the source of the drag (the same element that received the dragstart event). this event will fire if the drag was successful[1] or if it was cancelled. however, you can use the dropeffect property to determine which drop operation occurred. if the dropeffect property has the value none during a dragend, then the drag was cancelled...
...elled 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 not dispatched if the source node is moved or removed during the drag (e.g. on drop or dragover). bug 460801 see also html drag and drop api (overview) dragging and dropping multiple items recommended drag types html5 living standard: drag and drop ...
HTML Drag and Drop API - Web APIs
nd some events might fire many times, such as the drag and dragover events. each drag event type has an associated global event handler: event on event handler fires when… drag ondrag …a dragged item (element or text selection) is dragged. dragend ondragend …a drag operation ends (such as releasing a mouse button or hitting the esc key; see finishing a drag.) dragenter ondragenter …a dragged item enters a valid drop target. (see specifying drop targets.) dragexit ondragexit …an element is no longer the drag operation's immediate selection target. dragleave ondragleave …a dragged item leaves a valid drop target. dragover ondragover …a dragged item is being dragged over a va...
...d of a drag operation, the dragend event fires at the source element — the element that was the target of the drag start. this event fires regardless of whether the drag completed or was canceled. the dragend event handler can check the value of the dropeffect property to determine if the drag operation succeeded or not. for more information about handling the end of a drag operation, see: finishing a drag interoperability as can be seen in the datatransferitem interface's browser compatibility table, drag-and-drop interoperability is relatively broad among desktop browsers (except the datatransferitem and datatransferitemlist interfaces have less support). this data also indicates drag-and-drop support among mobile browsers is very low. examples and demos copying and moving elemen...
IDBTransaction.error - Web APIs
taining the relevant error. in chrome 48+/firefox 58+ this property returns a domexception because domerror has been removed from the dom standard. the exact error is one of serveral possibilities. it can be a reference to the same error as the request object that raised it, or a transaction failure (for example quotaexceedederror or unknownerror). this property is null if the transaction is not finished, is finished and successfully committed, or was aborted with the idbtransaction.abort method. example in the following code snippet, we open a read/write transaction on our database and add some data to an object store. note also the functions attached to transaction event handlers to report on the outcome of the transaction opening in the event of success or failure. note the transaction.one...
...e: "walk dog", hours: 19, minutes: 30, day: 24, month: "december", year: 2013, notified: "no" } ]; // open a read/write db transaction, ready for adding the data var transaction = db.transaction(["todolist"], "readwrite"); // report on the success of opening the transaction transaction.oncomplete = function(event) { note.innerhtml += '<li>transaction completed: database modification finished.</li>'; }; transaction.onerror = function(event) { note.innerhtml += '<li>transaction not opened due to error: ' + transaction.error + '</li>'; }; // create an object store on the transaction var objectstore = transaction.objectstore("todolist"); // add our newitem object to the object store var objectstorerequest = objectstore.add(newitem[0]); objectstorerequest.onsucc...
IDBTransaction.objectStore() - Web APIs
lue an idbobjectstore object for accessing an object store. exceptions this method may raise a domexception of one of the following types: exception description notfounderror the requested object store is not in this transaction's scope. invalidstateerror the request was made on a source object that has been deleted or removed, or if the transaction has finished. example in the following code snippet, we open a read/write transaction on our database and add some data to an object store. note also the functions attached to transaction event handlers to report on the outcome of the transaction opening in the event of success or failure. for a full working example, see our to-do notifications app (view example live.) // let us open our database v...
...duplicate items not allowed.</li>'; }; // create an object store on the transaction var objectstore = transaction.objectstore("todolist"); // add our newitem object to the object store var objectstorerequest = objectstore.add(newitem[0]); objectstorerequest.onsu...
IDBTransaction - Web APIs
ansaction 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 read only returns a domexception indicating the type of error that occured when there is an unsuccessful transaction. this property is null if the transaction is not finished, is finished and successfully committed, or was aborted with theidbtransaction.abort() function. idbtransaction.mode read only the mode for isolating access to data in the object stores that are in the scope of the transaction. the default value is readonly. idbtransaction.objectstorenames read only returns a domstringlist of the names of idbobjectstore objects associated with the transac...
...duplicate items not allowed.</li>'; }; // create an object store on the transaction var objectstore = transaction.objectstore("todolist"); // add our newitem object to the object store var objectstorerequest = objectstore.add(newitem[0]); objectstorerequest.onsuc...
Using the Payment Request API - Web APIs
style.display = 'block'; }); }) this object provides the developer with access to details they can use to complete the logical steps required after the payment completes, such as an email address to contact the customer, a shipping address for mailing goods out to them, etc. in the code above, you'll see that we've called the paymentresponse.complete() method to signal that the interaction has finished — you'd use this to carry out finishing steps, like updating the user interface to tell the user the transaction is complete, etc. other useful payment request methods there are some other useful payment request methods worth knowing about. paymentrequest.canmakepayment() can be used to check whether the paymentrequest object is capable of making a payment before you start the payment proc...
... if(result) { // real payment request var request = new paymentrequest(buildsupportedpaymentmethoddata(), checkoutobject); request.show().then(function(paymentresponse) { // here we would process the payment. paymentresponse.complete('success') .then(function() { // finish handling payment }); }) } }) paymentrequest.abort() can be used to abort the payment request if required. detecting availability of the payment request api you can effectively detect support for the payment request api by checking if the user's browser supports paymentrequest, i.e. if (window.paymentrequest). in the following snippet, a merchant page perfo...
PerformanceNavigationTiming.unloadEventEnd - Web APIs
example the following example illustrates this property's usage. ...
... example the following example illustrates this property's usage. ...
PerformanceResourceTiming.domainLookupEnd - Web APIs
example in the following example, the value of the *start and *end properties of all "resource" type events are logged. ...
...ain name lookup for the resource. if the user agent has the domain information in cache, domainlookupstart and domainlookupend represent the times when the user agent starts and ends the domain data retrieval from the cache. note: this feature is available in web workers. syntax resource.domainlookupend; return value a domhighrestimestamp representing the time immediately after the browser finishes the domain name lookup for the resource. example in the following example, the value of the *start and *end properties of all "resource" type events are logged. function print_performanceentries() { // use getentriesbytype() to just get the "resource" events var p = performance.getentriesbytype("resource"); for (var i=0; i < p.length; i++) { print_start_and_end_properties(p[i]); ...
PerformanceResourceTiming - Web APIs
rcetiming.fetchstartread only a domhighrestimestamp immediately before the browser starts to fetch the resource. performanceresourcetiming.domainlookupstartread only a domhighrestimestamp immediately before the browser starts the domain name lookup for the resource. ...
... performanceresourcetiming.secureconnectionstartread only a domhighrestimestamp immediately before the browser starts the handshake process to secure the current connection. ...
RTCIceTransport.state - Web APIs
er, and there may still be gathering underway on one or both of the two devices. the transport may revert from the "connected" state to the "checking" state if either peer decides to cancel consent to use the selected candidate pair, and may revert to "disconnected" if there are no candidates left to check but one or both clients are still gathering candidates. "completed" the transport has finished gathering local candidates and has received a notification from the remote peer that no more candidates will be sent. in addition, all candidate pairs have been considered and a pair has been selected for use. if consent checks fail on all successful candidate pairs, the transport state will change to "failed". "disconnected" the ice agent has determined that connectivity has been lost for th...
...ent has determined that connectivity has been lost for this rtcicetransport. this is not a failure state (that's "failed"). a value of "disconnected" means that a transient issue has occurred that has broken the connection, but that should resolve itself automatically without your code having to take any action. see the disconnected state for additional details. "failed" the rtcicetransport has finished the gathering process, has received the "no more candidates" notification from the remote peer, and has finished checking pairs of candidates, without successfully finding a pair that is both valid and for which consent can be obtained. this is a terminal state, indicating that the connection cannot be achieved or maintained. "closed" the transport has shut down and is no longer responding to...
RTCPeerConnection.iceGatheringState - Web APIs
you can detect when the value of this property changes by watching for an event of type icegatheringstatechange. syntax var state = rtcpeerconnection.icegatheringstate; value the possible values are those of an enum of type rtcicegatheringstate. ...
...tion.icegatheringstate property. you can detect when this value changes by watching for an event of type icegatheringstatechange. constant description "new" the peer connection was just created and hasn't done any networking yet. "gathering" the ice agent is in the process of gathering candidates for the connection. "complete" the ice agent has finished gathering candidates. if something happens that requires collecting new candidates, such as a new interface being added or the addition of a new ice server, the state will revert to "gathering" to gather those candidates. example var pc = new rtcpeerconnection(); var state = pc.icegatheringstate; specifications specification status comment webrtc 1.0: real-...
RTCPeerConnection: icecandidate event - Web APIs
tring. only candidates for which the event's candidate property is null are not forwarded across the signaling connection. the end-of-candidates indication is described in section 9.3 of the trickle ice draft specification (note that the section number is subject to change as the specification goes through repeated drafts). indicating that ice gathering is complete once all ice transports have finished gathering candidates and the value of the rtcpeerconnection object's icegatheringstate has made the transition to complete, an icecandidate event is sent with the value of complete set to null. this signal exists for backward compatibility purposes and does not need to be delivered onward to the remote peer (which is why the code snippet above checks to see if event.candidate is null prior to ...
...ng has ended */ break; } }); as you can see in this example, the icegatheringstatechange event lets you know when the value of the rtcpeerconnection property icegatheringstate has been updated. if that value is now complete, you know that ice gathering has just ended. this is a more reliable approach than looking at the individual ice messages for one indicating that the ice session is finished. examples this example creates a simple handler for the icecandidate event that uses a function called sendmessage() to create and send a reply to the remote peer through the signaling server. first, an example using addeventlistener(): pc.addeventlistener("icecandidate", ev => { if (ev.candidate) { sendmessage({ type: "new-ice-candidate", candidate: event.candidate })...
ReadableStream.cancel() - Web APIs
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(). ...
...given in the reason parameter. exceptions typeerror the stream you are trying to cancel is not a readablestream, or it is locked. examples in jake archibald's cancelling a fetch example, a stream is used to fetch the whatwg html spec chunk by chunk; each chunk is searched for the string "service workers". when the search terms is found, cancel() is used to cancel the stream — the job is finished so it is no longer needed. var searchterm = "service workers"; // chars to show either side of the result in the match var contextbefore = 30; var contextafter = 30; var caseinsensitive = true; var url = 'https://html.spec.whatwg.org/'; console.log(`searching '${url}' for '${searchterm}'`); fetch(url).then(response => { console.log('received headers'); var decoder = new textdecoder(); ...
ReadableStreamDefaultReader.cancel() - Web APIs
that data is lost after cancel is called, and the stream is not readable any more. ...
...xceptions 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 using a readablestreamdefaultreader created using getreader(). (this code is based on our simple random stream example). each chunk is read sequentially and output to the ui, until the stream has finished being read, at which point we return out of the recursive function and print the entire stream to another part of the ui. when the stream is done (if (done)), we run reader.cancel() to cancel the stream, signalling that we don't need to use it any more. function fetchstream() { const reader = stream.getreader(); let charsreceived = 0; // read() returns a promise that resolves // when...
ServiceWorkerContainer.startMessages() - Web APIs
the startmessages() method of the serviceworkercontainer interface explicitly starts the flow of messages being dispatched from a service worker to pages under its control (e.g. sent via client.postmessage()). this can be used to react to sent messages earlier, even before that page's content has finished loading. explanation by default, all messages sent from a page's controlling service worker to the page (using client.postmessage()) are queued while the page is loading, and get dispatched once the page's html document has been loaded and parsed (i.e. after the domcontentloaded event fires). it's possible to start dispatching these messages earlier by calling serviceworkercontainer.startmessages(), for example if you've invoked a message handler using eventtarget.addeventlistener() before t...
...ng client.postmessage()) are queued while the page is loading, and get dispatched once the page's html document has been loaded and parsed (i.e. after the domcontentloaded event fires). it's possible to start dispatching these messages earlier by calling serviceworkercontainer.startmessages(), for example if you've invoked a message handler using eventtarget.addeventlistener() before the page has finished loading, but want to start processing the messages right away. note: the messages start being sent automatically when setting the handler directly using serviceworkercontainer.onmessage. in this you don't need startmessages(). syntax serviceworkercontainer.startmessages(); parameters none. return value undefined. examples if('serviceworker' in navigator) { navigator.serviceworker ...
SpeechSynthesisUtterance.onend - Web APIs
}; examples var synth = window.speechsynthesis; var inputform = document.queryselector('form'); var inputtxt = document.queryselector('input'); var voiceselect = document.queryselector('select'); var voices = synth.getvoices(); ... ...
... draft ...
Streams API concepts - Web APIs
ight into a buffer supplied by the developer, minimizing the copying required. which underlying stream (and by extension, reader and controller) your code will use depends on how the stream was created in the first place (see the readablestream() constructor page). important: byte streams are not implemented anywhere as yet, and questions have been raised as to whether the spec details are in a finished enough state for them to be implemented. this may change over time. you can make use of ready-made readable streams via mechanisms like a response.body from a fetch request, or roll your own streams using the readablestream() constructor. teeing even though only a single reader can read a stream at once, it is possible to split a stream into two identical copies, which can then be read by t...
...readablestream can tell its underlying source to stop sending data, and we backpressure along the stream chain. if later on the consumer again wants to receive data, we can use the pull method in the stream creation to tell our underlying source to feed our stream with data. internal queues and queuing strategies as mentioned earlier, the chunks in a stream that have not yet been processed and finished with are kept track of by an internal queue. in the case of readable streams, these are the chunks that have been enqueued but not yet read in the case of writable streams, these are chunks that have been written but not yet processed by the underlying sink. internal queues employ a queuing strategy, which dictates how to signal backpressure based on the internal queue state. in general,...
Starting up and shutting down a WebXR session - Web APIs
, and if that fails, fall back to a viewer reference space, which all devices are required to support. preparing the new session for use once the requestsession() method's returned promise successfully resolves, you know you have a usable webxr session in hand. you can then proceed to prepare the session for use and begin your animations. the key things you need (or may need) to do in order to finish the configuration of your session include: add handlers for the events you need to watch. this most likely includes the end at a minimum, so you can detect when the session is over. if you use xr input controllers, watch the inputsourceschange event to detect the addition or removal of xr input controllers, and the various select and squeeze action events. you may want to watch for the xrsys...
...this final setup might look something like this: async function runsession(session) { let worlddata; session.addeventlistener("end", onsessionend); let canvas = document.queryselector("canvas"); gl = canvas.getcontext("webgl", { xrcompatible: true }); // set up webgl data and such worlddata = loadglprograms(session, "worlddata.xml"); if (!worlddata) { return null; } // finish configuring webgl worlddata.session.updaterenderstate({ baselayer: new xrwebgllayer(worlddata.session, gl) }); // start rendering the scene referencespace = await worlddata.session.requestreferencespace("unbounded"); worlddata.referencespace = referencespace.getoffsetreferencespace( new xrrigidtransform(worlddata.playerspawnposition, worlddata.playerspawnorientation)); ...
Advanced techniques: Creating and sequencing audio - Web APIs
let's create another async function to set up the sample — we can combine the two async functions in a nice promise pattern to perform further actions when this file is loaded and buffered: async function setupsample() { const filepath = 'dtmf.mp3'; const sample = await getfile(audioctx, filepath); return sample; } note: you can easily modify the above function to t...
... dial-up user controls the audiobuffersourcenode comes with a playbackrate property. let's expose that to our ui, so we can speed up and slow down our sample. we'll do that in the same sort of way as before: <label for="rate">rate</label> <input name="rate" id="rate" type="range" min="0.1" max="2" value="1" step="0.1" /> let playbackrate = 1; const ratecontrol = document.queryselec...
Using the Web Audio API - Web APIs
this is where the web audio api really starts to come in handy. ...
...epending on state if (this.dataset.playing === 'false') { audioelement.play(); this.dataset.playing = 'true'; } else if (this.dataset.playing === 'true') { audioelement.pause(); this.dataset.playing = 'false'; } }, false); we also need to take into account what to do when the track finishes playing. our htmlmediaelement fires an ended event once it's finished playing, so we can listen for that and run code accordingly: audioelement.addeventlistener('ended', () => { playbutton.dataset.playing = 'false'; }, false); modifying sound let's delve into some basic modification nodes, to change the sound that we have. this is where the web audio api really starts to come in handy. first of all, let's change the volume. this can be done using a gainno...
XMLHttpRequest.send() - Web APIs
ue undefined. exceptions exception description invalidstateerror send() has already been invoked for the request, and/or the request is complete. networkerror the resource type to be fetched is a blob, and the method is not get. example: get var xhr = new xmlhttprequest(); xhr.open('get', '/server', true); xhr.onload = function () { // request finished. do processing here. }; xhr.send(null); // xhr.send('string'); // xhr.send(new blob()); // xhr.send(new int8array()); // xhr.send(document); example: post var xhr = new xmlhttprequest(); xhr.open("post", '/server', true); //send the proper header information along with the request xhr.setrequestheader("content-type", "application/x-www-form-urlencoded"); xhr.onreadystatechange = function(...
...nt); example: post var xhr = new xmlhttprequest(); xhr.open("post", '/server', true); //send the proper header information along with the request xhr.setrequestheader("content-type", "application/x-www-form-urlencoded"); xhr.onreadystatechange = function() { // call a function when the state changes. if (this.readystate === xmlhttprequest.done && this.status === 200) { // request finished. do processing here. } } xhr.send("foo=bar&lorem=ipsum"); // xhr.send(new int8array()); // xhr.send(document); specifications specification status comment xmlhttprequestthe definition of 'send()' in that specification. living standard whatwg living standard ...
XRSession.onselectend - Web APIs
for example, this might include releasing a button or joystick. note: not to be confused with xrsession.onselectstart and xrsession.onselect. syntax xrsession.onselectend = function(event) { ... ...
...for example, this might include releasing a button or joystick. note: not to be confused with xrsession.onselectstart and xrsession.onselect. syntax xrsession.onselectend = function(event) { ... ...
Using CSS transitions - CSS: Cascading Style Sheets
configure transitions, as it makes it easier to avoid out of sync parameters, which can be very frustrating to have to spend lots of time debugging in css. you can control the individual components of the transition with the following sub-properties: (note that these transitions loop infinitely only for the purpose of our examples; css transitions only visualize a property change from start to finish. if you need visualizations that loop, look into the css animation property.) transition-property specifies the name or names of the css properties to which transitions should be applied. only properties listed here are animated during transitions; changes to all other properties occur instantaneously as usual. transition-duration specifies the duration over which transitions should occur. ...
...this is a transitionevent object, which has two added properties beyond a typical event object: propertyname a string indicating the name of the css property whose transition completed. elapsedtime a float indicating the number of seconds the transition had been running at the time the event fired. this value isn't affected by the value of transition-delay. as usual, you can us...
Media events - Developer guides
lly loaded), and the load() method is called to reload it. encrypted the user agent has encountered initialization data in the media data. ended sent when playback completes. error sent when an error occurs. the element's error attribute contains more information. see htmlmediaelement.error for details. loadeddata the first frame of the media has finished loading. loadedmetadata the media's metadata has finished loading; all attributes now contain as much useful information as they're going to. loadstart sent when loading of the media begins. mozaudioavailable sent when an audio buffer is provided to the audio layer for processing; the buffer contains raw audio samples that may or may not already have been pla...
...ayback. then, in line 3, the example sets the element's currenttime attribute to 10.0, which initiates a seek operation to the 10-second mark in the media. this causes a seeking event to be sent when the operation begins, then a seeked event to be dispatched when the seek is completed. in other words, this example seeks to the 10-second mark in the media, then begins playback as soon as that's finished. ...
<audio>: The Embed Audio element - HTML: Hypertext Markup Language
Web › HTML › Element › audio
wser's default audio controls, etc. the content inside the opening and closing <audio></audio> tags is shown as a fallback in browsers that don't support the element. attributes this element's attributes include the global attributes. autoplay a boolean attribute: if specified, the audio will automatically begin playback as soon as it can do so, without waiting for the entire audio file to finish downloading. note: sites that automatically play audio (or videos with an audio track) can be an unpleasant experience for users, so should be avoided when possible. if you must offer autoplay functionality, you should make it opt-in (requiring a user to specifically enable it). however, this can be useful when creating media elements whose source will be set at a later time, under user control.
...minated. durationchange the duration attribute has been updated. emptied the media has become empty; for example, this event is sent if the media has already been loaded (or partially loaded), and the load() method is called to reload it. ended playback has stopped because the end of the media was reached. loadeddata the first frame of the media has finished loading. loadedmetadata the metadata has been loaded. pause playback has been paused. play playback has begun. playing playback is ready to start after having been paused or delayed due to lack of data. ratechange the playback rate has changed. seeked a seek operation completed. seeking a seek operation began. ...
<video>: The Video Embed element - HTML: Hypertext Markup Language
Web › HTML › Element › video
the browser's default video controls, etc. the content inside the opening and closing <video></video> tags is shown as a fallback in browsers that don't support the element. attributes like all other html elements, this element supports the global attributes. autoplay a boolean attribute; if specified, the video automatically begins to play back as soon as it can do so without stopping to finish loading the data. note: sites that automatically play audio (or videos with an audio track) can be an unpleasant experience for users, so should be avoided when possible. if you must offer autoplay functionality, you should make it opt-in (requiring a user to specifically enable it). however, this can be useful when creating media elements whose source will be set at a later time, under user con...
...minated. durationchange the duration attribute has been updated. emptied the media has become empty; for example, this event is sent if the media has already been loaded (or partially loaded), and the load() method is called to reload it. ended playback has stopped because the end of the media was reached. loadeddata the first frame of the media has finished loading. loadedmetadata the metadata has been loaded. pause playback has been paused. play playback has begun. playing playback is ready to start after having been paused or delayed due to lack of data. progress fired periodically as the browser loads a resource. ratechange the playback rate has changed. seeked ...
Using Promises - JavaScript
out() doesn't really fail, we left out reject in this case. composition promise.resolve() and promise.reject() are shortcuts to manually create an already resolved or rejected promise respectively. this can be useful at times. promise.all() and promise.race() are two composition tools for running asynchronous operations in parallel. ...
...thirdthing(newresult)); }).then(() => dofourththing()); // forgot to terminate chain with a catch! the first mistake is to not chain things together properly. this happens when we create a new promise but forget to return it. as a consequence, the chain is broken, or rather, we have two independent chains racing. this means dofourththing() won't wait for dosomethingelse() or dothirdthing() to finish, and will run in parallel with them, likely unintended. separate chains also have separate error handling, leading to uncaught errors. the second mistake is to nest unnecessarily, enabling the first mistake. nesting also limits the scope of inner error handlers, which—if unintended—can lead to uncaught errors. a variant of this is the promise constructor anti-pattern, which combines nesting ...
async function - JavaScript
function parallel() { console.log('==parallel with await promise.all==') // start 2 "jobs" in parallel and wait for both of them to complete await promise.all([ (async()=>console.log(await resolveafter2seconds()))(), (async()=>console.log(await resolveafter1second()))() ]) } sequentialstart() // after 2 seconds, logs "slow", then after 1 more second, "fast" // wait above to finish settimeout(concurrentstart, 4000) // after 2 seconds, logs "slow" and then "fast" // wait again settimeout(concurrentpromise, 7000) // same as concurrentstart // wait again settimeout(parallel, 10000) // truly parallel: after 1 second, logs "fast", then after 1 more second, "slow" await and parallelism in sequentialstart, execution suspends 2 seconds for the first await, and then another sec...
...out(concurrentpromise, 7000) // same as concurrentstart // wait again settimeout(parallel, 10000) // truly parallel: after 1 second, logs "fast", then after 1 more second, "slow" await and parallelism in sequentialstart, execution suspends 2 seconds for the first await, and then another second for the second await. the second timer is not created until the first has already fired, so the code finishes after 3 seconds. in concurrentstart, both timers are created and then awaited. the timers run concurrently, which means the code finishes in 2 rather than 3 seconds, i.e. the slowest timer. however, the await calls still run in series, which means the second await will wait for the first one to finish. in this case, the result of the fastest timer is processed after the slowest. if you wish ...
function* - JavaScript
value property containing the yielded value and a done property which indicates whether the generator has yielded its last value, as a boolean. calling the next() method with an argument will resume the generator function execution, replacing the yield expression where an execution was paused with the argument from next(). ...
...ion was paused with the argument from next(). a return statement in a generator, when executed, will make the generator finish (i.e. the done property of the object returned by it will be set to true). if a value is returned, it will be set as the value property of the object returned by the generator. much like a return statement, an error is thrown inside the generator will make the generator finished -- unless caught within the generator's body. when a generator is finished, subsequent next() calls will not execute any of that generator's code, they will just return an object of this form: {value: undefined, done: true}. examples simple example function* idmaker() { var index = 0; while (true) yield index++; } var gen = idmaker(); console.log(gen.next().value); // 0 console.lo...
Progressive loading - Progressive web apps (PWAs)
p: service workers, web manifests, notifications and push. in this article we will go even further and improve the performance of the app by progressively loading its resources. first meaningful paint it's important to deliver something meaningful to the user as soon as possible — the longer they wait for the page to load, the bigger the chance they will leave before waiting for everything to finish. we should be able to show them at least the basic view of the page they want to see, with placeholders in the places more content will eventually be loaded. this could be achieved by progressive loading — also known as lazy loading. this is all about deferring loading of as many resources as possible (html, css, javascript), and only loading those immediately that are really needed for the ve...
...s, which will force the browser to download them automatically, we can do it selectively via javascript. the js13kpwa app uses a placeholder image instead, which is small and lightweight, while the final paths to target images are stored in data-src attributes: <img src='data/img/placeholder.png' data-src='data/img/slug.jpg' alt='name'> those images will be loaded via javascript after the site finishes building the html structure. the placeholder image is scaled the same way the original images are, so it will take up the same space and not cause the layout to repaint as the images load. loading via javascript the app.js file processes the data-src attributes like so: let imagestoload = document.queryselectorall('img[data-src]'); const loadimages = (image) => { image.setattribute('src', ...
Using templates and slots - Web Components
able; when an element has been inserted in a slot, it is said to be slotted. note: an unnamed <slot> will be filled with all of the custom element's top-level child nodes that do not have the slot attribute. this includes text nodes. and that's it for our trivial example. if you want to play with it some more, you can find it on github (see it running live also). a more involved example to finish off the article, let's look at something a little less trivial. the following set of code snippets show how to use <slot> together with <template> and some javascript to: create a <element-details> element with named slots in its shadow root design the <element-details> element in such a way that, when used in documents, it is rendered from composing the element’s content together with con...
...ption" we put in the <element-details> shadow root . only the first of those two <element-details> elements references the "attributes" named slot. the second <element-details> element lacks any reference to the "attributes" named slot. the first <element-details> element references the "attributes" named slot using a <dl> element with <dt> and <dd> children. adding a final bit of style as a finishing touch, we'll add a tiny bit more css for the <dl>, <dt>, and <dd> elements in our doc: dl { margin-left: 6px; } dt { font-weight: bold; color: #217ac0; font-size: 110% } dt { font-family: consolas, "liberation mono", courier } dd { margin-left: 16px } body { margin-top: 47px } result finally let’s put all the snippets together and see what the rendered result looks like. scre...
Understanding WebAssembly text format - WebAssembly
being printed to the console: var memory = new webassembly.memory({initial:1}); var importobject = { console: { log: consolelogstring }, js: { mem: memory } }; webassembly.instantiatestreaming(fetch('logger2.wasm'), importobject) .then(obj => { obj.instance.exports.writehi(); }); note: you can find the full source on github as logger2.html (also see it live). webassembly tables to finish this tour of the webassembly text format, let’s look at the most intricate, and often confusing, part of webassembly: tables. tables are basically resizable arrays of references that can be accessed by index from webassembly code. to see why tables are needed, we need to first observe that the call instruction we saw earlier (see calling functions from other functions in the same module) takes...
... ...
Loading Content Scripts - Archive of obsolete content
ge is inserted into the dom. at this point the dom content hasn't been loaded yet, so the script won't be able to interact with it. "ready" loads the scripts after the dom for the page has been loaded: that is, at the point the domcontentloaded event fires. at this point, content scripts are able to interact with the dom content, but externally-referenced stylesheets and images may not have finished loading. "end" loads the scripts after all content (dom, js, css, images) for the page has been loaded, at the time the window.onload event fires. the default value is "end". the contentscriptoptions is a json that is exposed to content scripts as a read only value under self.options property. any kind of jsonable value (object, array, string, etc.) can be used here. ...
Content Scripts - Archive of obsolete content
he page is inserted into the dom. at this point the dom content hasn't been loaded yet, so the script won't be able to interact with it. "ready": load the scripts after the dom for the page has been loaded: that is, at the point the domcontentloaded event fires. at this point, content scripts are able to interact with the dom content, but externally-referenced stylesheets and images may not have finished loading. "end": load the scripts after all content (dom, js, css, images) for the page has been loaded, at the time the window.onload event fires. the default value is "end". note that tab.attach() doesn't accept contentscriptwhen, because it's generally called after the page has loaded. passing configuration options the contentscriptoptions is a json object that is exposed to content scr...
simple-storage - Archive of obsolete content
ry directory each time it starts. jpm run --no-copy --profile path/to/profile/dir if you specify a non-existent profile, the same will be created, don't worry. important: if you use this method, you must end your debugging session by quitting firefox normally, not by cancelling the shell command. if you don't close firefox normally, then simple storage will not be notified that the session is finished, and will not write your data to the backing store. accessing storage from the console in the add-on debugger, you can access your add-on's simple-storage programmatically from the console using the following: loader.modules['resource://gre/modules/commonjs/sdk/simple-storage.js'].exports.storage clarification from mozilla needed: writing the above line in add-on debugger console results ...
windows - Archive of obsolete content
ndows for (let window of windows) { console.log(window.title); } // close the active window windows.activewindow.close(function() { console.log("the active window was closed"); }); methods activate() makes window active, which will focus that window and bring it to the foreground. close(callback) close the window. parameters callback : function a function to be called when the window finishes its closing process. this is an optional argument. properties title the current title of the window. usually the title of the active tab, plus an app identifier. this property is read-only. tabs a live list of tabs in this window. this object has the same interface as the tabs api, except it contains only the tabs in this window, not all tabs in all windows. this property is read-only. ...
core/promise - Archive of obsolete content
nuewith(error, handle) { if (error) return ui.displayerror(error); twitter.gettweetsfor(handle, funtion continuewith(error, tweets) { if (error) return ui.displayerror(error); ui.showtweets(tweets); }); }); }); doing things in parallel is even harder: var tweets, answers, checkins; twitter.gettweetsfor(user, function continuewith(result) { tweets = result; somethingfinished(); }); stackoverflow.getanswersfor(question, function continuewith(result) { answers = result; somethingfinished(); }); foursquare.getcheckinsby(user, function continuewith(result) { checkins=result; somethingfinished(); }); var finished = 0; function somethingfinished() { if (++finished === 3) ui.show(tweets, answers, checkins); } this also makes error handling quite an adven...
lang/functional - Archive of obsolete content
debounce(fn, wait) this function is new in firefox 30. from underscore's debounce() function: this takes a function and returns a new version of the function which, when invoked, will not be executed until it has not been invoked for wait milliseconds. this means that if the function's called many times in quick succession the function will only execute once, after the blizzard of calls has finished. this could be useful, for example, if we are checking the user's keyboard input, and want to wait until they've paused in their typing before we do so. parameters fn : function the function to debounce. wait : integer the number of milliseconds to wait before the function is executed. returns function : the debounced version of fn. throttle(fn, wait, options) this function is new in ...
test/utils - Archive of obsolete content
marks = function (assert, done) { search().on('end', function (results) { assert.equal(results, 0, 'should be no bookmarks'); done(); }); }; before(exports, function (name, assert) { removeallbookmarks(); }); require('sdk/test').run(exports); both before and after may be asynchronous. ...
ui/button/action - Archive of obsolete content
ow }); function disableforthiswindow(state) { button.state("window", { disabled: true }); } to fetch the state for a specific window or tab, call state(), passing in the window or tab you are interested in, and it will return the state: var labelforactivetab = button.state("tab").label; to learn more about this, see the api documentation for state(). destroying buttons when you've finished with a button, destroy it by calling its destroy() method. after that, any attempts to access any of its properties or to call any of its methods will throw exceptions. globals constructors actionbutton(options) creates an action button. parameters options : object required options: name type id string the button's id. this is used internally to ...
ui/button/toggle - Archive of obsolete content
after that, any attempts to access any of its properties or to call any of its methods will throw exceptions. globals constructors togglebutton(options) creates a toggle button. parameters options : object required options: name type id string the button's id. this is used internally to k...
ui/sidebar - Archive of obsolete content
ill operate on the currently active window. from firefox 33 onwards you can pass a browserwindow into these methods, and they will then operate on the specified window. alternatively, the view->sidebar submenu in firefox will contain a new item which the user can use to show or hide the sidebar: the sidebar generates a show event when it is shown and a hide event when it is hidden. once you've finished using the sidebar you can destroy it by calling its dispose() method. to show what a sidebar looks like, here's a sidebar that displays the results of running the w3c validator on the current page: specifying sidebar content the content of a sidebar is specified using html, which is loaded from the url supplied in the url option to the sidebar's constructor. unlike modules such as panel, t...
Getting Started (jpm) - Archive of obsolete content
id: "mozilla-link", label: "visit mozilla", icon: { "16": "./icon-16.png", "32": "./icon-32.png", "64": "./icon-64.png" }, onclick: handleclick }); function handleclick(state) { tabs.open("https://developer.mozilla.org/"); } at the command prompt, execute jpm run again. this time clicking it takes you to https://developer.mozilla.org/. packaging the add-on when you've finished the add-on and are ready to distribute it, you'll need to package it as an xpi file. this is the installable file format for firefox add-ons. you can distribute xpi files yourself or publish them to https://addons.mozilla.org so other users can download and install them. to build an xpi, just execute the command jpm xpi from the add-on's directory: jpm xpi you should see a message like: jp...
Getting started (cfx) - Archive of obsolete content
id: "mozilla-link", label: "visit mozilla", icon: { "16": "./icon-16.png", "32": "./icon-32.png", "64": "./icon-64.png" }, onclick: handleclick }); function handleclick(state) { tabs.open("https://developer.mozilla.org/"); } at the command prompt, execute cfx run again. this time clicking it takes you to https://developer.mozilla.org/. packaging the add-on when you've finished the add-on and are ready to distribute it, you'll need to package it as an xpi file. this is the installable file format for firefox add-ons. you can distribute xpi files yourself or publish them to https://addons.mozilla.org so other users can download and install them. to build an xpi, just execute the command cfx xpi from the add-on's directory: cfx xpi you should see a message like: ex...
Developing for Firefox Mobile - Archive of obsolete content
with intent name org.mozilla.fennec pushing the addon to your device starting: intent { act=android.activity.main cmp=org.mozilla.fennec/.app (has extras) } --------- beginning of /dev/log/main --------- beginning of /dev/log/system could not read chrome manifest 'file:///data/data/org.mozilla.fennec/chrome.manifest'. info: starting info: starting zerdatime 1329258528988 - browser chrome startup finished. this will be followed by lots of debug output. on the device, you should see firefox launch with your add-on installed. console.log() output from your add-on is written to the command shell, just as it is in desktop development. however, because there's a lot of other debug output in the shell, it's not easy to follow. the command adb logcat prints adb's log, so you can filter the debug ou...
File I/O - Archive of obsolete content
terfaces.nsifile.normal_file_type, 0600); var stream = components.classes["@mozilla.org/network/safe-file-output-stream;1"]. createinstance(components.interfaces.nsifileoutputstream); stream.init(afile, 0x04 | 0x08 | 0x20, 0600, 0); // readwrite, create, truncate stream.write(pngbinary, pngbinary.length); if (stream instanceof components.interfaces.nsisafeoutputstream) { stream.finish(); } else { stream.close(); } more there are more methods and properties on nsifile and nsilocalfile interfaces; please refer to their documentation for more details. those methods/properties are mostly self-explanatory, so we haven't included examples of using them here. ...
Progress Listeners - Archive of obsolete content
if you use mylistener for more than one tab/window, // use aprogress.domwindow to obtain the tab/window which triggered the change. }, // for definitions of the remaining fun...
Creating custom Firefox extensions with the Mozilla build system - Archive of obsolete content
othering with the rest of mozilla. if everything works out, you'll see your xpi file in the xpi staging area. you'll also see the "exploded" version of the xpi (i.e. the unzipped directory structure) underneath /mozilla/$(moz_objdir)/dist/bin/extensions. (if something goes wrong, figure out what, fix it and then come back here and add it to this article.) to make sure that the build really finished, launch firefox and check that your extension is listed when you select tools/extensions. if you are using firefox as your regular browser (and if you're not, why not!?), you might be annoyed by the fact that you have to close regular firefox before running your custom-built version. if so, try setting the moz_no_remote environment variable to "1" before running the development version of firef...
Listening to events in Firefox extensions - Archive of obsolete content
to monitor are listed here: event description domlinkadded dispatched when a new html <link> element is detected in the document. domtitlechanged dispatched when the title of the page changes. domcontentloaded dispatched when the initial dom for the page is completely loaded. load dispatched after the page—including images—has first finished loading. unload dispatched when the user has navigated away from the page. pageshow dispatched when a page is newly displayed. pagehide dispatched when a page is hidden. standard behavior for web pages is: user navigates to a page. as the page loads, inline scripts run. once the page is loaded, the onload handler fires. some pages include a four...
Appendix: What you should know about open-source software licenses - Archive of obsolete content
e that microsoft sells, such as windows, comes with a license that permits only limited duplication in exchange for a fee, so, although customers can install it on their computers, they cannot modify it. and essential freedoms, such as reverse-engineering, are also restricted. this use permit is displayed when you install the software. when the user clicks “i agree,” the installation process finishes. software range of uses restricted to author unrestricted software license >> usable within permitted scope restricted use within permitted scope fixme: wow, the table is weird! so what’s an oss license? so now you’re wondering, what conditions does an oss license place on software? this can be briefly ...
Chapter 6: Firefox extensions and XUL applications - Archive of obsolete content
objects during step-by-step execution. with functions that include a lot of variables, this will be hard to read, so you can point out specific variables that you want to watch (figure 4). watched variables appear under the watches tab, and are updated every time they are evaluated. you can then continue with stepwise execution and watch the changes in the program and variables. once you’ve finished your inspection, you can continue and let the halted program resume execution. the author has done almost no work developing extensions, but has used this to investigate how extensions were implemented. in the quicknote example, we first set one breakpoint and then stepped through it. use step over to avoid a function, and step into to always call it; once you are done investigating a functio...
Chapter 4: Using XPCOM—Implementing advanced processes - Archive of obsolete content
note that firefox itself and its extensions have privileges set by default after installation and registration. extensions don't need special code like that in listing 2 in order to get privileges. fixme: we should advise against using such method fixme: figure 1: dialog requesting privileges listing 3: grant privileges without manual confirmation for a specific file user_pre...
XPCOM Objects - Archive of obsolete content
ace is just a definition of a set of attributes and methods that an object implementing it should have. xpcom components can implement multiple interfaces, and they often do. let's look at the preference service as an example of this. we'll look at its documentation in a very old xul site called xul planet. all of its documentation was planned to be migrated to mdc, but it looks like it was never finished and xul planet was discontinued. their xpcom documentation is better in terms of seeing the relationships between components and interfaces, so we'll use that. another useful resource is this xpcom reference. this is generated from source, and it's kept relatively up to date. it shows the relationships between components and interfaces, but it's more of a source browser than a documentation re...
Signing an XPI - Archive of obsolete content
tificate, install it into your browser, and attempt to load the signed extension by following these steps: 1. temporarily install the test certificate authority into your mozilla browser rename the x509.cacert file generated earlier to x509.cert import it into mozilla firefox as a software developer certificate authority. don't forget to delete the certificate from mozilla firefox once you've finished testing firefox 1.5: from the tools menu choose options->advanced->security->view certificates->authorities firefox 1.0: from the tools menu choose options->advanced->certificates->manage certificates->authorities press the import button. navigate to the folder containing x509.cert and choose it. in the downloading certificate dialog, tick trust this ca to identify software developers. and...
Tabbed browser - Archive of obsolete content
= wm.getmostrecentwindow("navigator:browser"); mainwindow.gbrowser.addtab(...); opening a url in a new tab // add tab gbrowser.addtab("http://www.google.com/"); // add tab, then make active gbrowser.selectedtab = gbrowser.addtab("http://www.google.com/"); manipulating content of a new tab if you want to work on the content of the newly opened tab, you'll need to wait until the content has finished loading. // wrong way (the page hasn't finished loading yet) var newtabbrowser = gbrowser.getbrowserfortab(gbrowser.addtab("http://www.google.com/")); alert(newtabbrowser.contentdocument.body.innerhtml); // better way var newtabbrowser = gbrowser.getbrowserfortab(gbrowser.addtab("http://www.google.com/")); newtabbrowser.addeventlistener("load", function () { newtabbrowser.contentdocument.bo...
Promises - Archive of obsolete content
row.getresultbyname("group")); } }); // and quickly grab a single row value. let [row] = yield db.execute( "select value from nodes where key = 'timestamp' \ order by value desc limit 1"); latesttimestamp = row.getresultbyindex(0); } finally { // make sure to close the database when finished. // failure to do this will prevent firefox from shutting down // cleanly. yield db.close(); } }); promise wrappers and helpers the following are some example promise-based wrappers for common callback-based asynchronous apis. addonmanager var aom = { __proto__: addonmanager, addon: function addon(addon) { if (!(addon && "getdatadirectory" in add...
Index - Archive of obsolete content
hat contains it. 3427 same-origin policy for file: uris same-origin policy, security, xmlhttprequest in gecko 1.8 or earlier, any two file: uris are considered to be same-origin. in other words, any html file on your local disk can read any other file on your local disk. 3428 source navigator note: this document is still in the draft state. i hope i can finish it within one day or two if i have more time. ;) --kennykaiyinyu 19:04, 10 june 2008 (pdt) 3429 source code directories overview developing mozilla no summary! 3430 using xml data islands in mozilla html5, xml internet explorer had an "xml data islands" feature that allows web authors include xml data inline in html documents using the <xml> tag. this fea...
MMgc - Archive of obsolete content
the ideal solution will result in only one mark incremental per frame unless the mutator is allocating memory so fast we need to mark more aggressively to get to the sweep. so the frequency of the incremental marking will be based on two factors: the rate at which we can trace memory and the rate at which the mutator is requesting more memory. study of real world app...
Source Navigator - Archive of obsolete content
;) --kennykaiyinyu 19:04, 10 june 2008 (pdt) what is source-navigator? (quoted from the internet) source-navigator is a source code analysis tool which lets users to edit, browse and build their projects. with it, you can edit your source code, display relationships between classes and functions and members, and display call trees. you can also build your projects, either with your own makefile, or by using source-navigator's build system to automatically generate a makefile. source-navigator works with the insight gui interface for gdb. ...
Automated testing tips and tricks - Archive of obsolete content
ofile add user_pref("browser.dom.window.dump.enabled", true); to profiledir/user.js how to execute test code with chrome privileges using a chrome doc - see sbtests.xul in http://people.mozilla.com/~davel/scripts/ for an example firefox-bin -p sbtestprofile -chrome chrome://sbtests/content/ above code calls the quit function in quit.js to exit after test is finished how to detect content onload event from chrome use the domcontentloaded event chromewindow.addeventlistener('domcontentloaded',callbackfunction,false); ...
Protecting Mozilla's registry.dat file - Archive of obsolete content
first time, and this seems to have the interesting "side-effect" of wiping any non-microsoft subfolders from %userprofile%\application data, including mozilla's . in order to prevent this, it's preferable to have mozilla's registry.dat file copied over from the server using the logon script. moreover, it's advisable to "protect" the mozilla registry using attrib +r +s in case the logon script is finished before ie's "personnalized settings" have completed their dirty deed... in summary, you can use the following series of commands in your logon script (usually stored in /home/samba/netlogon/startup.bat on the server): rem ================================================== rem mozilla rem ================================================== attrib -r -s "%userprofile%\application data\mozilla" >n...
Adding the structure - Archive of obsolete content
s="statusbarpanel-iconic" id="offline-status"/> <statusbarpanel class="statusbarpanel-iconic" id="security-button" onclick="browserpageinfo(null, 'securitytab')"/> </statusbar> the statusbar xul element defines a horizontal status bar where informative messages about an application's state can be displayed. it can contain both text messages (i.e. "done" in mozilla when a document finishes loading) and graphical messages (f.e. the lock icon in mozilla that shows whether or not a loaded document was encrypted with ssl). status bars comprise a series of panels, each one defined by a statusbarpanel xul element. each status bar panel displays a different kind of status information. graphical panels (like the one we are creating here that displays an icon) are given the statusbarpane...
Creating a Microsummary - Archive of obsolete content
select="id('download-count')"/> <text> fx downloads</text> </template> </transform> </template> </generator> note that white space between xslt tags is not included in the xslt output, unlike in html where that white space is collapsed to a single space, so make sure to prepend a space to the phrase in order to separate it from the download count. with this addition, we've finished writing the xslt transform sheet that converts the spread firefox home page to its microsummary. specifying the page to which the generator applies now that we've written the transform sheet, we have to specify the page to which it applies. if we were the spread firefox webmasters, we might simply reference the generator within the page itself by adding a <link rel="microsummary"> tag to its ...
Installing Dehydra - Archive of obsolete content
ion "building gcc 4.5" if you are using gcc 4.6 or above. building gcc 4.5 for treehydra's process_tree_decl to work, when compiling with g++, you must use a patched gcc 4.5 before building dehydra. cd $home # obtain gcc 4.5.3 (see http://gcc.gnu.org/mirrors.html for alternate mirrors) wget http://www.netgull.com/gcc/releases/gcc-4.5.3/gcc-4.5.3.tar.bz2 tar -jxvf gcc-4.5.3.tar.bz2 # apply plugin_finish_decl patch wget https://bug559964.bugzilla.mozilla.o....cgi?id=457606 -o finish_decl.diff cd gcc-4.5.3 patch -p0 < ../finish_decl.diff # build gcc cd .. mkdir gcc-objdir mkdir gcc-dist cd gcc-objdir ../gcc-4.5.3/configure --disable-bootstrap --enable-languages=c,c++ --prefix=$pwd/../gcc-dist make make install building dehydra and treehydra building dehydra requires spidermonkey development hea...
Download Manager improvements in Firefox 3 - Archive of obsolete content
anager gives applications and extensions access to the download manager, allowing them to add and remove files to the download list, retrieve information about past and present downloads, and request notifications as to the progress of downloads. nsidownload describes a file in the download queue; these files may currently be queued for download, actively being downloaded, or finished being downloaded. nsidownloadprogresslistener applications and extensions implement this interface to be made aware of changes in the status of downloads. nsidownloadmanagerui implement this interface to replace or augment the download manager user interface. other download manager documentation download manager preferences this article lists prefere...
Drag and Drop - Archive of obsolete content
t an element has a chance to remove any highlighting or other indication. ondragdrop this event handler is called for an element when something is dropped on the element. at this point, the user has already released the mouse button. the element can simply ignore the event or can handle it some way, such as pasting the dragged object into itself. ondragend called when the drag operation is finished. there are two ways that drag and drop events can be handled. this first involves using the drag and drop xpcom interfaces directly. the second is to use a javascript wrapper object that handles some of this for you. the code for this wrapper can be found in a file named toolkit/content/nsdraganddrop.js nsdraganddrop.js which is contained in the widget-toolkit (or global) package. xpcom drag...
GRE - Archive of obsolete content
ction between embedding code and xpcom. to use the xpcom glue, you must follow these steps: compile your code with xpcom_glue defined. link with xpcomglue.lib (not xpcomglue_s.lib!). don't link against the nspr libs. find a compatible gre (see above). dynamically link to that gre using the xpcomgluestartup() function. see environment variables below. initialize xpcom and do your work; when finished, shut down xpcom. unlink xpcom with xpcomglueshutdown(). dependent libraries and environment variables the xulrunner gre is designed so that the embedder does not need to set any environment variables such as path or ld_library_path before calling xpcomgluestartup(), because it dynamically loads the correct dependent libraries. unfortunately, the mozilla suite-based gre is not as forgiving,...
Scripting - Archive of obsolete content
fox extension is loaded into the browser chrome window. it can contain the following functions: startup when the app starts, before the user interface is displayed. since the web application has not yet loaded, the window object is still undefined. preload just before the user interface is displayed. returning false causes the application to terminate. load after the main application windows has finished loading. the window object has been initialized and can be used. error if there is an error loading the main app page (e.g. the server is not accessible). shutdown just before the application terminates. prism exposes desktop integration features through an property of the window object called platform. the platform property implements the nsiplatformglue interface, whose methods are described...
Supporting per-window private browsing - Archive of obsolete content
.e., when the last private window is closed), observe the last-pb-context-exited notification. function pbobserver() { /* clear private data */ } var os = components.classes["@mozilla.org/observer-service;1"] .getservice(components.interfaces.nsiobserverservice); os.addobserver(pbobserver, "last-pb-context-exited", false); preventing a private session from ending if there are unfinished transactions involving private data, where the transactions will be terminated by the ending of a private session, an add-on can vote to prevent the session from ending (prompting the user is recommended). to do this, observe the last-pb-context-exiting notification and set the data field of the nsisupportsprbool subject to true. var os = components.classes["@mozilla.org/observer-service;1"] ...
Running Tamarin acceptance tests - Archive of obsolete content
ist of all flags, run runtests.py with -h/--help) --nohtml : will suppress the creation of an html output file --rebuildtests : will only rebuild test .abc's, will not attempt to run them. ...
Tamarin build documentation - Archive of obsolete content
tive build configuration' in the 'build configuration for the indexer' section. ...
Writing textual data - Archive of obsolete content
r.charset = /* the character encoding you want, using utf-8 for this example */ "utf-8"; now you can convert and write to the stream: // this code assumes that os is your nsioutputstream // your_string here is the string you want to write. var chunk = converter.convertfromunicode(your_string); os.write(chunk, chunk.length); // repeat as needed for further strings at the end, you need to call finish and write its data to the stream. note that not many character encodings need it, but for those that do calling this is important for proper output. var fin = converter.finish(); if (fin.length > 0) os.write(fin, fin.length); os.close(); converting a string into a stream sometimes, it is useful to convert a string into a stream, for example for uploading it using nsiuploadchannel. the ...
initInstall - Archive of obsolete content
urns an integer error code. for a list of possible values, see return codes. description the initinstall method initializes the installation of the specified software. you must call this method immediately after the constructor. it is an error to call any other install methods before calling initinstall. after calling initinstall, your script must call performinstall or cancelinstall before it finishes. if your script does not call performinstall or cancelinstall, netscape 6 will not be able to clean up properly after your script finishes. example to start installation for the royal airways plug-in, you could use this code: initinstall("royal airways tripplanner","/royalairways/ tripplanner","1.0.0.0"); ... err = getlasterror(); if (!err) performinstall(); else cancelinstall(err); ...
image.onload - Archive of obsolete content
this applies whether the image is applied via the src attribute or the list-style-image style property. ...
onsearchcomplete - Archive of obsolete content
...
prefwindow.onload - Archive of obsolete content
...
Attribute (XUL) - Archive of obsolete content
ondialogclosure ondialogextra1 ondialogextra2 ondialoghelp onerror onerrorcommand onextra1 onextra2 oninput onload onnewtab onpageadvanced onpagehide onpagerewound onpageshow onpaneload onpopuphidden onpopuphiding onpopupshowing onpopupshown onsearchcomplete onselect ontextcommand ontextentered ontextrevert ontextreverted onunload onwizardback onwizardcancel onwizardfinish onwizardnext open ordinal orient pack pageid pageincrement pagestep parent parsetype persist persistence phase pickertooltiptext placeholder popup position predicate preference preference-editable primary priority properties querytype readonly ref rel removeelement resizeafter resizebefore rows screenx screeny searchbutton searchsessions searchlabel selected ...
Building accessible custom components in XUL - Archive of obsolete content
note that when we recreate the label element after editing, we need to explicitly restore the role attribute of the label, so that assistive technologies will continue to treat it as a cell within the spreadsheet. <code> const xul_ns = "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"; const x2_ns ="http://www.w3.org/tr/xhtml2" function start_edit(label) { var value =...
Reading from Files - Archive of obsolete content
ethod returns 0 if there is no more data to read, so you could use a loop to read a number of strings. this example keeps reading 10 character strings from a file until there is no more data to read. note that the last string read may be less than ten characters long. while(stream.available()) output += stream.readstring(10); the close method is used at the end to close the stream when you are finished reading from it. you should always strive to close a stream when you have finished reading or writing to it to ensure that it doesn't remain open longer than necessary. reading lines the readline method may be used to read a line from the file. this method doesn't take a count of characters to read but instead keeps reading until the end of a line is reached. this method handles all the differe...
Index - Archive of obsolete content
Archive › Mozilla › XUL › Index
vert xul attributes, xul reference no summary! 251 ontextreverted xul attributes, xul reference no summary! 252 onunload xul attributes, xul reference no summary! 253 onwizardback xul attributes, xul reference no summary! 254 onwizardcancel xul attributes, xul reference no summary! 255 onwizardfinish xul attributes, xul reference no summary! 256 onwizardnext xul attributes, xul reference no summary! 257 open needshelp, xul attributes, xul reference, needsattention no summary! 258 ordinal xul attributes, xul reference no summary! 259 orient xul attributes, xul reference no summary! 260 pack...
canAdvance - Archive of obsolete content
...
RDF Modifications - Archive of obsolete content
receive any notifications. this saves a lot of extra work. the rdf observer also has two methods onbeginupdatebatch and onendupdatebatch. these are called when performing a lot of operations on a datasource. when changing the datasource, the changes are surrounded by begin and end batch calls. then, rather than notify on every change, the datasource will send one notification when the changes are finished. the template builder then rebuilds the template completely when done. this is useful when making a large amount of changes to avoid having to keep recalculating parts of the template that might change again quickly. adding rdf triples let's say we've just added the triple below to the datasource. subject: http://www.xulplanet.com/ndeakin/images/t/obelisk.jpg predicate: http://purl.org/dc/e...
Template and Tree Listeners - Archive of obsolete content
d may be attached to a tree builder using the builder's addobserver method. you can add more than one observer if needed, and can remove them again with the builder's removeobserver method. the observer is always invoked before the appropriate operation is performed. for instance, the ontoggleopenstate method of any observers will be called before the tree item is opened. after the observers have finished, the tree builder opens the row and adds any child rows inside. note that you cannot cancel the operation from within the observer. some useful functions of the observer are the drag and drop related callbacks to handle when an item is dragged onto the tree. this makes handling dragging onto a tree fairly simple. all you need to do is implement three methods, candropon, candropbeforeafter and o...
textbox (Toolkit autocomplete) - Archive of obsolete content
not called when the user presses non-displayable keys. onsearchbegin type: script code this event handler is called when the autocomplete search begins. note: for firefox 12 and above, this event handler must be set as an initial attribute. onsearchcomplete new in thunderbird 3requires seamonkey 2.0 type: script code this event handler is called when the autocomplete search is finished and results are available. note: for firefox 12 and above, this event handler must be set as an initial attribute. ontextentered new in thunderbird 3requires seamonkey 2.0 type: script code this event handler is called when a result is selected for the textbox. note: for firefox 12 and above, this event handler must be set as an initial attribute. ontextreverted new in thunderbi...
Textbox (XPFE autocomplete) - Archive of obsolete content
ng a result from the popup. oninput type: script code this event is sent when a user enters text in a textbox. this event is only called when the text displayed would change, thus it is not called when the user presses non-displayable keys. onsearchcomplete new in thunderbird 3requires seamonkey 2.0 type: script code this event handler is called when the autocomplete search is finished and results are available. ontextcommand obsolete since gecko 1.9.1 type: script code note: applies to: thunderbird, seamonkeythis event handler is called when a result is selected for the textbox. as of gecko 1.9.1, this attribute is superseded by the ontextentered attribute. ontextentered new in thunderbird 3requires seamonkey 2.0 type: script code this event handler is call...
Complete - Archive of obsolete content
this page is for readers who have followed the custom toolbar button tutorial for firefox, thunderbird and sunbird, or the custom toolbar button:seamonkey tutorial for seamonkey, and who want to learn more about developing extensions. introduction you can use the custom toolbar button tutorial as a very simple introduction to extensions. however, because it is so simple it does not support some of the usual features of extensions. this page describes how to structure the extension in a more conventional way. this page is not a step-by-step tutorial. instead it explains the missing features, and outlines how to add them. ...
Toolbar customization events - Archive of obsolete content
window.addeventlistener("beforecustomization", customizestart, false); window.addeventlistener("aftercustomization", customizeend, false); window.addeventlistener("customizationchange", customizechange, false); function customizestart(e) { let thetoolbox = e.target; /* now we know the user has started customizing */ } function customizeend(e) { let thetoolbox = e.target; /* the user has finished customizing */ } function customizechange(e) { let thetoolbox = e.target; /* the user has made a change to the toolbox */ } ...
Adding Event Handlers - Archive of obsolete content
hen to the document, followed by each ancestor of the xul element where the event occured downwards until it reaches that element. in the target phase, the event is sent to the target xul element. in the bubbling phase, the event is sent to each element back upwards until it reaches the window again. you can respond to an event during either the capturing or bubbling phase. once the event has finished propagating, any default action will occur, which is the built in behaviour of the element. for example, when the mouse is moved over a button that is inside a box, a 'mousemove' event is generated, and sent first to the window, followed by the document, and then the box. that completes the capturing phase. next, the 'mousemove' event is sent to the button. finally, the bubbling phase causes t...
Adding Methods to XBL-defined Elements - Archive of obsolete content
there are two points when a binding is attached to an element. the first occurs when a window is displayed. all elements that have xbl-bound content will have their constructors invoked. the order that they are called in should not be relied upon, as they are loaded from various files. the window's onload handler is not called until after all the bindings have been attached and their constructors finished. the second point is when a binding is attached by changing the -moz-binding style property of an element. the existing binding will be removed, after its destructor is called. then, the new binding will be added in its place and its constructor invoked. the script for a constructor or destructor should be placed directly inside the appropriate tag. there should only be at most one of each per...
More Event Handlers - Archive of obsolete content
y. we'll learn more about the box object in a later section, but it holds information pertaining to how the element is displayed, including the x and y position of the element. in this example code, these coordinates are subtracted from the event coordinates to get the event position relative to the element. load events the load event is sent to the document (the window tag) once the xul file has finished loading and just before the content is displayed. this event is commonly used to initialize fields and perform other tasks that need to be done before the user can use the window. you should use a load event to do these kinds of things as opposed to adding a script at the top level outside of a function. this is because the xul elements may not have loaded or fully initialized yet, so some thin...
Progress Meters - Archive of obsolete content
eted. you typically see it when downloading files or when performing a lengthy operation. xul has a progressmeter element which can be used to create these. there are two types of progress meters: determinate and indeterminate. determinate progress meters are used when you know the length of time that an operation will take. the progress meter will fill up and, once full, the operation should be finished. this can be used for the download file dialog as the size of the file is known. indeterminate progress meters are used when you do not know the length of time of an operation. the progress meter will have an animation such as a spinning barber pole or a sliding box, depending on the platform and theme used. determinate progress meter: indeterminate progress meter: the progress meter has ...
XUL Questions and Answers - Archive of obsolete content
mponents.interfaces.nsisupports)) return this; throw components.results.ns_nointerface; } listobj.onstatechange = function(aprogress, arequest, aflag, astatus) { if (aflag & listobj.wpl.state_start) { // this fires when the load event is initiated } else { if (aflag & listobj.wpl.state_stop) { if ( aflag & listobj.wpl.state_is_window ) { // this fires when all load finish } if ( aflag & listobj.wpl.state_is_network ) { // fires when all load are really over, // do something "final" here // (my two cents) } else { // this fires when a load finishes } } } return 0; } // this fires when the location bar changes i.e load event is confirmed // or when the user switches tabs listobj.onlocationchange = fun...
image - Archive of obsolete content
Archive › Mozilla › XUL › image
cessibletype, src style classes alert-icon, error-icon, message-icon, question-icon examples <image src='firefoxlogo.png' width='135' height='130'/> attributes onerror type: script code this event is sent to an image element when an error occurs loading the image. image.onload type: script code this event handler will be called on the image element when the image has finished loading. this applies whether the image is applied via the src attribute or the list-style-image style property. if you change the image, the event will fire again when the new image loads. this event will not bubble up the element tree. src type: uri the uri of the content to appear in the element. validate type: one of the values below this attribute indic...
prefwindow - Archive of obsolete content
s called. if the routine returns true, the dialog will indeed go away, but if it returns false it will not. ondialogdisclosure type: script code the code in this attribute is called when the "disclosure" button is pressed. ondialoghelp type: script code the code in this attribute is called when the "help" button is pressed. prefwindow.onload type: script code when a window finishes loading, it calls this event handler on the prefwindow element. title type: string the text to appear in the title bar of the window. type type: string set this attribute to child for preference dialogs that are child dialogs of a main preferences window. this ensures that the preferences are only saved when the main dialog is closed, if this is the appropriate behaviour for t...
wizard - Archive of obsolete content
boolean this property is set to true if the user can press the next button to go to the next page. if this property is false, the user cannot navigate to the next page. set this property to true to indicate that the user can go to the next page. set to false to disallow moving to the next page. this has the effect of enabling or disabling the next button, or, on the last page of the wizard, the finish button. canrewind type: boolean this property is set to true if the user can press the back button to go to the previous page. if this property is false, the user cannot navigate to the previous page. set this property to true to indicate that the user can go back a page. set to false to disallow moving to the previous page. this has the effect of enabling or disabling the back button. ...
Debugging a XULRunner Application - Archive of obsolete content
see: preference reference for more information about these preferences. console to enable a console on windows, start xulrunner with the -console argument. note that -console goes after the application.ini argument: e.g. xulrunner.exe /path/to/application.ini -console to output text to the console, use dump("m...
Getting started with XULRunner - Archive of obsolete content
see xul application packaging for details. mac on the mac, before you can run a xulrunner application with everything intact, you must install it using the --install-app xulrunner commandline flag. installing the application creates an os x application bundle: /library/frameworks/xul.framework/xulrunner-bin --install-app /<path>/<to>/myapp.zip once installed, you can run th...
Make your xulrunner app match the system locale - Archive of obsolete content
p is to get the code we're about to write to run before any of the locale specific resources are loaded. democracy does this by creating a command line handler called democracyclh, and then creating a new object of our pybridge component. the code described lives in the pybridge component's onstartup method which gets called automatically. the second step is to figure out the system locale. to be finished later. then set the locale preference. the following is python code to set this preference. from xpcom import components ps_cls = components.classes["@mozilla.org/preferences-service;1"] ps = ps_cls.getservice(components.interfaces.nsiprefservice) branch = ps.getbranch("general.useragent.") branch.setcharpref("locale", lang) i also set the language environment variable to match the system loc...
Mozprocess - Archive of obsolete content
ontained subclass of subprocess.popen, process, which does the brunt of the process management. basic usage: process = processhandler(['command', '-line', 'arguments'], cwd=none, # working directory for cmd; defaults to none env={}, # environment to use for the process; defaults to os.environ ) exit_code = process.waitforfinish(timeout=60) # seconds see an example in https://github.com/mozilla/mozbase/b...profilepath.py processhandler may be subclassed to handle process timeouts (by overriding the ontimeout() method), process completion (by overriding onfinish()), and to process the command output (by overriding processoutputline()). todo document improvements over subprocess.popen.kill ...
NPByteRange - Archive of obsolete content
e last request. description the plug-in seeks within a stream by building a linked list of one or more npbyterange objects, which represents a set of discontiguous byte ranges. the only plug-in api call that uses the npbyterange type is npn_requestread(), which lets the plug-in read specified parts of a file without downloading it. the plug-in is responsible for deleting npbyterange objects when finished with them. the browser makes a copy if it needs to keep the objects beyond the call to npn_requestread(). see also npn_requestread() ...
NPN_GetURLNotify - Archive of obsolete content
est and calls npp_urlnotify(). this notification is the only way the plug-in can tell whether a request with a null target failed, or that a request with a non-null target completed. for requests that complete unsuccessfully, the browser calls npp_urlnotify() as soon as possible. for requests that complete successfully: if the target is non-null, the browser calls npp_urlnotify() after it has finished loading the url. if the target is null, the browser calls npp_urlnotify() after closing the stream by calling npn_destroystream(). if this function is called with a target parameter value of _self or a parent to _self, this function should return nperr_invalid_param. this is the only way to notify the plug-in once it is deleted. warning: in gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonke...
NPP_DestroyStream - Archive of obsolete content
operations. npres_network_err: stream failed due to problems with network, disk i/o, lack of memory, or other problems. returns if successful, the plug-in should return nperr_no_error. if unsuccessful, the plug-in should return an error code. for possible values, see error codes. description the browser calls the npp_destroystream function when a data stream sent to the plug-in is finished, either because it has completed successfully or terminated abnormally. after this, the browser deletes the npstream object. you should delete any private data allocated in stream->pdata at this time, and should not make any further references to the stream object. see also npp_newstream, npstream ...
Introduction to SSL - Archive of obsolete content
he ssl session and to verify its integrity-that is, to detect any changes in the data between the time it was sent and the time it is received over the ssl connection. the client sends a message to the server informing it that future messages from the client will be encrypted with the session key. it then sends a separate (encrypted) message indicating that the client portion of the handshake is finished. the server sends a message to the client informing it that future messages from the server will be encrypted with the session key. it then sends a separate (encrypted) message indicating that the server portion of the handshake is finished. the ssl handshake is now complete, and the ssl session has begun. the client and the server use the session keys to encrypt and decrypt the data they sen...
Create Your Own Firefox Background Theme - Archive of obsolete content
it will be anchored to the top-right corner of the browser window. view a sample theme header here. ...
Using IO Timeout And Interrupt On NT - Archive of obsolete content
d the io function fails with <tt>pr_io_timeout_error</tt> or <tt>pr_pending_interrupt_error</tt>, the file descriptor must be closed before the thread exits. in this memo we explain the problem this guideline is trying to work around and discuss its limitations. nspr io on nt the io model of nspr 2.0 is synchronous and blocking. a thread calling an io function is blocked until the io operation finishes, either due to a successful io completion or an error. if the io operation cannot complete before the specified timeout, the io function returns with <tt>pr_io_timeout_error</tt>. if the thread gets interrupted by another thread's <tt>pr_interrupt()</tt> call, the io function returns with <tt>pr_pending_interrupt_error</tt>. on windows nt, nspr io is implemented using nt's overlapped (also call...
Using SSH to connect to CVS - Archive of obsolete content
exit essentially both sets of commands do the same thing. first ssh-agent is called and its output is evaluated in the current environment. this sets environment variables that let cvs know how to find and use the agent. your private key is then added to ssh-agent using ssh-add at which point you will be prompted for the key's passphrase. since it's important that you kill the agent when you're finished with it, the last three lines start a child environment that, when exited, will result in the agent's process being killed. the environment you will actually use to build is the child environment. there are a few things to note about the commands for the ms-dos command prompt. first of all they will only work in versions of windows based on nt (nt/2000/xp). if you're building on win9x/winme yo...
Styling the Amazing Netscape Fish Cam Page - Archive of obsolete content
left, a one-pixel border the rest of the way around, and set the background to match the rest of the design. thus: div.card {float: left; width: 45%; margin: 1em 2% 0 2%;} div.card img {float: left; margin: 4px 0 0 0; border: 1px solid #339;} div.card h3 {border: 1px solid #339; border-left: 5px double #339; background: #eec url(body-bg-tan.jpg) bottom left no-repeat fixed; color: #339;} finishing the style adding the background to the heading containing the name of the fish created three problems: the double border was completely covered up by the image. the text of the h3 was basically touching the right side of the floated image... ...or it would have been, except in some browsers the heading was drawn over the floated image, in contradiction to the css specification. getting...
Reference - Archive of obsolete content
for us here, however i am unaware of anyone feverishly working on it. (there are some other priorities ahead of that, imho). if downloading the stuff is your priority you are free to field ideas/concept to the devmo mailing list for discussion, and then actually code it (or find someone to do so). thanks for your thoughts --callek 15:05, 13 january 2006 (pst) notification when reorganization is finished leandro (localiser for the portuguese wiki) would like to be emailed when the js reference reorganization has been finished. his user page is here: http://developer.mozilla.org/pt/docs...%c3%aas_xavier -- dria 08:19, 24 february 2006 (pst) object and function relation here is my problem , it has been breaking my head for quite some time now. i'm very confused about the way function and obj...
Building Mozilla XForms - Archive of obsolete content
ac_add_options --enable-extensions="default,xforms" ac_add_options --enable-debug ac_add_options --disable-optimize ac_add_options --disable-tests building now that you have everything ready, you can rebuild mozilla with the same command you used before to build firefox without xforms. switch to the root of your source directory and start the build with make -f client.mk build after the build finishes, you'll have a xforms.xpi in obj-*/dist/xpi-stage/xforms.xpi. congratulations, you've successfully built your first mozilla xforms extension! the built xpi file will only install on a nightly snapshot from the same day or your self-built firefox version. if you are sure that older or newer firefox versions are compatible with your extension, you can unzip the xpi file (it's a regular zip file),...
Fixing Incorrectly Sized List Item Markers - Archive of obsolete content
summary: an obscure bug in gecko causes list-item markers to be differently sizeed than the text of the list item, but there is a fix authors can use. learn how to correctly size list item markers in gecko 0.9.4, the basis of netscape 6.2.x and compuserve 7. shortly before mozilla 0.9.4 was finished, a bug was introduced that affects the sizing of list item markers (such as the numbers in an ordered list). while this bug was corrected shortly after 0.9.4 was finished, the bug still affects all netscape 6.2.x versions, as well as compuserve 7.0. the problem in affected browsers, list item markers will very often appear to be too big compared to the text in the list item itself. this is most obvious in ordered lists, where the number that precedes each list item may be obviously different than ...
Publishing games - Game development
me distribution so you've followed a tutorial or two and created an html5 game — that's great! game distribution provides all you need to know about the ways you can distribute your newly created game into the wild — including hosting it yourself online, submitting it to open marketplaces, and submitting it to closed ones like google play or the ios app store. game promotion developing and finishing the game is not enough. you have to let the world know that you have made something interesting available, which people will enjoy playing. there are many game promotion techniques — many of them free — so even if you're struggling to make a living as an indie dev with zero budget you can still do a lot to let people know about your great new game. promoting the game helps a lot in monetiz...
Building up a basic demo with PlayCanvas editor - Game development
se the online playcanvas editor. this can be a more pleasant working environment if you are not someone who likes to code. creating an account the playcanvas editor is free — all you have to do to begin with is register your account and login: when you first sign up, you are taken straight into the editor and given a simple starter tutorial involving editing a 3d rolling ball game. you can finish this before you continue our tutorial if you like. when you are ready to continue with our tutorial, go to your canvas homepage — for example mine is https://playcanvas.com/end3r. here's what the page looks like — you can create projects and manage them, change their settings etc. creating a new project start a brand new project by clicking on the new button: the resulting dialog box wil...
Audio for Web games - Game development
let's create another async function to set up the sample — we can combine the two async functions in a nice promise pattern to perform further actions when each file is loaded and buffered: async function loadfile(filepath) { const track = await getfile(filepath); return track; } let's also create a playtrack() function, which we can call once a file has been fetched. we ne...
Desktop mouse and keyboard controls - Game development
ch let's think about implementing pure javascript keyboard/mouse controls in the game first to see how it would work. first, we'd need an event listener to listen for the pressed keys: document.addeventlistener('keydown', keydownhandler, false); document.addeventlistener('keyup', keyuphandler, false); whenever any key is pressed down, we're executing the keydownhandler function, and when press finishes we're executing the keyuphandler function, so we know when it's no longer pressed. to do that we'll hold the information on whether the keys we are interested in are pressed or not: var rightpressed = false; var leftpressed = false; var uppressed = false; var downpressed = false; then we will listen for the keydown and keyup events and act accordingly in both handler functions. inside them we...
Bounce off the walls - Game development
dy = -dy; } when the distance between the center of the ball and the edge of the wall is exactly the same as the radius of the ball, it will change the movement direction. subtracting the radius from one edge's width and adding it onto the other gives us the impression of the proper collision detection — the ball bounces off the walls as it should do. compare your code lets again check the finished code for this part against what you've got, and have a play: exercise: try changing the color of the ball to a random colour every time it hits the wall. next steps we've now got to the stage where our ball is both moving and staying on the game board. in the fourth chapter we'll look at implementing a controllable paddle — see paddle and keyboard controls. « previousnext » ...
Create the Canvas and draw on it - Game development
ctx.beginpath(); ctx.arc(240, 160, 20, 0, math.pi*2, false); ctx.fillstyle = "green"; ctx.fill(); ctx.closepath(); as you can see we're using the beginpath() and closepath() methods again. between them, the most important part of the code above is the arc() method. it takes six parameters: x and y coordinates of the arc's center arc radius start angle and end angle (what angle to start and finish drawing the circle, in radians) direction of drawing (false for clockwise, the default, or true for anti-clockwise.) this last parameter is optional. the fillstyle property looks different than before. this is because, just as with css, color can be specified as a hexadecimal value, a color keyword, the rgba() function, or any of the other available color methods. instead of using fill() and ...
Move the ball - Game development
a separate function. replace the existing draw() function with the following two functions: function drawball() { ctx.beginpath(); ctx.arc(x, y, 10, 0, math.pi*2); ctx.fillstyle = "#0095dd"; ctx.fill(); ctx.closepath(); } function draw() { ctx.clearrect(0, 0, canvas.width, canvas.height); drawball(); x += dx; y += dy; } compare your code you can check the finished code for this article for yourself in the live demo below, and play with it to understand better how it works: exercise: try changing the speed of the moving ball, or the direction it moves in. next steps we've drawn our ball and gotten it moving, but it keeps disappearing off the edge of the canvas. in the third chapter we'll explore how to make it bounce off the walls. « previou...
2D breakout game using pure JavaScript - Game development
you should be able to build your own simple web games. lesson details all the lessons — and the different versions of the mdn breakout game we are building together — are available on github: create the canvas and draw on it move the ball bounce off the walls paddle and keyboard controls game over build the brick field collision detection track the score and win mouse controls finishing up starting with pure javascript is the best way to get a solid knowledge of web game development. after that, you can pick any framework you like and use it for your projects. frameworks are just tools built with the javascript language; so even if you plan on working with them, it's good to learn about the language itself first to know what exactly is going on under the hood. frameworks sp...
Bounce off the walls - Game development
unds = true; now the ball will stop at the edge of the screen instead of disappearing, but it doesn't bounce. to make this occur we have to set its bounciness. add the following line below the previous one: ball.body.bounce.set(1); try reloading index.html again — now you should see the ball bouncing off all the walls and moving inside the canvas area. compare your code you can check the finished code for this lesson in the live demo below, and play with it to understand better how it works: next steps this is starting to look more like a game now, but we can't control it in any way — it's high time we introduced the player paddle and controls. « previousnext » ...
Build the brick field - Game development
the ball goes through the bricks without stopping — we need proper collision detection. « previousnext » ...
Buttons - Game development
« previousnext » ...
Collision detection - Game development
k in question from the screen simply by running the kill() method on it. you would expect to have to write a lot more calculations of your own to implement collision detection when using pure javascript. that's the beauty of using the framework — you can leave a lot of boring code to phaser, and focus on the most fun and interesting parts of making a game. compare your code you can check the finished code for this lesson in the live demo below, and play with it to understand better how it works: next steps we can hit the bricks and remove them, which is a nice addition to the gameplay already. it would be even better to count the destroyed bricks increment the score as a result. « previousnext » ...
Extra lives - Game development
and causes it to be executed every time the event occurs, while addonce() is useful when you want to have the bound function executed only once and then unbound so it is not executed again. in our case, on every outofbounds event the ballleavescreen will be executed, but when the ball leaves the screen we only want to remove the message from the screen once. compare your code you can check the finished code for this lesson in the live demo below, and play with it to understand better how it works: next steps lives made the game more forgiving — if you lose one life, you still have two more left and can continue to play. now let's expand the look and feel of the game by adding animations and tweens. « previousnext » ...
Game over - Game development
ball.checkworldbounds = true; ball.events.onoutofbounds.add(function(){ alert('game over!'); location.reload(); }, this); adding those lines will make the ball check the world (in our case canvas) bounds and execute the function bound to the onoutofbounds event. when you click on the resulting alert, the page will be reloaded so you can play again. compare your code you can check the finished code for this lesson in the live demo below, and play with it to understand better how it works: next steps now the basic gameplay is in place let's make it more interesting by introducing bricks to smash — it's time to build the brick field. « previousnext » ...
Load the assets and print them on screen - Game development
d.sprite(50, 50, 'ball'); } this will add the ball to the game and render it on the screen. the first two parameters are the x and y coordinates of the canvas where you want it added, and the third one is the name of the asset we defined earlier. that's it — if you load your index.html file you will see the image already loaded and rendered on the canvas! compare your code you can check the finished code for this lesson for yourself in the live demo below, and play with it to better understand how it works: next steps printing out the ball was easy; next, we'll try moving the ball on screen. « previousnext » ...
Move the ball - Game development
hat will update the ball's position on screen. add the following new lines of the code inside update(), as shown: function update() { ball.x += 1; ball.y += 1; } the code above adds 1 to the x and y properties representing the the ball coordinates on the canvas, on each frame. reload index.html and you should see the ball rolling across the screen. compare your code you can check the finished code for this lesson in the live demo below, and play with it to understand better how it works: next steps the next step is to add some basic collision detection, so our ball can bounce off the walls. this would take several lines of code — a significantly more complex step than we have seen so far, especially if we want to add paddle and brick collisions too — but fortunately phaser a...
Physics - Game development
e launched upwards, but then fall due to the effects of gravity pulling it down. this kind of functionality is just the tip of the iceberg — there are various functions and variables that can help you manipulate the physics objects. check out the official physics documentation and see the huge collection of examples using the arcade and p2 physics systems. compare your code you can check the finished code for this lesson in the live demo below, and play with it to understand better how it works: next steps now we can move to the next lesson and see how to make the ball bounce off the walls. « previousnext » ...
Player paddle and controls - Game development
et(0.5); the velocity stays almost the same — we're just changing the second parameter's value from 150 to -150, so the ball will start the game by moving up instead of down. find the existing ball.body.velocity.set( ... ) line and update it to the following: ball.body.velocity.set(150, -150); now the ball will start right from the middle of the paddle. compare your code you can check the finished code for this lesson in the live demo below, and play with it to understand better how it works: next steps we can move the paddle and bounce the ball off it, but what's the point if the ball is bouncing off the bottom edge of the screen anyway? let's introduce the possibility of losing — also known as game over logic. « previousnext » ...
Randomizing gameplay - Game development
the paddle it will bounce left, whereas hitting the right side will bounce it to the right. it ended up that way because of a little bit of experimentation with the given values, you can do your own experimentation and see what happens. it's not completely random of course, but it does make the gameplay a bit more unpredictable and therefore more interesting. compare your code you can check the finished code for this lesson in the live demo below, and play with it to understand better how it works: summary you've finished all the lessons — congratulations! by this point you would have learnt the basics of phaser and the logic behind simple 2d games. exercises to follow you can do a lot more in the game — add whatever you feel would be best to make it more fun and interesting. it's a ...
Scaling - Game development
ardless of size. adding a custom canvas background colour we can also add a custom background color to our canvas, so it won't stay black. the stage object has a backgroundcolor property for this purpose, which we can set using css color definition syntax. add the following line below the other three you added earlier: game.stage.backgroundcolor = '#eee'; compare your code you can check the finished code for this lesson in the live demo below, and play with it to understand better how it works: next steps now we've set up the scaling for our game, let's continue to the third lesson and work out how to load the assets and print them on screen. « previousnext » ...
The score - Game development
xt to display the current score. this can be done using the settext() method — add the two new lines seen below to the ballhitbrick() function: function ballhitbrick(ball, brick) { brick.kill(); score += 10; scoretext.settext('points: '+score); } that's it for now — reload your index.html and check that the score updates on every brick hit. compare your code you can check the finished code for this lesson in the live demo below, and play with it to understand better how it works: next steps we now have a scoring system, but what's the point of playing and keeping score if you can't win? let's see how we can add a victory state, allowing us to win the game. « previousnext » ...
Win the game - Game development
(count_alive == 0) { alert('you won the game, congratulations!'); location.reload(); } } we loop through the bricks in the group using bricks.children, checking for the aliveness of each with each brick's .alive() method. if there are no more bricks left alive, then we show a winning message, restarting the game once the alert is dismissed. compare your code you can check the finished code for this lesson in the live demo below, and play with it to understand better how it works: next steps both losing and winning are implemented, so the core gameplay of our game is finished. now let's add something extra — we'll give the player three lives instead of one. « previousnext » ...
Gecko FAQ - Gecko Redirect 1
devices with network access and wish to include web browsing functionality. likewise, many software developers want to include web browsing capability in their applications, but don't want to independently develop browser software. these developers can pick and choose the browser components they want from among those that gecko offers, and package these components alongside their own within their finished products. which open standards is the gecko development project working to support, and to what extent does it support them? by the end of calendar year 2000, gecko is expected to support the following recommended open internet standards fully except for the areas noted below and open bugs documented in bugzilla: html 4.0 - full support except for: elements: bdo, basefont attribut...
Call stack - MDN Web Docs Glossary: Definitions of Web-related terms
multiple functions — what function is currently being run and what functions are called from within that function, etc. when a script calls a function, the interpreter adds it to the call stack and then starts carrying out the function. any functions that are called by that function are added to the call stack further up, and run where their calls are reached. when the current function is finished, the interpreter takes it off the stack and resumes execution where it left off in the last code listing. if the stack takes up more space than it had assigned to it, it results in a "stack overflow" error. example function greeting() { // [1] some codes here sayhi(); // [2] some codes here } function sayhi() { return "hi!"; } // invoke the `greeting` function greeting(); // [...
Control flow - MDN Web Docs Glossary: Definitions of Web-related terms
all of the fields in the form, checking each one in turn. looking back at the code in the if and else sections, the lines promptuser and submitform could also be calls to other functions in the script. as you can see, control structures can dictate complex flows of processing even with only a few lines of code. control flow means that when you read a script, you must not only read from start to finish but also look at program structure and how it affects order of execution. learn more general knowledge control flow on wikipedia technical reference javascript reference - control flow on mdn learn about it statements (control flow) on mdn ...
HTTP header - MDN Web Docs Glossary: Definitions of Web-related terms
an http header is a field of an http request or response that passes additional information, altering or precising the semantics of the message or of the body. headers are case-insensitive, begins at the start of a line and are immediately followed by a ':' and a value depending of the header itself. the value finish at the next crlf or at the end of the message. traditionally, headers are classed in categories, though this classification is no more part of any specification: general header: headers applying to both requests and responses but with no relation to the data eventually transmitted in the body. request header: headers containing more information about the resource to be fetched or about the client itself. response header: headers with additional information about the re...
Promise - MDN Web Docs Glossary: Definitions of Web-related terms
a promise is an object that's returned by a function that has not yet completed its work. the promise literally represents a promise made by the function that it will eventually return a result through the promise object. when the called function finishes its work asynchronously, a function on the promise object called a resolution (or fulfillment, or completion) handler is called to let the original caller know that the task is complete. learn more to learn more, have a look at these links. general knowledge futures and promises technical reference promise in the javascript reference. using promises ...
Time to interactive - MDN Web Docs Glossary: Definitions of Web-related terms
tti, proposed by the web incubator community group in 2018, is intended to provide a metric that describes when a page or application contains useful content and the main thread is idle and free to respond to user interactions, including having event handlers registered. ...
Speculative parsing - MDN Web Docs Glossary: Definitions of Web-related terms
uilder state such that the speculative state after the </script> tag no longer holds when all the content inserted by document.write() has been parsed. however, only unusual uses of document.write() cause trouble. here are the things to avoid: don't write unbalanced trees. <script>document.write("<div>");</script> is bad. <script>document.write("<div></div>");</script> is ok. don't write an unfinished token. <script>document.write("<div></div");</script> is bad. don't finish your writing with a carriage return. <script>document.write("hello world!\r");</script> is bad. <script>document.write("hello world!\n");</script> is ok. note that writing balanced tags may cause other tags to be inferred in a way that makes the write unbalanced. e.g. <script>document.write("<div></div>");</script> ins...
Assessment: Accessibility troubleshooting - Learn web development
se the example. decompress the contents into a new directory somewhere on your local computer. alternatively, you could use a site like jsbin or glitch to do your assessment. you could paste the html, css, and javascript into one of these online editors. if the online editor you are using doesn't have a separate css/js panel, feel free to put them in appropriate <style> / <script> elements. the finished assessment site should look like so: you will see some differences/issues with the display of the starting state of the assessment — this is mainly due to the differences in the markup, which in turn cause some styling issues as the css is not applied properly. don't worry — you'll be fixing these problems in the upcoming sections! note: if you get stuck, then ask us for help — see t...
A cool-looking box - Learn web development
ame color until the end. multiple box shadows. give it one standard box shadow to make the box look slightly raised off the page. the other two should be inset box shadows — a semi-transparent white shadow near the top left and a semi-transparent black shadow near the bottom right — to add to the nice raised 3d look of the box. example the following screenshot shows an example of what the finished design could look like: assessment or further help if you would like your work assessed, or are stuck and want to ask for help: put your work into an online shareable editor such as codepen, jsfiddle, or glitch. write a post asking for assessment and/or help at the mdn discourse forum learning category. your post should include: a descriptive title such as "assessment wanted for c...
Creating fancy letterheaded paper - Learn web development
llback version of a declaration first, followed by the version that works across newer browsers only. older browsers will apply the first declaration and ignore the second one, whereas newer browsers will apply the first one, then override it with the second one. feel free to create your own graphics for the assessment if you wish. example the following screenshot shows an example of what the finished design could look like: assessment or further help if you would like your work assessed, or are stuck and want to ask for help: put your work into an online shareable editor such as codepen, jsfiddle, or glitch. write a post asking for assessment and/or help at the mdn discourse forum learning category. your post should include: a descriptive title such as "assessment wanted for c...
Organizing your CSS - Learn web development
for css another way to organise css is to take advantage of some of the tooling that is available for front-end developers, which allows you to take a slightly more programmatic approach to writing css. there are a number of tools which we refer to as pre-processors and post-processors. a pre-processor runs over your raw files and turns them into a stylesheet, whereas a post-processor takes your finished stylesheet and does something to it — perhaps to optimize it in order that it will load faster. using any of these tools will require that your development environment can run the scripts that do the pre and post-processing. many code editors can do this for you, or you can install command line tools to help. the most popular pre-processor is sass. this is not a sass tutorial, so i will bri...
Test your skills: Overflow - Learn web development
the bottom of this page. task one the content is overflowing the box because it has a fixed height. keep the height but cause the box to have scrollbars only if there is enough text to cause an overflow. test by removing some of the text from the html, that if there is only a small amount of text that does not overflow, no scrollbar appears. try updating the live code below to recreate the finished example: for assessment or further work purposes, download the starting point for this task to work in your own editor or in an online editor. task two in this task an image is in the box, it is bigger than the dimensions of the box so overflows visibly. change it so that any image outside of the box is hidden. try updating the live code below to recreate the example as displayed in t...
Test your skills: sizing - Learn web development
use it to grow to that height, however, the content should not overflow if there is more content than fits in 100 pixels. test this box by removing the content from the html to make sure you still get a 100 pixel tall box even with no content. the second box should be fixed at 100 pixels tall, so that content will overflow if there is too much. try updating the live code below to recreate the finished example: for assessment or further work purposes, download the starting point for this task to work in your own editor or in an online editor. task two this task has a box, which contains another box. your task is to make the inner box 60% of the width of the outer box. the value of the box-sizing property is set to border-box, which means that the total width includes any padding and bo...
Test your skills: tables - Learn web development
on the tasks. if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page. task in the lesson we styled up a table in a rather garish manner. in this task we are going to style the same table, but using some good practices for table design as outlined in the external article web typography: designing tables to be read not looked at. our finished table will look like the image below. there are a number of ways that you can achieve this, but i suggest following similar patterns as used in the tutorial to do the following things. align headings and data for columns containing numbers right. align headings and data for columns containing text left. add a top and bottom border, plus a border above the footer. stripe every odd row of t...
Test your skills: values and units - Learn web development
ent formats, plus a final list item where you should make the background semi-opaque. the second list item should use rgb color. the third should use hsl color. the fourth should use rgb color but with the alpha channel set to .2. you can find conversions for the hex color at this link. you need to figure out how to use the values in css. try updating the live code below to recreate the finished example: for assessment or further work purposes, download the starting point for this task to work in your own editor or in an online editor. task two in this task you need to set the size of various items of text. the <h1> should be 50 pixels. the <h2> should be 2em. all <p> elements should be 16 pixels. a <p> element that is directly after an <h1> should be 120%. try updatin...
Flexbox - Learn web development
h will align all items at the start and end of the cross axis respectively. see align-items for the full details. you can override the align-items behavior for individual flex items by applying the align-self property to them. for example, try adding the following to your css: button:first-child { align-self: flex-end; } have a look at what effect this has, and remove it again when you've finished. justify-content controls where the flex items sit on the main axis. the default value is flex-start, which makes all the items sit at the start of the main axis. you can use flex-end to make them sit at the end. center is also a value for justify-content, and will make the flex items sit in the center of the main axis. the value we've used above, space-around, is useful — it distribut...
How CSS works - Learn web development
browsers will use the pixel version, ignoring the line about calc() as they don't understand it. new browsers will interpret the line using pixels, but then override it with the line using calc() as that line appears later in the cascade. .box { width: 500px; width: calc(100% - 50px); } we will look at many more ways to support varying browsers in later lessons. and finally you've nearly finished this module; we only have one more thing to do. in the next article you'll use your new knowledge to restyle an example, testing out some css in the process. previous overview: first steps next in this module what is css? getting started with css how css is structured how css works using your new knowledge ...
Using your new knowledge - Learn web development
t an assessment. a link to the example you want assessed or need help with, in an online shareable editor (as mentioned in step 1 above). this is a good practice to get into — it's very hard to help someone with a coding problem if you can't see their code. a link to the actual task or assessment page, so we can find the question you want help with. what's next? congratulations on finishing this first module. you should now have a good general understanding of css, and be able to understand much of what is happening in a stylesheet. in the next module, css building blocks, we will go on to look at a number of key areas in depth. previous overview: first steps in this module what is css? getting started with css how css is structured how css works using your new kno...
Fundamental text and font styling - Learn web development
the cat as he reeled back to clear whatever foreign matter may have nestled its way into his mighty throat. many a fat alley rat had met its demise while staring point blank down the cavernous barrel of this awesome prowling machine. truly a wonder of nature this urban predator — tommy the cat had many a story to tell. but it was a rare occasion such as this that he did.</p> you can find the finished example on github (see also the source code.) color the color property sets the color of the foreground content of the selected elements (which is usually the text, but can also include a couple of other things, such as an underline or overline placed on text using the text-decoration property). color can accept any css color unit, for example: p { color: red; } this will cause the parag...
Typesetting a community school homepage - Learn web development
the look and feel for the page. hints and tips you don't need to edit the html in any way for this exercise. you don't necessarily have to make the nav menu look like buttons, but it needs to be a bit taller so that it doesn't look silly on the side of the page; also remember that you need to make this one a vertical nav menu. example the following screenshot shows an example of what the finished design could look like: assessment or further help if you would like your work assessed, or are stuck and want to ask for help: put your work into an online shareable editor such as codepen, jsfiddle, or glitch. write a post asking for assessment and/or help at the mdn discourse forum learning category. your post should include: a descriptive title such as "assessment wanted for t...
How much does it cost to do something on the Web? - Learn web development
an be free (gimp, paint.net), moderately expensive (paintshop pro, less than $100), or several hundred dollars (adobe photoshop). you can use any of them, as they will have similar functionality, though some are so comprehensive you'll never use every feature. if at some point you need to exchange projects with other designers, you should find out what tools they're using. editors can all export finished projects to standard file formats, but each editor saves ongoing projects in its own specialized format. most of the images on the internet are copyrighted, so it is better to check the license of the file before you use it. sites like pixabay provide images under cc0 license, so you can use, edit and publish them even with modification for commercial use. media editors if you want to include...
How do you set up a local testing server? - Learn web development
e instructions to install it: go to python.org under the download section, click the link for python "3.xxx". at the bottom of the page, choose the windows x86 executable installer and download it. when it has downloaded, run it. on the first installer page, make sure you check the "add python 3.xxx to path" checkbox. click install, then click close when the installation has finished. open your command prompt (windows)/ terminal (macos/ linux). to check python is installed, enter the following command: python -v # or you might have the py command available, # in which case try py -v this should return a version number. if this is ok, navigate to the directory that your example is inside, using the cd command. # include the directory name to enter it, f...
How to structure a web form - Learn web development
uired">*</abbr></strong> <em>formatted as mm/dd/yyyy</em> </label> <input type="date" id="date" name="expiration"> </p> </section> the last section we'll add is a lot simpler, containing only a <button> of type submit, for submitting the form data. add this to the bottom of your form now: <p> <button type="submit">validate the payment</button> </p> you can see the finished form in action below (also find it on github — see our payment-form.html source and running live): test your skills! you've reached the end of this article, but can you remember the most important information? you can find a further test to verify that you've retained this information before you move on — see test your skills: form structure. summary you now have all the knowledge you...
Sending forms through JavaScript - Learn web development
if( file.dom.files[0] ) { reader.readasbinarystring( file.dom.files[0] ); } // if not, read the file once the user selects it. file.dom.addeventlistener( "change", function () { if( reader.readystate === filereader...
Styling web forms - Learn web development
e the transform property to help you with positioning your <legend>. however, when you position it with for example a transform: translatey();, it moves but leaves an ugly gap in the <fieldset> border, which is not easy to get rid of. a specific styling example let's look at a concrete example of how to style an html form. we will build a fancy-looking "postcard" contact form; see here for the finished version. if you want to follow along with this example, make a local copy of our postcard-start.html file, and follow the below instructions. the html the html is only slightly more involved than the example we used in the first article of this guide; it just has a few extra ids and a heading. <form> <h1>to: mozilla</h1> <div id="from"> <label for="name">from:</label> <input ty...
Your first form - Learn web development
ty 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 only allows plain text in its label whereas the <button> element allows full html content, allowing more complex, creative button content. basic form styling now that you have finished writing your form's html code, try saving it and looking at it in a browser. at the moment, you'll see that it looks rather ugly. note: if you don't think you've got the html code right, try comparing it with our finished example — see first-form.html (also see it live). forms are notoriously tricky to style nicely. it is beyond the scope of this article to teach you form styling in detai...
CSS basics - Learn web development
ment and an inline element. it will make more sense as you continue your study of css. you can find more information about different display values on mdn's display reference page. conclusion if you followed all the instructions in this article, you should have a page that looks similar to this one: (you can view our version here.) if you get stuck, you can always compare your work with our finished example code on github. in this exercise, we have just scratched the surface of css. to go further, see learning to style html using css. previous overview: getting started with the web next in this module installing basic software what will your website look like? dealing with files html basics css basics javascript basics publishing your website how the web works ...
HTML basics - Learn web development
bute name at first. if you are having trouble remembering it, remember that it stands for hypertext reference. add a link to your page now, if you haven't already done so. conclusion if you have followed all the instructions in this article, you should end up with a page that looks like the one below (you can also view it here): if you get stuck, you can always compare your work with our finished example code on github. here, we have only really scratched the surface of html. to find out more, go to our learning html topic. previous overview: getting started with the web next in this module installing basic software what will your website look like? dealing with files html basics css basics javascript basics publishing your website how the web works ...
JavaScript basics - Learn web development
etusername() again from the start. if it does have a value (if the above statement is not true), then store the value in localstorage and set it as the heading's text. conclusion if you have followed all the instructions in this article, you should end up with a page that looks something like the image below. you can also view our version. if you get stuck, you can compare your work with our finished example code on github. we have just scratched the surface of javascript. if you enjoyed playing, and wish to go further, take advantage of the resources listed below. ...
Publishing your website - Learn web development
this article explains how to get your simple sample code online with little effort. what are the options? publishing a website is a complex topic because there are many ways to go about it. this article doesn't attempt to document all the possible methods. instead, it explains the advantages and disadvantages of three approaches that are practical for beginners. then it steps through one method that can work right away for many readers. ...
Getting started with the Web - Learn web development
javascript is the programming language that you use to add interactive features to your website. some examples could be games, things that happen when buttons are pressed or data is entered in forms, dynamic styling effects, animation, and much more. javascript basics gives you an idea of what is possible with this exciting language, and how to get started. publishing your website once you have finished writing the code and organizing the files that make up your website, you need to put it all online so people can find it. publishing your sample code describes how to get your simple sample code online with minimum effort. how the web works when you access your favorite website, a lot of complicated things happen in the background that you may not know about. how the web works outlines what h...
Advanced text formatting - Learn web development
e a character shares a comment only with the audience for humorous or dramatic effect. this is usually a feeling, thought or piece of additional background information description lists use a different wrapper than the other list types — <dl>; in addition each term is wrapped in a <dt> (description term) element, and each description is wrapped in a <dd> (description definition) element. ...
Creating hyperlinks - Learn web development
. a navigation menu is usually just a list of links, so this is semantically ok. change each page name into a link to that page. copy the navigation menu across to each page. on each page, remove just the link to that same page — it's confusing and unnecessary for a page to include a link to itself. and, the lack of a link acts a good visual reminder of which page you are currently on. the finished example should look similar to the following page: note: if you get stuck, or aren't sure if you have got it right, you can check the navigation-menu-marked-up directory to see the correct answer. e-mail links it's possible to create links or buttons that, when clicked, open a new outgoing email message rather than linking to a resource or page. this is done using the <a> element and the...
Mozilla splash page - Learn web development
or ask for help — see the assessment or further help section at the bottom of this page. note: the example html file contains quite a lot of css, to style the page. you don't need to touch the css, just the html inside the <body> element — as long as you insert the correct markup, the styling will make it look correct. project brief in this assessment we are presenting you with a mostly-finished mozilla splash page, which aims to say something nice and interesting about what mozilla stands for, and provide some links to further resources. unfortunately, no images or video have been added yet — this is your job! you need to add some media to make the page look nice and make more sense. the following subsections detail what you need to do: preparing images using your favourite image ...
Assessment: Structuring planet data - Learn web development
ents inside the html page. project brief you are working at a school; currently your students are studying the planets of our solar system, and you want to provide them with an easy-to-follow set of data to look up facts and figures about the planets. an html data table would be ideal — you need to take the raw data you have available and turn it into a table, following the steps below. the finished table should look like this: you can also see the example live here (no looking at the source code — don't cheat!) steps to complete the following steps describe what you need to do to complete the table example. all the data you'll need is contained in the planets-data.txt file. if you have trouble visualising the data, look at the live example above, or try drawing a diagram. ope...
Choosing the right approach - Learn web development
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 JavaScript - Learn web development
t complex to set up and understand, and so modern browsers have implemented async functions and the await operator. the former allows standard functions to implicitly behave asynchronously with promises, whereas the latter can be used inside async functions to wait for promises before the function continues. this makes chaining promises simpler and easier to read. choosing the right approach to finish this module off, we'll consider the different coding techniques and features we've discussed throughout, looking at which ones you should use when, with recommendations and reminders of common pitfalls where appropriate. ...
Build your own function - Learn web development
from this: displaymessage('woo, this is a different message!'); to one of these: displaymessage('your inbox is almost full — delete some mails', 'warning'); displaymessage('brian: hi there, how are you today?','chat'); you can see how useful our (now not so) little function is becoming. note: if you have trouble getting the example to work, feel free to check your code against the finished version on github (see it running live also), or ask us for help. 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: functions. these tests require skills that are covered in the next article, so you might wan...
Introduction to events - Learn web development
hat resides in it — this might be a single element, set of elements, the html document loaded in the current tab, or the entire browser window. there are many different types of events that can occur. for example: the user selects a certain element or hovers the cursor over a certain element. the user chooses a key on the keyboard. the user resizes or closes the browser window. a web page finishes loading. a form is submitted. a video is played, paused, or finishes. an error occurs. you can gather from this (and from glancing at the mdn event reference) that there are a lot of events that can be responded to. each available event has an event handler, which is a block of code (usually a javascript function that you as a programmer create) that runs when the event fires. when such a...
Image gallery - Learn web development
h an onclick handler to each <img> inside the thumb-bar <div> so that when they are clicked, the corresponding image is displayed in the displayed-img <img> element. attach an onclick handler to the <button> so that when it is clicked, a darken effect is applied to the full-size image. when it is clicked again, the darken effect is removed again. to give you more of an idea, have a look at the finished example (no peeking at the source code!) steps to complete the following sections describe what you need to do. looping through the images we've already provided you with lines that store a reference to the thumb-bar <div> inside a constant called thumbbar, create a new <img> element, set its src attribute to a placeholder value xxx, and append this new <img> element inside thumbbar. you n...
Looping code - Learn web development
owever, in this example we are counting down after each iteration, not up, so you don't want i++ — how do you iterate downwards? note: if you start typing the loop (for example (while(i>=0)), the browser might stuck because you have not yet entered the end condition. so be careful with this. you can start writing your code in a comment to deal with this issue and remove the comment after you finish. if you make a mistake, you can always reset the example with the "reset" button. if you get really stuck, press "show solution" to see a solution. active learning <h2>live output</h2> <div class="output" style="height: 410px;overflow: auto;"> </div> <h2>editable code</h2> <p class="a11y-label">press esc to move focus away from the code area (tab inserts a tab character).</p> <textarea id=...
Making decisions in your code — conditionals - Learn web development
meters of black and white, meaning that we end up with background color of black and text color of white. if it returns false, we run the update() function with parameters of white and black, meaning that the site color are inverted. note: you can also find this example on github (see it running live on there also.) active learning: a simple calendar in this example, you are going to help us finish a simple calendar application. in the code you've got: a <select> element to allow the user to choose between different months. an onchange event handler to detect when the value selected in the <select> menu is changed. a function called createcalendar() that draws the calendar and displays the correct month in the <h1> element. we need you to write a conditional statement inside the onch...
Introduction to web APIs - Learn web development
oelement = document.queryselector('audio'); const playbtn = document.queryselector('button'); const volumeslider = document.queryselector('.volume'); const audiosource = audioctx.createmediaelementsource(audioelement); next up we include a couple of event handlers that serve to toggle between play and pause when the button is pressed and reset the display back to the beginning when the song has finished playing: // play/pause audio playbtn.addeventlistener('click', function() { // check if context is in suspended state (autoplay policy) if (audioctx.state === 'suspended') { audioctx.resume(); } // if track is stopped, play it if (this.getattribute('class') === 'paused') { audioelement.play(); this.setattribute('class', 'playing'); this.textco...
Silly story generator - Learn web development
ed into the "enter custom name" text field before the generate button is pressed. converts the default us weight and temperature quantities and units in the story into uk equivalents if the uk radio button is checked before the generate button is pressed. will generate another random silly story if you press the button again (and again...) the following screenshot shows an example of what the finished program should output: to give you more of an idea, have a look at the finished example (no peeking at the source code!) steps to complete the following sections describe what you need to do. basic setup: create a new file called main.js, in the same directory as your index.html file. apply the external javascript file to your html by inserting a <script> element into your html refere...
What is JavaScript? - Learn web development
formance issue, slowing down your site. async and defer there are actually two modern features we can use to bypass the problem of the blocking script — async and defer (which we saw above). let's look at the difference between these two. scripts loaded using the async attribute (see below) will download the script without blocking rendering the page and will execute it as soon as the script finishes downloading. you get no guarantee that scripts will run in any specific order, only that they will not stop the rest of the page from displaying. it is best to use async when the scripts in the page run independently from each other and depend on no other script on the page. for example, if you have the following script elements: <script async src="js/vendor/jquery.js"></script> <script asyn...
JavaScript object basics - Learn web development
the live version will give you a blank screen, but that's ok — again, open your devtools and try typing in the above commands to see the object structure. so what is going on here? well, an object is made up of multiple members, each of which has a name (e.g. name and age above), and a value (e.g. ['bob', 'smith'] and 32). each name/value pair must be separa...
Object prototypes - Learn web development
ed __proto__ property) and the prototype property on constructor functions. the former is the property on each instance, and the latter is the property on the constructor. that is, object.getprototypeof(new foobar()) refers to the same object as foobar.prototype. let's look at an example to make this a bit clearer. understanding prototype objects here we'll go back to the example in which we finished writing our person() constructor — load the example in your browser. you can use our oojs-class-further-exercises.html example (see also the source code), if you don't already have it from working through the last article. in this example, we have defined a constructor function, like so: function person(first, last, age, gender, interests) { // property and method definitions this.name...
Test your skills: JSON - Learn web development
her cat name should have an "and" before it, and a full stop after it. how do you make sure this can work, no matter how many cats are in the json? why are the para1.textcontent = motherinfo; and para2.textcontent = kitteninfo; lines inside the displaycatinfo() function, and not at the end of the script? this has something to do with async code. try updating the live code below to recreate the finished example: warning: to answer this question, you'll need to write your code into the live code window above. the example won't work locally, or in an environment like codepen or jsfiddle, because of something called cross-origin security. this basically means that you can't request a file from one origin using code on a different origin. in the live code editor above, both the javascript code...
Perceived performance - Learn web development
o be painted. it doesn't account for jitter, nor does it weight which content important to a user more highly, so it's not a perfect metric. these metrics have to do with initial load and render. it is also important to ensure the site feels fast once the user begins interacting with it. for this, time to interactive, is a good metric; it is the moment when the last long task of the load process finishes and the ui is available for user interaction with delay. ui lack or responsiveness and jank both harm perceived performance. even though a task may take a long time, though, there are ways to make it seem faster. there are several tips to improving perceived performance. improving perceived performance understanding networking, how the browser works, user perception of time, etc., can help y...
Routing in Ember - Learn web development
w want to have our todolist component show a filtered list, we'll want to pass an argument to the todolist component representing the "current list of todos", as shown here: {{#each @todos as |todo| }} and that's it for this tutorial! your app should now have fully working links in the footer that display the "index"/default, "active", and "completed" routes. summary congratulations! you've finished this tutorial! there is a lot more to be implemented before what we've covered here has parity with the original todomvc app, such as editing, deleting, and persisting todos across page reloads. to see our finished ember implementation, checkout the finished app folder in the repository for the code of this tutorial or see the live deployed version here. study the code to learn more about emb...
React resources - Learn web development
javascript console. but there's more we can do here. the react devtools utility allows you to inspect the internals of your react application directly in the browser. it adds a new panel to your browser's developer tools, and with it you can inspect the state and props of various components, and even edit state and props to make immediate changes to your application. this screenshot shows our finished application as it appears in react devtools: on the left, we see all of the components that make up our application, including some unique keys for the things that are rendered from arrays. on the right, we see the props and hooks that our app component utilizes. notice, too, that the form, filterbutton, and todo components are indented to the right – this indicates that app is their paren...
Beginning our React todo list - Learn web development
eact – an app that allows users to add, edit, and delete tasks they want to work on, and also mark tasks as complete without deleting them. this article will walk you through putting the basic app component structure and styling in place, ready for individual component definition and interactivity, which we'll add later. note: if you need to check your code against our version, you can find a finished version of the sample react app code in our todo-react repository. for a running live version, see https://mdn.github.io/todo-react-build/. prerequisites: familiarity with the core html, css, and javascript languages, knowledge of the terminal/command line. objective: to introduce our todo list case study, and get the basic app structure and styling in place. ...
Working with Svelte stores - Learn web development
in this article we will show another way to handle state management in svelte — stores. stores are global global data repositories that hold values. components can subscribe to stores and receive notifications when their values change. ...
Using Vue computed properties - Learn web development
their dependencies changes. in our case, this would only re-run when the todoitems array changes. to create a computed property, we need to add a computed property to our component object, much like the methods property we've used previously. adding a summary counter add the following code to your app component object, below the methods property. the list summary method will get the number of finished todoitems, and return a string reporting this. computed: { listsummary() { const numberfinisheditems = this.todoitems.filter(item =>item.done).length return `${numberfinisheditems} out of ${this.todoitems.length} items completed` } } now we can add {{listsummary}} directly to our template; we'll add this inside an <h2> element, just above our <ul>. we'll also add an id and an aria...
Creating our first Vue component - Learn web development
now it's time to dive deeper into vue, and create our own custom component — we'll start by creating a component to represent each item in the todo list. along the way, we'll learn about a few important concepts such as calling components inside other components, passing data to them via props, and saving data state. note: if you need to check your code against our version, you can find a finished version of the sample vue app code in our todo-vue repository. for a running live version, see https://mdn.github.io/todo-vue/dist/. prerequisites: familiarity with the core html, css, and javascript languages, knowledge of the terminal/command line. vue components are written as a combination of javascript objects that manage the app's data and an html-based template sy...
Focus management with Vue refs - Learn web development
he 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 in our todo-vue repository. for a running live version, see https://mdn.github.io/todo-vue/dist/. 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 todo list componentizing our react app react...
Implementing feature detection - Learn web development
<div> element as part of our test. in our conditional statement, we test that the flex and flex-flow properties exist in the browser. note how the javascript representations of those properties that are stored inside the htmlelement.style object use lower camel case, not hyphens, to separate the words. note: if you have trouble getting this to work, you can compare it to our css-feature-detect-finished.html code (see also the live version). when you save everything and try out your example, you should see the flexbox layout applied to the page if the browser supports modern flexbox, and the float layout if not. note: often such an approach is overkill for a minor feature detection problem — you can often get away with using multiple vendor prefixes and fallback properties, as described ...
Handling common HTML and CSS problems - Learn web development
and menu. in the search packages text field, type "lint" and press enter/return to search for linting-related packages. you should see a package called lint at the top of the list. install this first (using the install button), as other linters rely on it to work. after that, install the linter-csslint plugin for linting css, and the linter-tidy plugin for linting html. after the packages have finished installing, try loading up an html file and a css file: you'll see any issues highlighted with green (for warnings) and red (for errors) circles next to the line numbers, and a separate panel at the bottom provides line numbers, error messages, and sometimes suggested values or other fixes. other popular editors have similar linting packages available. for example, see: sublimelinter for...
Understanding client-side web development tools - Learn web development
client-side tooling can be intimidating, but this series of articles aims to illustrate the purpose of some of the most common client-side tool types, explain the tools you can chain together, how to install them using package managers, and control them using the command line. we finish up by providing a complete toolchain example showing you how to get productive. get started now, with our "client-side tooling overview" prerequisites you should really learn the basics of the core html, css, and javascript languages first before attempting to use the tools detailed here. 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 guides 1. client-side tooling overview in this...
Tools and testing - Learn web development
topic, which gives a useful overview of the general area. modules understanding client-side web development tools client-side tooling can be intimidating, but this series of articles aims to illustrate the purpose of some of the most common client-side tool types, explain the tools you can chain together, how to install them using package managers, and control them using the command line. we finish up by providing a complete toolchain example showing you how to get productive. understanding client-side javascript frameworks javascript frameworks are an essential part of modern front-end web development, providing developers with tried and tested tools for building scalable, interactive web applications. many modern companies use frameworks as a standard part of their tooling, so many fron...
Accessibility API cross-reference
ystems. 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. however, only about one third of the states and roles in sun's accessibility api's are the same as in msaa. to do fill out mac api column.(mac os x - carbon accessibility api and accessibility constants) finish aria column - add explanation of the term 'abstract role' fill out html column create aom column fill out xul column. fill out tagged pdf column (relevant documents from pdf association) add missing aria properties fill out events cross reference table use this info to expand mozilla's accessibility api coverage to include mac, so that we can start to freeze them talk about the fact that ...
Accessibility/LiveRegionDevGuide
rmance degradation. polite: a message should be derived from the event and added to the queue. assertive: the queue should be purged of 'polite' messages and the new message should be added to the queue. speak should not be interrupted. rude: the queue should be purged of 'polite' and 'assertive' messages and the new message should be added to the queue. current utterances should be allowed to finish but the 'rude' messages should be output as soon as possible. container-atomic the atomic property determines if a live region change should be presented on it's own or if an at should present the entire region. if atomic is set to "true", it means that the region must be presented as a whole while atomic="false" (default) indicates that the region can stand on it's own. the text offsets assoc...
Mozilla accessibility architecture
l is used to create a hash key to get the doc accessible from gglobaldocaccessiblecache. the dom node pointer is used to create the new hash key and add the nsiaccessnode* into the document accessible's maccessnodecache. the init() method is also virtual, and many accessibles override it to do their own special initialization. if they do, they must also call their parent class' init() method when finished. nsaccessnode::shutdown() shutdown() is used when the dom node for the given nsaccessnode/nsaccessible no longer exists. it can be called in a number of ways: in the destructor for nswindow: when the document is destroyed, its window also goes away. if there is a newly loading document, it has its own separate window which has already been created and rendered into. in fact, for about a seco...
Lightweight themes
lightweight themes are sometimes referred to as "background themes" or, (on addons.mozilla.org) as just "themes". how to create your own lightweight theme lightweight themes are made up of a "header" graphic image file, which skins the default firefox ui background. finished your design? you can submit it right now! creating a theme header image the header image is displayed as the background of the top of the browser window, nestling in behind the toolbars, address bar, search bar and the tab strip. it will be anchored to the top-right corner of the browser window. view a sample theme header here. image requirements dimensions should be 3000px wide × 200px high png or jpg file format image must be no larger than 300 kb in file size tips subtle, soft contrast images and...
Adding a new CSS property
tomated and make the code smaller.) animation if the existing animation behaviors in nsstyleanimation aren't sufficient for how this new property is interpolated (as its specification should describe), then you'll need to implement a new behavior type in nsstyleanimation and reference it from nscssproplist.h. this should probably be in a separate patch from the basic addition of the property. finishing up then you'll need to rebuild and run the mochitests in layout/style (./mach mochitest -f plain layout/style/). if you've done everything right, they should pass; if they don't, you need to fix something. then you should get review on the work you've done so far and move on to implementing whatever the property does (which should be in a separate patch or patches). ...
Creating JavaScript callbacks in components
hen predefined events occur. here is a very simple example of the observer pattern: [scriptable, uuid(...)] interface stringparserobserver { void onword(string word); }; [scriptable, uuid(...)] interface stringparser { void parse(string data); void addobserver(stringparserobserver observer); }; in this example, the stringparser will call the stringparserobserver.onword method whenever it finishes parsing a word found in the raw string data. here is an example of how to use the callback system: var wordhandler = { onword : function(word) { alert(word); } }; var stringparser = /* get a reference to the parser somehow */ stringparser.addobserver(wordhandler); stringparser.parse("pay no attention to the man behind the curtain"); you can find examples of this pattern all over the m...
Creating Sandboxed HTTP Connections
ve mentioned listener is a nsistreamlistener, which gets notified about events such as http redirects and data availability. onstartrequest - gets called when a new request is initiated. ondataavailable - new data is available. since this is a stream, it could be called multiple times (depending on the size of the returned data, networking conditions, etc). onstoprequest - the request has finished. onchannelredirect - when a redirect happens, a new nsichannel is created, and both the old and new ones are passed in as arguments. since nsistreamlistener does not cover cookies, the current channel being used will need to be stored as a global, since another listener will be used for cookie notifications (covered in the next section). it is usually best to use a javascript wrapper that i...
Debugging OpenGL
ebug 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. this makes debugging crashes caused by an opengl call much easier, since the stack you see will match where the call was issued, rather than some time in the future when it happens to run and crash. if an opengl error occurred when executing the call, an error message is output. note: you ...
Debugging on Mac OS X
aking this step. creating an xcode project if you try to create a new xcode project in an existing directory then xcode will delete its existing contents (xcode will warn you beforehand). to work around that, the steps below have you initialize the project outside the mozilla source tree, close the project, copy the .xcodeproj project "file" into the source tree, and then reopen the project to finish setting it up. note also that since xcode 7.3.1 it doesn't seem to be possible to have the xcode project live outside the source tree. if you try to do that then xcode will simply copy the source files under the project directory rather than link to them (still the case in xcode 10?) which breaks debugging and the possibility to modify-rebuild-relaunch from inside xcode. these steps were last ...
HTTP logging
mporary directory. you can type "%temp%" directly into the windows explorer location bar to get there quickly. advanced techniques you can adjust some of the settings listed above to change what http information get logged. limiting the size of the logged data by default there is no limit to the size of log file(s), and they capture the logging throughout the time firefox runs, from start to finish. these files can get quite large (gigabytes)! so we have added a 'rotate:size_in_mb' option to moz_log (we use it in the examples above). if you are using firefox >= 51, setting this option saves only the last n megabytes of logging data, which helps keep them manageable in size. (unknown modules are ignored, so it's ok to use 'rotate' in your environment even if you're running firefox <= 50:...
Error codes returned by Mozilla APIs
001e) ns_error_xslt_var_already_set (0x8060001f) miscellaneous errors other errors that can occur. ...
Storage access policy: Block cookies from trackers
lclassifier.trackingannotationtable.testentries". if the preference already exists, edit the preference value. if the preference does not exist, click "string" and then "+" to create a new preference. for the preference value enter comma separated origins that you’d like to have classified as trackers. e.g. "example.net,example.org". warning: be sure to remove these entries after you have finished testing. faq this cookie policy has the potential to lead to site breakage, but has been designed to allow common third-party integrations to continue to work while preventing cross-site tracking. in this section we describe the functionality you can expect in different integration scenarios. will this storage access policy block ads from displaying on my website? no — this feature only ...
mozbrowserloadend
non-standard this feature is not on a current w3c standards track, but it is supported on the firefox os platform. although implementations may change in the future and it is not supported widely across browsers, it is suitable for use in code dedicated to firefox os apps. the mozbrowserloadend event is fired when the browser <iframe> has finished loading all its assets, or has failed to load. this can be used when the embedder wants to stop spinning a loading indicator, or update the ui in some other way to indicate loading is complete. general info specification non standard interface customevent bubbles yes cancelable yes target <iframe> default action none properties property type description target read only e...
Browser API
iframe> content (see htmliframeelement search methods.) mozbrowserfirstpaint sent when the <iframe> paints content for the first time (this doesn't include the initial paint from about:blank.) mozbrowsericonchange sent when a new icon (e.g. <link rel="icon"> or <link rel="apple-touch-icon">) is available in the browser <iframe>'s content. mozbrowserloadend sent when the browser <iframe> has finished loading all its assets. mozbrowserloadstart sent when the browser <iframe> starts to load a new page. mozbrowserlocationchange sent when a browser <iframe>'s location changes. mozbrowsermanifestchange sent when a the path to the app manifest changes, in the case of a browser <iframe> with an open web app embedded in it. mozbrowsermetachange sent when a <meta> elelment is added to, remov...
HTML parser threading
ve loads are used. (speculative loads are discussed later.) the third tokenizer/tree builder pair is initialized from the state of the main document.write() tokenizer/tree builder pair but can get into an inconsistent state if document.write() is invoked re-entrantly. this is ok, because the tree ops aren't used and it's mostly harmless if the speculative loads are wrong. after an external script finishes executing, it dispatches an event to reflush the tree op executor. the reflush causes a call to nshtml5parser::parseuntilblocked(). parseuntilblocked() parses data left by document.write() in the linked list of buffers, because the parser was blocked. this might cause more script execution tree ops to be generated and executed and document.write() to be called more times. when parseuntilblocked...
HTTP Cache
otherwise: state = writing opener is removed from the fifo and remembered as the current 'writer' oncacheentryavailable with anew = true and this entry is invoked (on the caller thread) for the writer state == ready: oncacheentrycheck with the entry is invoked on the first opener in fifo - on the caller thread if demanded result == recheck_after_write_finished: opener is left in the fifo with a flag recheckafterwrite such openers are skipped until the output stream on the entry is closed, then oncacheentrycheck is re-invoked on them note: here is a potential for endless looping when recheck_after_write_finished is abused result == entry_needs_revalidation: state = revalidating, this prevents invocation of any...
IME handling guide
ome changes caused by the 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 ...
Extending a Protocol
arv.throw(ns_error_unexpected); return nullptr; } auto windowglobalchild = mwindow->getwindowglobalchild(); // let's get us a child! mechochild = windowglobalchild->allocpechochild(); // let's make sure it's initialized and ready to send messages. windowglobalchild->sendpechoconstructor(mechochild); } return mechochild; } and finally... ...
IPDL Tutorial
d. the messaging semantics applies in the same way to both directions. so, for example, in synchronous semantics from the child to the parent, the child will block until the parent receives the message and the response arrives, and in asynchronous semantics from the parent to the child the parent will not block. when creating a plugin instance, the browser should block until instance creation is finished, and needs some information returned from the plugin: sync protocol pplugininstance { child: sync init() returns (bool windowless, bool ok); }; we added two new keywords to the plugin protocol, sync and returns. sync marks a message as being sent synchronously. the returns keyword marks the beginning of the list of values that are returned in the reply to the message. async message retu...
Internationalized Domain Names (IDN) Support in Mozilla Browsers
l change the default from puncycode to race. next create another new preference item using the right-mouse click menu new > boolean. the name of the preference is: network.idn_testbed. the value should be "true". now access idn sites under the .com and .net top domains. you should succeed in reaching the sample sites. don't forget to set the value of these preferences to "default" once you are finished with testing! caveats and conclusions netscape 7.1/mozilla 1.4 has solid support for internationalized domain names and is the first browser with built-in support for new rfc's for idn established by ietf. this means that there is no longer any need to use a plug-in to process non-ascii domain names. netscape/mozilla's support for idn is not without some bugs. one notable bug is that non-as...
AddonManager
addons passed back from the asynchronous request constants addoninstall states constant description state_available an install that is waiting to be started. state_downloading an install that is in the process of being downloaded. state_checking an install that is checking for updated information. state_downloaded an install that has finished downloading and is ready to install. state_download_failed an install that failed to download. state_installing an install that is in the process of being installed. state_installed an install that has successfully been installed. state_install_failed an install that has failed to install. state_cancelled an install that has been cance...
CustomizableUI.jsm
ise, for the duration of the firefox session, customization state is never saved. typically, you would do this using a try...finally block wrapped around your insertion code. endbatchupdate() end a batch update. see the documentation for beginbatchupdate above. state is not saved if we believe it is identical to the last known saved state. state is only ever saved when all batch updates have finished (that is, there has been 1 endbatchupdate call for each beginbatchupdate call). if any of the endbatchupdate calls pass aforcedirty=true, we will flush to the prefs file. parameters aforcedirty force customizableui to flush to the prefs file when all batch updates have finished. createwidget() create a widget. to create a widget, you should pass an object with its desired properties. f...
DownloadTarget
r downloads of multiple files, such as downloading a web page and its required media to disk, the meaning of this property is undefined. it currently indicates the size of the main file (such as the html document) rather than the sum of all of the files' sizes, but you must not rely upon this behavior, as it is subject to change. this is a dynamic property, which is updated when the download finishes or whenever the download.refresh() method is called. you can use this value from the front-end to reduce file i/o that would be required to check the file directly. methods refresh() updates the state of a finished, failed, or canceled download based on the current state as indicated by the file system. if the download is in progress or has been finalized, this method does nothing ...
Application Translation with Mercurial
iff = -p -u 8 qnew = -u [diff] git = 1 showfunc = 1 unified = 8 [extensions] hgext.mq = progress = [hooks] put in your name and email address which later will be public on the internet after your translation patch got accepted and uploaded. save the file and close it. enabling mercurial queues (revertable patches) some 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 ...
Bootstrapping a new locale
po import existing data? $ cd /path/to/existing/hg/repo/ $ hg push http://bitbucket.org/mozillal10n/ab-cd/ prefer ssh? $ hg clone ssh://hg@bitbucket.org/mozillal10n/ab-cd/ $ hg push ssh://hg@bitbucket.org/mozillal10n/ab-cd/ as you begin to move through your translations, you should "commit" the changes locally and "push" your work to this experimental respository. for instance, if you have finished translating all the .dtd and .property files in your ~/ab-cd/browser/ directory, then you should $ cd ~/ab-cd/ $ hg status $ hg commit -m "translated browser/" $ hg push http://bitbucket.org/mozillal10n/ab-cd/ note that due to the distributed nature of hg, hg commit saves the changes locally, i.e. in the hg repository on your computer. you can see the history of commits with hg log. after do...
Mozilla Content Localized in Your Language
where strings are truncated. ellipsis should only be used at high level of ui pages, but not be on the final page (after a series of click-through) where detailed instruction is given. ellipsis should not be used as a way to solve truncation issue. focus on making the ui short and precise. the sequence of the sentence structure in another language may not translate well, when a sentence is half finished as such. add fluency :: spelling, punctuation, capitalization, diacritics, typography, unpaired brackets or quote marks, whitespace. include a note to look for, reference, and adhere to a national standard for the language, where possible. add style :: register, variants/slang, awkward, company style (branding guidelines), inconsistent style, third-party style, unidiomatic (steps to d...
Localizing with Koala
e it's time to put these files under mercurial's version control system. this will allow you to track changes, export them to remote repositories (first on bitbucket, later on hg.mozilla.org) and revert files to earlier versions in case of errors. version control systems add a lot of transparency to your work and allow others to get involved easily, so it's best to commit often (e.g. after you finish translating every file, or even more frequently). koala supports mercurial and allows you to add and commit files automatically from komodo. for the purposes of this tutorial, we will switch to the command line every now and then to see what koala does behind the scenes. normally though, you don't have to use the command line to commit your work. assuming that your locale files are in c:\mozilla\...
Initial setup
manager or following these links. ...
Localization quick start guide
bout the variety of projects you can contribute to and the tools used to localize them. when we get to specific examples, we'll take them from the firefox project, as it is the most widely localized project within mozilla. as you near the end of this guide, you should be able to make a change to firefox in your local setting and then see that change in the firefox interface. in closing, when you finish this guide, you will have all the tools necessary to start contributing! remember, this guide will instruct you on the technical aspects of mozilla l10n only. visit the l10n process page to learn about the whole process. initial setup tech prep work before localizing. translation phase l10n tools tutorials for translation. qa phase l10n testing tutorials. release phase steps to shipping ...
Localization technical reviews
t column to the right. as your work is approved, you'll see a green circle in the furthest column to the right as well as a measure of percentage in the middle column. first round approved! once your work is entirely approved, go out and celebrate! you've accomplished a massive undertaking and you deserve to be rewarded! go grab a drink with friends and enjoy your latest success! after you've finished celebrating your first approved release, it's time to start planning for the next one! when you update your localization for the next release, you'll need to put it through a different form of qa review called a sign-off review. visit the wiki page for sign-off reviews to learn what's involved when maintaining a localized mozilla product. ...
What every Mozilla translator should know
n successful. if so, change the state of the bug to verified and write verified1.8.xxx in the keyword field tinderbox in tinderbox you can see the result of the build process. once you have made some changes in mercurial, as soon as the next build is done you can check the tinderbox and see if something was wrong. l10n tinderbox when the color is green, it means that the build process has finished with no errors. in this case the resultant installable file will be available in the mozilla ftp servers: firefox nightly builds thunderbird nightly builds qa (quality assurance) in order to assure the quality of a build we should make some tests using http://litmus.mozilla.org ...
Mozilla DOM Hacking Guide
ers interface_list is filled with the addresses of the iid's of all the interfaces passed as arguments to the macro. in our window example, the interfaces are nsidomwindow, nsidomjswindow, nsidomeventreciever, nsidomeventtarget, nsidomviewcss, and nsidomabstractview. please see section 1.2 on interface flattening for an explanation of the use of these interfaces. the initialization for a class is finished by the dom_classinfo_map_end macro. #define dom_classinfo_map_end nsnull }; d.minterfaces = interface_list; } the interface_list array is terminated by a null pointer. the line d.minterfaces = interface_list assigns to minterfaces the address of the first element of the interface_list array, which is itself a pointer. minterfaces is thus correctly a pointer to a pointer to an object of type ...
GC and CC logs
only log worker ccs. the default value is all, which will log all ccs. to get cycle collector logs on try server, set moz_cc_log_directory to moz_upload_dir, then set the other variables appropriately to generate cc logs. the way to set environment variables depends on the test harness, or you can modify the code in nscyclecollector to set that directly. to find the cc logs once the try run has finished, click on the particular job, then click on "job details" in the bottom pane in treeherder, and you should see download links. to set the environment variable, find the buildbrowserenv method in the python file for the test suite you are interested in, and add something like this code to the file: browserenv["moz_cc_log_directory"] = os.environ["moz_upload_dir"] browserenv["moz_cc_log_shutdow...
Profiling with the Firefox Profiler
ected element. 2. call tree the call tree shows the samples organized by 'running time' which will show the data by wall clock time. there are lighter grey names to the right of tree elements that indicate where the code comes from. be aware that elements can be from javascript, gecko, or system libraries. note that if some functions are not yet named properly, symbolication may not yet be finished. tip: you can right-click on a function name to get an option to copy its name to the clipboard. a significant portion of time can be spent in idle, blocking calls like waiting for events. this is ideal for a responsive application to be ready to service incoming events. there are os-specific waiting functions like ntwaitformultipleobjects seen in the example above taken on windows or mach_...
tools/power/rapl
ower is the sum of the package power and the ram power. the package estimate is divided into three parts: cores, gpu, and "other". "other" is computed as the package power minus the cores power and gpu power. if the processor does not support gpu or ram estimates then " n/a " will be printed in the relevant column instead of a number, and it will contribute zero to the total. ...
Nonblocking IO In NSPR
the blocking io model encourages the use of multiple threads as a programming model. a thread is typically created to attend to one of the simultaneous i/o operations that may potentially block. in the nonblocking io model, a file descriptor may be marked as nonblocking. an io function on a nonblocking file descriptor either succeeds immediately or fails immediately with <tt>pr_would_block_error</tt>. ...
Named Shared Memory
already exist, or opens a connection with the existing shared memory segment if it already exists. pr_attachsharedmemory should be called following pr_opensharedmemory to map the memory segment to an address in the application's address space. pr_attachsharedmemory may also be called to remap a shared memory segment after detaching the same prsharedmemory object. be sure to detach it when you're finished. pr_detachsharedmemory should be called to unmap the shared memory segment from the application's address space. pr_closesharedmemory should be called when no further use of the prsharedmemory object is required within a process. following a call to pr_closesharedmemory, the prsharedmemory object is invalid and cannot be reused. pr_deletesharedmemory should be called before process terminati...
PRThreadState
er thread joins it. the join process permits strict synchronization of thread termination and therefore promotes effective resource management. if a thread is created as an unjoinable (also called detached) thread, it terminates and cleans up after itself after returning from its root function. this results in some ambiguity after the thread's root function has returned and before the thread has finished terminating itself. ...
PR_CWait
ling thread was not the thread that held the monitor's mutex. description using the value specified in the address parameter to find a monitor in the monitor cache, pr_cwait waits for a notification that the monitor's state has changed. while the thread is waiting, it exits the monitor (just as if it had called pr_cexitmonitor as many times as it had called pr_centermonitor). when the wait has finished, the thread regains control of the monitor's lock with the same entry count as before the wait began. the thread waiting on the monitor resumes execution when the monitor is notified (assuming the thread is the next in line to receive the notify) or when the interval specified in the timeout parameter has been exceeded. when the thread resumes execution, it is the caller's responsibility to te...
Threads
ent request and remains a valid, independent execution entity until it returns from its root function or the process abnormally terminates. threads are critical resources and therefore require some management. to synchronize the termination of a thread, you can join it with another thread (see pr_jointhread). joining a thread provides definitive proof that the target thread has terminated and has finished with both the resources to which the thread has access and the resources of the thread itself. for an overview of the nspr threading model and sample code that illustrates its use, see introduction to nspr. for api reference information related to thread synchronization, see locks and condition variables. threading types and constants prthread prthreadtype prthreadscope prthreadstate ...
Certificate functions
ertextension mxr 3.4 and later cert_findcertissuer mxr 3.3 and later cert_findkeyusageextension mxr 3.4 and later cert_findsmimeprofile mxr 3.2 and later cert_findsubjectkeyidextension mxr 3.7 and later cert_findusercertbyusage mxr 3.4 and later cert_findusercertsbyusage mxr 3.4 and later cert_finishcertificaterequestattributes mxr 3.10 and later cert_finishextensions mxr 3.5 and later cert_formatname mxr 3.2 and later cert_freedistnames mxr 3.2 and later cert_freenicknames mxr 3.2 and later cert_getavatag mxr 3.2 and later cert_getcertchainfromcert mxr 3.4 and later cert_getcertemailaddre...
HTTP delegation
eady) and the request path. in our example the path is "/cgi-bin/ocsp-responder". (when issueing get requests, the "?query-string=data" portion should already be appended to the request path) after creation, nss might call functions to provide additional details of the http request (e.g. sec_httprequest_setpostdatafcn). the application is expected to collect the details for later use. once nss is finished providing all details, it will request to initiate the actual network communication (sec_httprequest_trysendandreceivefcn). the application should try to reuse existing network connections associated with the server session object. once the http response has been obtained from the http server, the function will provide the results in its "out parameters". please read the source code documentati...
HTTP delegation
ready) and the request path. in our example the path is "/cgi-bin/ocsp-responder". (when issuing get requests, the "?query-string=data" portion should already be appended to the request path) after creation, nss might call functions to provide additional details of the http request (e.g. sec_httprequest_setpostdatafcn). the application is expected to collect the details for later use. once nss is finished providing all details, it will request to initiate the actual network communication (sec_httprequest_trysendandreceivefcn). the application should try to reuse existing network connections associated with the server session object. once the http response has been obtained from the http server, the function will provide the results in its "out parameters". please read the source code documentati...
NSS Memory allocation
in the free list that are large enough to satisfy the request. there are two consequences of the use of plarenapools that affect leak analysis. they are: 1. at the end of execution of a program, all the arenas in the free list will appear to have been leaked. this makes it difficult to tell arenas that are truly leaked from those that are merely in the free list. there is a function named pl_arenafinish that really frees all the arenas on the free list. see the prototype at http://mxr.mozilla.org/nspr/source/n.../ds/plarenas.h a program should call that function at the very end, after having shutdown nss and nspr, to really free the contents of the free list. after that function returns, any arenas that still appear to be leaked have truly been leaked, and are not merely on the free list. 2. lea...
NSS 3.15.2 release notes
g 663313 - md2, md4, and md5 signatures are no longer accepted for ocsp or crls, consistent with their handling for general certificate signatures. bug 884178 - add pk11_cipherfinal macro bugs fixed in nss 3.15.2 bug 734007 - sizeof() used incorrectly bug 900971 - nssutil_readsecmoddb() leaks memory bug 681839 - allow ssl_handshakenegotiatedextension to be called before the handshake is finished. bug 848384 - deprecate the ssl cipher policy code, as it's no longer relevant. it is no longer necessary to call nss_setdomesticpolicy because all cipher suites are now allowed by default. a complete list of all bugs resolved in this release can be obtained at https://bugzilla.mozilla.org/buglist.cgi?resolution=fixed&classification=components&query_format=advanced&target_milestone=3.15.2&pr...
NSS 3.21 release notes
ckm_tls12_master_key_derive - derives tls 1.2 master secret ckm_tls12_key_and_mac_derive - derives tls 1.2 traffic key and iv ckm_tls12_master_key_derive_dh - derives tls 1.2 master secret for dh (and ecdh) cipher suites ckm_tls12_key_safe_derive and ckm_tls_kdf are identifiers for additional pkcs#12 mechanisms for tls 1.2 that are currently unused in nss. ...
NSS 3.45 release notes
ilt on android bug 1528174 - chacha20poly1305 should no longer modify output length on failure bug 1549382 - don't leak in pkcs#11 modules if c_getslotinfo() returns error bug 1551041 - fix builds using gcc < 4.3 on big-endian architectures bug 1554659 - add versioning to openbsd builds to fix link time errors using nss bug 1553443 - send session ticket only after handshake is marked as finished bug 1550708 - fix gyp scripts on solaris sparc so that libfreebl_64fpu_3.so builds bug 1554336 - optimize away unneeded loop in mpi.c bug 1559906 - fipstest: use ckm_tls12_master_key_derive instead of vendor specific mechanism bug 1558126 - tls_aes_256_gcm_sha384 should be marked as fips compatible bug 1555207 - helloretryrequestcallback return code for rejecting 0-rtt bug 1556591 - elimi...
NSS 3.46 release notes
hangs on windows x64 when building nss since changeset 9162c654d06915f0f15948fbf67d4103a229226f bug 1564875 - improve rebuilding with build.sh bug 1565243 - support tc_owner without email address in nss taskgraph bug 1563778 - inc...
Enc Dec MAC Output Public Key as CSR
secfailure; goto cleanup; } arena = port_newarena(der_default_chunksize); if (!arena) { fprintf(stderr, "out of memory"); rv = secfailure; goto cleanup; } exthandle = cert_startcertificaterequestattributes(cr); if (exthandle == null) { port_freearena (arena, pr_false); rv = secfailure; goto cleanup; } cert_finishextensions(exthandle); cert_finishcertificaterequestattributes(cr); /* der encode the request */ encoding = sec_asn1encodeitem(arena, null, cr, sec_asn1_get(cert_certificaterequesttemplate)); if (encoding == null) { pr_fprintf(pr_stderr, "der encoding of request failed\n"); rv = secfailure; goto cleanup; } /* sign ...
NSS Sample Code Utilities_1
press enter to continue: "); while ((c = getc(stdin)) != '\n' && c != eof) ; if (c == eof) rv = secfailure; fprintf(stderr, "\n"); /* set back termio the way it was */ tio.c_lflag = orig_lflag; tio.c_cc[vmin] = orig_cc_min; tio.c_cc[vtime] = orig_cc_time; tcsetattr(fd, tcsaflush, &tio); return rv; } /* * seedfromnoisefile */ secstatus se...
Utilities for nss samples
press enter to continue: "); while ((c = getc(stdin)) != '\n' && c != eof) ; if (c == eof) rv = secfailure; fprintf(stderr, "\n"); /* set back termio the way it was */ tio.c_lflag = orig_lflag; tio.c_cc[vmin] = orig_cc_min; tio.c_cc[vtime] = orig_cc_time; tcsetattr(fd, tcsaflush, &tio); return rv; } /* * seedfromnoisefile */ secstatus se...
NSS release notes template
or network security services (nss) 3.xx.y is a patch release for nss 3.xx. the bug fixes in nss 3.xx.y are described in the "bugs fixed" section below. distribution information the hg tag is nss_3_xx_rtm. nss 3.xx requires nspr 4.xx or newer. nss 3.xx source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_xx_rtm/src/ (make a link) new in nss 3.xx new functionality either: no new functionality is introduced in this release. this is a patch release to fix ... or: ... ...
PKCS11 Implement
and cfk_user_pin_initialized = false. c_setpin called only in the key generation case, as noted in this document under c_gettokeninfo, when cfk_login_required = true and cfk_user_pin_initialized = false. session management c_opensession the nss calls c_opensession whenever it initializes a token and keeps the session open as long as possible. the nss almost never closes a session after it finishes doing something with a token. it uses a single session for all single-part rsa operations such as logging in, logging out, signing, verifying, generating keys, wrapping keys, and so on. the nss opens a separate session for each part of a multipart encryption (bulk encryption). if it runs out of sessions, it uses the initial session for saves and restores. c_closesession the nss calls c_close...
PKCS 12 functions
sec_pkcs12addcertandkey mxr 3.2 and later sec_pkcs12addpasswordintegrity mxr 3.2 and later sec_pkcs12createexportcontext mxr 3.2 and later sec_pkcs12createpasswordprivsafe mxr 3.2 and later sec_pkcs12createunencryptedsafe mxr 3.2 and later sec_pkcs12decoderfinish mxr 3.2 and later sec_pkcs12decodergetcerts mxr 3.4 and later sec_pkcs12decoderimportbags mxr 3.2 and later sec_pkcs12decoderiterateinit mxr 3.10 and later sec_pkcs12decoderiteratenext mxr 3.10 and later sec_pkcs12decodersettargettokencas mxr 3.8 ...
FC_DecryptDigestUpdate
pted data in bytes. ppart [in] pointer to the location which receives the recovered data part or null. pulpartlen [in] pointer to the length of the recovered part buffer. description fc_decryptdigestupdate continues a multi-part decrypt and digest operation. after calling both fc_decryptinit and fc_digestinit to set up the operations this function may be called multiple times. the operation is finished by calls to fc_digestfinal and fc_decryptfinal. a user must log into the token (to assume the nss user role) before calling fc_decryptdigestupdate. return value examples see also nsc_decryptdigestupdate ...
FC_DecryptFinal
syntax ck_rv fc_decryptfinal( ck_session_handle hsession, ck_byte_ptr plastpart, ck_ulong_ptr puslastpartlen ); parameters hsession [in] session handle. plastpart [out] pointer to the location where the last block of recovered data, if any, is to be stored. puslastpartlen [in,out] pointer to location where the number of bytes of recovered data is to be stored. description fc_decryptfinal returns the last block of data of a multi-part decryption operation. a user must log into the token (to assume the nss user role) before calling fc_decryptfinal. ...
FC_DecryptVerifyUpdate
ta [in] pointer to the location which receives the recovered data part or null. puldatalen [in] pointer to the length of the recovered part buffer. description fc_decryptverifyupdate continues a multi-part decryption and and signature verification operation. after calling both fc_decryptinit and fc_verifyinit to set up the operations this function may be called multiple times. the operation is finished by calls to fc_decryptfinal and fc_verifyfinal. a user must log into the token (to assume the nss user role) before calling fc_decryptverifyupdate. return value examples see also nsc_decryptverifyupdate ...
FC_DigestEncryptUpdate
dpart [in] pointer to the location which receives the digested and encrypted part or null. pulencryptedpartlen [in] pointer to the length of the encrypted part buffer. description fc_digestencryptupdate continues a multi-part digest and encryption operation. after calling both fc_digestinit and fc_encryptinit to set up the operations this function may be called multiple times. the operation is finished by calls to fc_digestfinal and fc_encryptfinal in that order. a user must log into the token (to assume the nss user role) before calling fc_digestencryptupdate. return value examples see also nsc_digestencryptupdate ...
FC_EncryptFinal
syntax ck_rv fc_encryptfinal( ck_session_handle hsession, ck_byte_ptr plastencryptedpart, ck_ulong_ptr puslastencryptedpartlen ); parameters hsession [in] session handle. plastencryptedpart [out] pointer to the location that receives the last encrypted data part, if any puslastencryptedpartlen [in,out] pointer to location where the number of bytes of the last encrypted data part is to be stored. description fc_encryptfinal returns the last block of data of a multi-part encryption operation. a user must log into the token (to assume the nss user role) before calling fc_encryptfinal. ...
FC_SignEncryptUpdate
art [in] pointer to the location which receives the signed and encrypted data part or null. pulencryptedpartlen [in] pointer to the length of the encrypted part buffer. description fc_signencryptupdate continues a multi-part signature and encryption operation. after calling both fc_signinit and fc_encryptinit to set up the operations this function may be called multiple times. the operation is finished by calls to fc_signfinal and fc_encryptfinal. a user must log into the token (to assume the nss user role) before calling fc_signencryptupdate. return value examples see also nsc_signencryptupdate ...
NSS tools : certutil
hardware or software token. -m modify a certificate's trust attributes using the values of the -t argument. -n create new certificate and key databases. -o print the certificate chain. -r create a certificate request file that can be submitted to a certificate authority (ca) for processing into a finished certificate. output defaults to standard out unless you use -o output-file argument. use the -a argument to specify ascii output. -s create an individual certificate and add it to a certificate database. -t reset the key database or token. -u list all available modules or print a single named module. ...
NSS tools : modutil
ver's root directory. the %temp% directory is created at the beginning of the installation and destroyed at the end. the purpose of %temp% is to hold executable files (such as setup programs) or files that are used by these programs. files destined for the temporary directory are guaranteed to be in place before any executable file is run; they are not deleted until all executable files have finished. absolutepath specifies the destination directory of the file as an absolute path. executable specifies that the file is to be executed during the course of the installation. typically, this string is used for a setup program provided by a module vendor, such as a self-extracting setup executable. more than one file can be specified as executable, in which case the files are run in the o...
NSS reference
exchange data such as private keys and certificates between two parties. sec_pkcs12createexportcontext sec_pkcs12createpasswordprivsafe sec_pkcs12createunencryptedsafe sec_pkcs12addcertandkey sec_pkcs12addpasswordintegrity sec_pkcs12enablecipher sec_pkcs12encode sec_pkcs12destroyexportcontext sec_pkcs12decoderstart sec_pkcs12decoderimportbags sec_pkcs12decoderupdate sec_pkcs12decoderfinish sec_pkcs12decodervalidatebags sec_pkcs12decoderverify sec_pkcs12decodergetcerts sec_pkcs12decodersettargettokencas sec_pkcs12decoderiterateinit sec_pkcs12decoderiteratenext sec_pkcs12isencryptionallowed sec_pkcs12setpreferredcipher nspr functions a small number of nspr functions are required for using the certificate verification and ssl functions in nss. these functions are listed in...
gtstd.html
e client" -a -i client_db/client.crt -t ",," display the contents of the client's certificate databases. >certutil -l -d client_db the trust flag settings "u,u,u" indicate that the client's databases contain the private key for this certificate. this is necessary for the ssl client to be able to authenticate to the server. verifying the server and client certificates when you have finished setting up the server and client certificate databases, verify that the client and server certificates are valid, as follows: >certutil -v -d server_db -u v -n myco.mcom.org certutil: certificate is valid >certutil -v -d client_db -u c -n "joe client" certutil: certificate is valid building nss programs on unix, use the gnu utility gmake to run the makefile. on windows nt, use the nma...
TLS Cipher Suite Discovery
keyspace; pruint16 effectivekeybits; /* mac info */ const char * macalgorithmname; sslmacalgorithm macalgorithm; pruint16 macbits; pruintn isfips : 1; pruintn isexportable : 1; pruintn nonstandard : 1; pruintn reservedbits :29; } sslciphersuiteinfo; (unfinished, to be completed here) ...
NSS Tools certutil
mmand options and their arguments are defined as follows: options -n create new certificate and key databases. -s create an individual certificate and add it to a certificate database. -r create a certificate-request file that can be submitted to a certificate authority (ca) for processing into a finished certificate. output defaults to standard out unless you use -ooutput-file argument. use the -a argument to specify ascii output. -c create a new binary certificate file from a binary certificate-request file. use the -i argument to specify the certificate-request file. if this argument is not used certificate database tool prompts for a filename. ...
NSS Tools modutil
used by these programs. for example, a windows installation might consist of a setup.exe installation program, a help file, and a .cab file containing compressed information. all these files could be installed in the temporary directory. files destined for the temporary directory are guaranteed to be in place before any executable file is run; they are not deleted until all executable files have finished. absolutepath specifies the destination directory of the file as an absolute path. if both relativepath and absolutepath are specified, the installer attempts to use the relative path; if it is unable to determine a relative path, it uses the absolute path. executable specifies that the file is to be executed during the course of the installation. typically this string would be used for...
certutil
ular hardware or software token. -m modify a certificate's trust attributes using the values of the -t argument. -n create new certificate and key databases. -o print the certificate chain. -r create a certificate request file that can be submitted to a certificate authority (ca) for processing into a finished certificate. output defaults to standard out unless you use -o output-file argument. use the -a argument to specify ascii output. -s create an individual certificate and add it to a certificate database. -t reset the key database or token. -u list all available modules or print a single named module. -v ...
NSS tools : modutil
Mozilla › Projects › NSS › tools › modutil
directory. the %temp% directory is created at the beginning of the installation and destroyed at the end. the purpose of %temp% is to hold executable files (such as setup programs) or files that are used by these programs. files destined for the temporary directory are guaranteed to be in place before any executable file is run; they are not deleted until all executable files have finished. absolutepath specifies the destination directory of the file as an absolute path. executable specifies that the file is to be executed during the course of the installation. typically, this string is used for a setup program provided by a module vendor, such as a self-extracting setup executable. more than one file can be specified as executable, in which case the files ...
Index
cros to define an array of jsfunctionspecs to pass to js_definefunctions or js_initclass. 269 js_fileescapedstring jsapi reference, reference, référence(2), spidermonkey js_fileescapedstring writes str into file fp escaping any non-printable or non-ascii character. if quote is not 0, it must be a single or double quote character that will quote the output. 270 js_finish jsapi reference, obsolete, spidermonkey js_finish is obsolete. use js_destroyruntime instead. 271 js_flattenstring jsapi, jsapi reference, reference, référence(2), spidermonkey js_flattenstring flattens a string str and returns a pointer to jsflatstring. 272 js_flushcaches jsapi reference, needscontent, spidermonkey . 273 js_forgetl...
Bytecode Descriptions
implicit ones generated as part of for-of iteration. resumeindex operands: (uint24_t resumeindex) stack: ⇒ resumeindex push resumeindex. this value must be used only by jsop::gosub, jsop::finally, and jsop::retsub. format: jof_resumeindex gosub operands: (int32_t forwardoffset) stack: false, resumeindex ⇒ jump to the start of a finally block. jsop::gosub is unusual: if the finally block finishes normally, it will reach the jsop::retsub instruction at the end, and control then "returns" to the jsop::gosub and picks up at the next instruction, like a function call but within a single script and stack frame. (it's named after the thing in basic.) we need this because a try block can terminate in several different ways: control can flow off the end, return, throw an exception, break with o...
Statistics API
t 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 time taken by each phase: the sum of each field of the map from the slices. the last two fields r...
Garbage collection
a bit of marking work, then let the mutator (javascript program) run a bit, then do another bit of marking work. thus, instead of one long pause for marking, the gc does a series of short pauses. the pauses can be set to be 10ms or less. there is always a possibility that a long pause will be required. if the allocation rate is high during incremental gc, the engine may run out of memory before finishing the incremental gc. if so, the engine must immediately restart a full, non-incremental gc in order to reclaim some memory and continue execution. incremental write barrier the problem that requires a write barrier incremental gc requires a write barrier for correctness. todo decent diagrams the basic problem is as follows (see dictionary for color terms). say object a is black and contain...
SpiderMonkey Internals: Thread Safety
he most obvious effect of a request is: at any given moment there can either be multiple threads in active requests, or one thread doing gc and all requests suspended. a call to js_gc() will block until the latter becomes possible. in other words, gc waits until each other thread is either outside jsapi (in which case we don't care what it's doing) or else in jsapi, but blocked, waiting for gc to finish. threads must not do anything that would affect gc while outside a request. and obviously you shouldn't block or otherwise dilly-dally while in a request; it prohibits gc. as an optimization, each thread has its own size-classified freelists containing chunks of gc-managed memory ready to be allocated. this allows allocation to avoid locking most of the time (a significant speed win). a thread ne...
JSAPI User Guide
on. then it determines whether to allow the operation to proceed. tracing and profiling there are features provided by the jsapi that make it easier to implement javascript tracers and profilers. ...
JSObjectOps.dropProperty
wing contract governs jsobjectops callers and implementations: whenever jsobjectops.lookupproperty returns a jsproperty pointer, the property is locked. while the property is locked, the caller may access it using other jsobjectops callbacks. it may not otherwise call into the jsapi in ways that might trigger other property accesses. (in a js_threadsafe build, that would risk deadlock.) when finished with a locked property, the caller must release it by calling the dropproperty callback. the lifetime of the jsproperty * extends from the successful defineproperty or lookupproperty call to the dropproperty call. as a spidermonkey implementation detail, what is actually locked here (under the native implementation of jsobjectops) is not the property but some collection of objects including ...
JS_ClearContextThread
ext. description an application that creates or uses a jscontext in one thread, then uses or destroys it in another thread, must use js_clearcontextthread and js_setcontextthread to transfer the jscontext safely from one thread to the other. the rules for using jscontexts in multiple threads are: each jscontext may only be used by one thread at a time. each request runs from start to finish on a single thread. before transferring a jscontext from thread a to thread b, thread a must call js_clearcontextthread. this is the last thing thread a does with the context. before thread b uses the jscontext, it must call js_setcontextthread. this is the first thing thread b does with the context, before beginning a request. so the usual code for using a jscontext on a thread other than th...
JS_SetGCCallback
is not in an active request calls js_gc while gc is already happening on another thread). in a js_threadsafe build, a jsgc_begin callback can happen on one thread before or while a jsgc_end callback for the previous gc cycle runs on another thread. in a js_threadsafe build, the jsgc_end callback is called after each stop-the-world rendezvous during which one or more garbage collection cycles finished. the callback executes on the same thread that performed gc, after the gc lock has been released. other threads may be running in active requests. see also mxr id search for js_setgccallback js_setfinalizecallback bug 723286 ...
JS_SetGCZeal
r removed. 2 collect when every frequency allocations. 3 collect on window paints. 4 verify pre write barriers between instructions. 5 verify pre write barriers between window paints. 6 verify stack rooting. 7 collect the nursery every frequency nursery allocations. 8 incremental gc in two slices: 1) mark roots 2) finish collection. 9 incremental gc in two slices: 1) mark all 2) new marking and finish. 10 incremental gc in multiple slices. 11 verify post write barriers between instructions. 12 verify post write barriers between paints. 13 check internal hashtables on minor gc. 14 perform a shrinking collection every frequency allocations. ...
JS_THREADSAFE
ication must separate code that uses the jsapi from code that performs blocking i/o or time-consuming calculations. a request is a region of code that uses the jsapi. requests must be bracketed with calls to js_beginrequest() and js_endrequest(). js_beginrequest(cx); /* ... do jsapi stuff ... */ js_endrequest(cx); a request is always associated with a specific jscontext and runs from start to finish on a single thread. most jsapi functions require the caller to be in a request. in this reference, these jsapi functions are marked with the words "requires request", like this: name type description cx jscontext * the context to use. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. most jsapi callback functions ...
Property attributes
other apis that define properties: it means that the name parameter is actually an integer unsafely cast to a pointer type, not a string. mxr id search for jsprop_index jsprop_define_late don't define property when initially creating the constructor. some objects like function/object have self-hosted functions that can only be defined after the initialization is already finished. added in spidermonkey 38 mxr id search for jsprop_define_late jsfun_stub_gsops use js_propertystub getter/setter instead of defaulting to class gsops for property holding function. added in spidermonkey 17 mxr id search for jsfun_stub_gsops jsfun_constructor native that can be called as a constructor. added in spidermonkey 17 mxr id sear...
SpiderMonkey 1.8.5
zeobject js_definefunctionbyid js_defineownproperty js_definepropertybyid js_deletepropertybyid js_deletepropertybyid2 js_doubleisint32 js_encodestringtobuffer js_entercrosscompartmentcall js_evaluatescriptforprincipalsversion js_evaluateucscriptforprincipalsversion js_executeregexp js_executeregexpnostatics js_executescriptversion js_forget_string_flatness js_fileescapedstring js_finishjsonparse (removed in future releases, replaced with js_parsejson) js_flatstringequalsascii js_flattenstring js_flushcaches js_freezeobject js_getcompartmentprivate js_getemptystring js_getflatstringchars js_getgcparameter js_getgcparameterforthread js_getglobalforscopechain js_getinternedstringchars js_getinternedstringcharsandlength js_getownpropertydescriptor js_getpropertyattrsge...
SpiderMonkey 1.8.7
zeobject js_definefunctionbyid js_defineownproperty js_definepropertybyid js_deletepropertybyid js_deletepropertybyid2 js_doubleisint32 js_encodestringtobuffer js_entercrosscompartmentcall js_evaluatescriptforprincipalsversion js_evaluateucscriptforprincipalsversion js_executeregexp js_executeregexpnostatics js_executescriptversion js_forget_string_flatness js_fileescapedstring js_finishjsonparse (removed in future releases, replaced with js_parsejson) js_flatstringequalsascii js_flattenstring js_flushcaches js_freezeobject js_getcompartmentprivate js_getemptystring js_getflatstringchars js_getgcparameter js_getgcparameterforthread js_getglobalforscopechain js_getinternedstringchars js_getinternedstringcharsandlength js_getownpropertydescriptor js_getpropertyattrsge...
Setting up CDT to work on SpiderMonkey
s page. start eclipse and create a workspace somewhere. select "new > makefile project with existing code" from the "file" menu. give the project a name that you like ("spidermonkey" has a nice ring to it) and use the "browser…" button to select your checkout's js/src folder for the "existing code location". choose the correct toolchain for your platform (i.e. macos x gcc on mac) and click "finish". at this point, the indexer starts running and already produces a pretty decent index of much of spidermonkey. still, there are a quite a few things that cdt does not pick up yet: for everything to be indexed, cdt has to be aware of the project's build details. step 3 - index all the code to let cdt know about the build, it has to invoke make itself (or, as is done in the guide for the whole...
Web Replay
ses at once, and coordinate their behavior so they run in parallel. there can be up to one recording child and two replaying children at once. the advantage of spawning both recording and replaying children is that by switching between different children the middleman can effectively rewind a live recording, then play forward and allow the user to resume interacting with the tab after they have finished inspecting state in the past. the advantage of using two replaying processes is to provide a smoother experience when rewinding. recording/replaying process extensions during initialization the child process spawns a thread that does not participate in the recording — any ipc or other system calls it performs are live, even when replaying. this thread sends and receives messages from the...
Setting up an update server
click it to restart and apply the update. ...
Gecko events
p menu has been displayed. is supported: yes event_menupopup_end a pop-up menu has been closed. is supported: yes event_capture_start a window has received mouse capture. is supported: no event_capture_end a window has lost mouse capture. is supported: no event_movesize_start a window is being moved or resized. ...
Accessing the Windows Registry Using XPCOM
t_key_local_machine, "software\\microsoft\\windows\\currentversion", wrk.access_read); wrk.startwatching(false); // only watch the values on this key, not child keys var id = readregistryvalue(wrk, "productid"); /* later you can read this again, and it should come from the cache unless there have been changes to the registry. remember to call wrk.close() when you are finished! */ support in firefox 1.0 firefox 1.0 includes a much simpler interface to the windows registry, without most of the functionality supported in newer versions. the functionality is exposed in the nsiwindowsshellservice interface. it consists of only one method, getregistryentry(), and a set of named constants to specify the root key. you can use it as shown in the following example: var ws...
Building the WebLock UI
led weblock.xul, which you'll be adding to an installer archive in appendix b in this book. note that this file defines the dialog that displays when the user/administrator clicks the web locking icon in the bottom right corner of the browser. that piece of ui - which needs to be dynamically inserted into the browser at runtime - is described in overlaying new user interface into mozilla. the finished dialog appears below. web lock manager dialog as you can see, it's a simple interface, providing just enough widgetry to lock and unlock the browser and to add new sites to the list. the entire xul file for the web lock manager dialog is defined in weblock.xul below. the locking ui once you have the basic xul wrapper set up for your interface, the next step is to define that part of the i...
Preface
its own chapter, in which a number of topics associated with the step are discussed. create the generic module code for the component. use c++ macros, special string classes and smart pointers to optimize your code. define the functionality for the component; create an xpidl interface for that functionality; create the implementation code specific to the custom weblock component interface. finish implementing the weblock component: nsicontentpolicy, file i/o, locking, etc. creating the user interface for the weblock component. packaging weblock for distribution and installation. following along with the examples there are a couple of different ways to get xpcom onto your machine so you can begin to create components. if you already have a mozilla build or the source from mozilla 1.2 ...
Setting up the Gecko SDK
its location. (this example uses "samplegeckoproject" as the project name and c:\ as its location.). (need correction for last visual c++. now it's microsoft visual c++ 2010. express edition is free.) new dialog select ok. in the win32 dynamic-link library dialog that displays (see below), you can choose the default selection "an empty dll project" as the type of dll. in this dialog, click finish. microsoft studio creates a new project per your specification and presents you with the standard project view. adding the gecko sdk to the project settings in order to build anything that uses gecko, you have to further modify the project so that it knows where to find the gecko sdk on the disk. to edit project settings, select settings from the project menu (or press alt-f7). most of the cha...
Creating XPCOM components
com xpidl code generation getting the weblock service from a client implementing the iweblock interface the directory service modifying paths with nsifile manipulating files with nsifile using nsilocalfile for reading data processing the white list data iweblock method by method lock and unlock addsite removesite setsites getnext getsites hasmoreelements finishing the component using frozen interfaces copying interfaces into your build environment implementing the nsicontentpolicy interface receiving notifications implementing the nsicontentpolicy uniform resource locators checking the white list creating nsiuri objects building the weblock ui user interface package list client code overview xul the xul document ...
Detailed XPCOM hashtable guide
. because pldhash does not know what datatype your key is, all functions that work with keys are declared using const void*, and your client code must cast these pointers to the appropriate type. pldhashtables can be allocated on the stack or the heap: when allocated on the stack, or as a c++ class member, the table must be initialized using pl_dhashtableinit, and finalized using pl_dhashtablefinish; when allocated on the heap, use pl_newdhashtable and pl_dhashtabledestroy to allocate and delete the table. plhashtable plhashtable is a part of nspr. the header file can be found at nsprpub/lib/ds/plhash.h. in general, pldhash is a better solution than plhashtable, because plhashtable makes many heap allocations. there are two situations where plhashtable may be preferable to pldhash: y...
Receiving startup notifications
oading their components, and continuing with application startup, all without having to restart the browser. receiving startup notifications prior to gecko 2.0 (firefox 4) to receive startup notifications, one needs to register with the "app-startup" category using nsicategorymanager; having done so, the component will receive these startup notifications, including: xpcom-startup sent when xpcom finishes starting up. most application features are not yet available at this point, but xpcom itself is. app-startup sent when the application has finished starting up. final-ui-startup sent just before the first application window is displayed. registering with the category manager to register with the category manager, simply call its nsicategorymanager.addcategoryentry() method: categorymanager->ad...
XPCOM Stream Guide
Mozilla › Tech › XPCOM › Guide › Streams
listener object. you can get an nsichannel object from the io service's newchannel(spec, charset, baseuri) method or its .newchannelfromuri(uri) method. the "safe file output stream" mozilla provides a "safe file output stream" implementation. this implementation actually writes the contents of the file you're trying to create to a temporary file. if everything goes well, calling the stream's .finish() method overwrites the original file with the new file. using streams in c++ using streams in javascript input streams input streams are not scriptable - you cannot directly call .read() on them, for example. to solve this, there is a special nsiscriptableinputstream interface and "scriptable stream" wrapper. if you have an input stream called nativestream, you can use code like this: var s...
Components.utils.Sandbox
function() { ... }; complex objects can be cloned into the sandbox using components.utils.cloneinto: mysandbox.someobject = components.utils.cloneinto({ a: 'string', b: 21 }, mysandbox); obviously you need to consider the security implications of the functions you import. this technique isn't limited to functions - it can be used to import objects or values. freeing the sandbox when you have finished using a sandbox, it should be freed to avoid memory leaks. generally the javascript garbage collector will take care of this when there are no remaining references to the sandbox or the code it contains. however, in some cases it can be difficult to remove all references. for example, the code in the sandbox might be a third-party library that sets expando properties or adds event listeners to ...
Components.utils.schedulePreciseGC
components.utils.scheduleprecisegc( function() { // this code is executed when the garbage collection has completed } ); since the garbage collection doesn't occur until some time in the future (unlike, for example, components.utils.forcegc(), which causes garbage collection immediately but isn't able to collect all javascript-related memory), the callback lets you know when that's been finished. ...
HOWTO
.org/en/xpconnect/xpcshell/howto> print("doing async work"); gscriptdone = false; var gthreadmanager = cc["@mozilla.org/thread-manager;1"] .getservice(ci.nsithreadmanager); var mainthread = gthreadmanager.currentthread; while (!gscriptdone) mainthread.processnextevent(true); while (mainthread.haspendingevents()) mainthread.processnextevent(true); 2. in all callbacks where your script is finished, i.e. both success and error callbacks, put: gscriptdone = true; if you forget some condition where your script should exit but you don't add this statement, your script will hang (busy wait). this is of course a massive, ugly hack prone to error, but this is what the xpcshell test harness does. there should really be a better solution in xpcshell. using js modules and non-ui javascript chrome ...
Profiling XPCShell
ll scripts. to use it, you need to enable it in your mozconfig: ac_add_options --enable-xpctools now you can profile an entire script by setting the environment variable <tt>mozilla_js_profiler_output</tt> to a filename where you want the output file. for example, on linux or macosx you do: export mozilla_js_profiler_output=/tmp/profile.txt now, run the script using xpcshell. after running has finished, the output file will contain a profile. a profile will look like this: file:///users/michiel/mozilla/tree1/...js/calutils.js [2,25420] createdatetime() {60-62} 579 {min 0, max 3, avg 0, sum 427, self 427} [2,56810] cp_qi() {860-866} 835 {min 0, max 1, avg 0, sum 950, self 950} the first line tells which file was profiled. then, the next lines shows the amount of time spend in the f...
NS_InitXPCOM2
ider* aappfilelocationprovider ); parameters aresult [out] the resulting xpcom service manager. you may pass null if you are not interested in this return value. the service manager may alternatively be accessed by calling ns_getservicemanager. the resulting interface pointer is addref'd upon return and must either be release'd explicitly or passed to ns_shutdownxpcom when the application is finished with xpcom. abindirectory [in] the directory containing the component registry and runtime libraries. pass null to specify that the current working directory should be used. aappfilelocationprovider [in] the object to be used by xpcom to locate application specific directories and files (e.g., the user profile, the component registry, etc.). this parameter may be nsnull. return values ...
NS_InitXPCOM3
pruint32 astaticmodulecount ); parameters aresult [out] the resulting xpcom service manager. you may pass null if you are not interested in this return value. the service manager may alternatively be accessed by calling ns_getservicemanager. the resulting interface pointer is addref'd upon return and must either be release'd explicitly or passed to ns_shutdownxpcom when the application is finished with xpcom. abindirectory [in] the directory containing the component registry and runtime libraries. pass null to specify that the current working directory should be used. aappfilelocationprovider [in] the object to be used by xpcom to locate application specific directories and files (e.g., the user profile, the component registry, etc.). this parameter may be nsnull. astaticmodules ...
NS_ShutdownXPCOM
n the calling process. #include "nsxpcom.h" nsresult ns_shutdownxpcom( nsiservicemanager* asvcmanager ); parameters asvcmanager [in] the nsiservicemanager instance that was returned by ns_initxpcom2 (or ns_initxpcom3) or null. return values the ns_shutdownxpcom function returns ns_ok if successful. otherwise, it returns an error code. remarks you must call this method once you are finished using xpcom. calling this method triggers the "xpcom-shutdown" notification to be dispatched to observers. once this function has been called, the nsicomponentmanager and nsiservicemanager will refuse to return object instances. history this function was finalized for mozilla 0.9.6. see bug bug 99147 for details. see also ns_initxpcom2, ns_initxpcom3 ...
imgIDecoderObserver
ew with this, please talk to bholley first. void onstopdecode( in imgirequest arequest, in nsresult status, in wstring statusarg ); parameters arequest the request on which data is available, or null if being called for an imgidecoder object. status missing description statusarg missing description onstopframe() a decode notification that is called when a frame is finished decoding. void onstopframe( in imgirequest arequest, in unsigned long aframe ); parameters arequest the request on which data is available, or null if being called for an imgidecoder object. aframe missing description onstoprequest() a load notification that is called at the same time that nsirequestobserver.onstoprequest() would be (used only for observers of imgirequest...
imgIEncoder
ta. outputoptions semicolon-delimited list of name=value pairs that can give options to the output encoder. options are encoder-specific. just give an empty string for default behavior. remarks for encoding images which may contain multiple frames, the 1-shot initfromdata() interface is too simplistic. the alternative is to use startimageencode(), call addimageframe() one or more times, and then finish initialization with endimageencode(). ...
mozIRepresentativeColorCallback
void oncomplete( in boolean success, [optional] in unsigned long color ); parameters success true if analysis was successful, false otherwise. analysis can fail if the image is transparent, imageuri doesn't resolve to a valid image, or the image is too big. color the representative color as an integer in rgb form. e.g. 0xff0102 == rgb(255,1,2). if success is fa...
mozIStorageAggregateFunction
lback should be reentrant if any of the above applies to your use of the storage apis! void onstep( in mozistoragevaluearray afunctionarguments ); parameters afunctionarguments a mozistoragevaluearray holding the arguments passed in to the function. onfinal() this is called after all results have been obtained and notified via mozistorageaggregatefunction. the implementation should finish its calculations on the data, and return a result. note this callback is executed on the thread that the statement or trigger is executing on. if you use mozistorageconnection.executeasync() or, mozistoragestatement.executeasync() this callback will run on a different thread from the rest of your code. likewise, if you execute sql on a different thread, this callback will be executed on that th...
mozIStorageStatementCallback
mary 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. 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 ...
nsIAccessibleEvent
a pop-up menu has been displayed. event_menupopup_end 0x001b 0x0018 a pop-up menu has been closed. event_capture_start 0x001c 0x0019 a window has received mouse capture. event_capture_end 0x001d 0x001a a window has lost mouse capture. event_movesize_start 0x001e 0x001b a window is being moved or resized. event_movesize_end 0x001f 0x001c the movement or resizing of a window has finished. event_contexthelp_start 0x0020 0x001d a window has entered context-sensitive help mode. event_contexthelp_end 0x0021 0x001e a window has exited context-sensitive help mode. event_dragdrop_start 0x0022 0x001f an application is about to enter drag-and-drop mode. event_dragdrop_end 0x0023 0x0020 an application is about to exit drag-and-drop mode. event_dialog_start 0x0024 0x00...
nsIAppShell
may be nested. on some platforms this will be a no-op. void resumenative(); parameters none. run() enter an event loop. do not leave until exit() is called. void run(); parameters none. runinstablestate() allows running of a "synchronous section", in the form of an nsirunnable once the event loop has reached a "stable state". a stable state is reached when the currently executing task/event has finished, (see: webappapis.html#synchronous-section). in practice this runs arunnable once the currently executing event finishes. if called multiple times per task/event, all the runnables will be executed, in the order in which runinstablestate was called. void runinstablestate( in nsirunnable arunnable ); parameters arunnable an nsirunnable to run. spindown() obsolete since geck...
nsIAppStartup
lues are the times. events that didn't occur are not in the object. event identifier (key) description main time at which main application core was loaded. note: only available with libxul builds. firstpaint time the first paint occurred. note: only available with libxul builds. sessionrestored time session restore finished. example this example logs startup time information to the console. var aconsoleservice = components.classes["@mozilla.org/consoleservice;1"] .getservice(components.interfaces.nsiconsoleservice); var startupinfo = components.classes["@mozilla.org/toolkit/app-startup;1"] .getservice(ci.nsiappstartup_mozilla_2_0).getstartupinfo(); var keys = o...
nsIContentPrefCallback2
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. voi...
nsIDownload
this interface is deprecated as of firefox 26. please use downloads.jsm instead. toolkit/components/downloads/public/nsidownload.idlscriptable this interface describes a download object. download objects are used by the download manager (see nsidownloadmanager to manage files that are queued to download, being downloaded, and finished being downloaded.) inherits from: nsitransfer last changed in gecko 1.9.1 (firefox 3.5 / thunderbird 3.0 / seamonkey 2.0) note: once the download is completed, the download manager stops updating the nsidownload object. completed states are nsidownloadmanager::download_finished, nsidownloadmanager::download_failed, and nsidownloadmanager::download_canceled. attributes attribute type description amounttransferred long long ...
nsIDownloadManager
th specified by the browser.download.dir preference. if this preference is invalid, the download directory falls back to the default. read only. constants constant value description download_notstarted -1 the download has not been started yet. download_downloading 0 the download is in the process of being downloaded. download_finished 1 download completed including any processing of the target file. download_failed 2 the download failed due to error. download_canceled 3 the user canceled the download. download_paused 4 the download is currently paused. download_queued 5 the download is in the queue but is not presently downloading. download_blocked_p...
nsIDragService
ved( in long ax, in long ay ); parameters ax the x coordinate to which to move the popup being dragged. ay the y coordinate to which to move the popup being dragged. enddragsession() tells the drag service to end a drag session. this is called when an external drag occurs. void enddragsession( in prbool adonedrag ); parameters adonedrag if adonedrag is true, the drag has finished, otherwise the drag has just left the window. firedrageventatsource() obsolete since gecko 43 (firefox 43 / thunderbird 43 / seamonkey 2.40)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. fire a drag event at the source of the drag. this was changed in gecko 43, see the following se...
nsIEventTarget
an event to this event target. this function may be called from any thread, and it may be called re-entrantly. void dispatch( in nsirunnable event, in unsigned long flags ); parameters event the event to dispatch. flags the dispatch flags modifying the event. exceptions thrown ns_error_unexpected indicates that the thread is shutting down and has finished processing events, so this event would never run and has not been dispatched. ns_error_invalid_arg indicates that event is null. isoncurrentthread() check to see if this event target is associated with the current thread. boolean isoncurrentthread(); parameters none. return value returns true if events dispatched to this event target will run on the current thread (that is, the ...
nsIFactory
ng requested in the component which is being currently created. result pointer to the newly created instance, if successful. exceptions thrown ns_error_no_interface indicates that the requested interface is not supported. ns_error_no_aggregation indicates that aggregation is not supported. lockfactory() this method provides the client a way to keep the component in memory until it is finished with it. gecko 1.7 note as of gecko 1.7, this method is unused. most implementations do nothing interesting with this method. it exists primarily for binary compatibility with microsoft com's iclassfactory interface. void lockfactory( in prbool lock ); parameters lock true to lock the factory, and false to unlock the factory. remarks on win32 systems, nsifactory is abi-compat...
nsIFrameMessageManager
closed ); parameters amessage the name of the message for which to add a listener. alistener an object implementing nsiframemessagelistener whose receivemessage method will be called when the message is received. listenwhenclosed default is false. set to oo if you want to receive messages during the short period after a frame has been removed from the dom and before its frame script has finished unloading. this parameter only has an effect for frame message managers in the main process. an alternative method to listen for death of frame script is to use message-manager-disconnect observer: observer notifications :: message manager. removemessagelistener() removes a message listener previously added by calling addmessagelistener(). void removemessagelistener( in astring amessage,...
nsIHttpUpgradeListener
1.0 66 introduced gecko 6.0 inherits from: nsisupports last changed in gecko 6.0 (firefox 6.0 / thunderbird 6.0 / seamonkey 2.3) this is used, for example, by websockets in order to upgrade an http channel to use the websocket protocol. ...
nsIMessageListenerManager
] in boolean listenwhenclosed); parameters messagename a string indicating the name of the message to listen for. listener an nsimessagelistener to invoke when a message is received. see nsimessagelistener for details of the message syntax. listenwhenclosed specify true to receive messages during the short period after a frame has been removed from the dom and before its frame script has finished unloading; this is false by default. this parameter only has an effect for frame message managers in the main process. an alternative method to listen for death of frame script is to use a message-manager-disconnect observer; see observer notifications :: message manager. removemessagelistener() undo an addmessagelistener() call; that is, calling this causes listener to stop being invoked w...
nsIMicrosummary
this method returns false if either objects don't have a generator removeobserver() remove a microsummary observer from this microsummary. void removeobserver( in nsimicrosummaryobserver observer ); parameters observer the microsummary observer to remove. update() update the microsummary, first loading its generator and page content as necessary. if you want know when a microsummary finishes updating, add an observer before calling this method. void update(); see also microsummary topics creating a microsummary ...
nsIMsgMessageService
in boolean canonicallineending, in nsimsgwindow amsgwindow); parameters amessageuri url representing the message to spool out to disk. afile the file you want the message saved to. ageneratedummyenvelope usually false. set to true if you want the message appended at the end of the file. aurllistener a nsiurllistener for being notified when the copy is finished. canonicallineending amsgwindow nsimsgwindow for progress and status feedback return values aurl the new nsiuri of the saved message. note: this operation may be obsolete. you always can use streammessage to get the eml string representation of the message and then write it using file i/o methods. geturlforuri() when you have a uri and you would like to convert that to a url which ...
nsIMsgSearchNotify
void onsearchdone(in nsresult status); /* * until we can encode searches with a uri, this will be an * out-of-bound way to connect a set of search terms to a datasource */ /* * called when a new search begins */ void onnewsearch(); }; ...
nsINavHistoryResultObserver
, so that it won't handle the large number of updates that are about to be notified. this is especially useful when updating user interfaces, to avoid flicker or continuous selection changes, which may result in performance degradation (for example, if updating a view for each update). void batching( in boolean atogglemode ); parameters atogglemode specify true to start batch mode or false to finish the batch. containerclosed() obsolete since gecko 11.0 (firefox 11.0 / thunderbird 11.0 / seamonkey 2.8) called when a container node's state changes from opened to closed. note: this method was deprecated in gecko 2.0 and removed in gecko 11.0 (firefox 11.0 / thunderbird 11.0 / seamonkey 2.8). implement the containerstatechanged() method instead. void containerclosed(...
nsIProtocolProxyService
ny additional bits that do not correspond to a resolve_ flag are reserved for future use. return value an nsiproxyinfo object or null for a direct connection. note: if pac is configured, and the pac file has not yet been loaded, then this method will return a nsiproxyinfo instance with a type of "unknown" to indicate to the consumer that asyncresolve should be used to wait for the pac file to finish loading. otherwise, the consumer may choose to treat the result as type "direct" if desired. see nsiproxiedprotocolhandler.newproxiedchannel(). asyncresolve() this method is an asychronous version of the resolve method. unlike resolve, this method is guaranteed not to block the calling thread waiting for dns queries to complete. this method is intended as a substitute for resolve when the resu...
nsISHistory
of toplevel documents currently available in session history. read only. index long the index of the current document in session history. read only. maxlength long used to get/set the maximum number of toplevel documents, session history can hold for each instance. requestedindex long the index of the last document that started to load that is not yet finished loading. when the document finishes loading the value -1 is returned. read only. shistoryenumerator nsisimpleenumerator called to obtain a enumerator for all the documents stored in session history. the enumerator object thus returned by this method can be traversed using nsisimpleenumerator. to access individual history entries of the enumerator, perform the following ...
nsIServiceManager
repository to find and instantiate factories to obtain services. because services are instantiated lazily, methods are provided to test whether or not a service has already been instantiated. users of the service manager must first obtain a pointer to the global service manager by calling ns_getservicemanager. after that, they can request specific services by calling getservice(). when they are finished they should call nsisupports.release() on the service as they would with any interface pointer. in some language bindings, such as javascript, this step is unnecessary. and, moreover such languages typically offer more convenient mechanisms to acquire references to xpcom services and components. a user of a service may keep references to services until application shutdown. this interface was...
nsISupports proxies
*x = 0; <----- you will blow up here. } so, given an event queue to execute methods on, and either an nsisupports object that has been created or cid, and a flag, a new nsisupports proxy object will be returned to you. once you have a proxy object, you may use it as if it is the "real" object. all the methods that are in the "real" object are stubbed into the proxy object. when you are finished with a proxy object, you should call ns_release on it. it will take care of freeing the "real" object as well as itself. if you have created the object yourself and then created the proxy, please note that you will have at least a refcount of 2 (one for the proxy and one for the created object which you passed into getproxyobject, plus any other refcounts which you may have). a point here to b...
nsITimer
_skip while also being less useful. so the distinction was removed. type_repeating_precise_can_skip 3 this repeating timer aims to have constant period between firings. the processing time for each timer callback should not influence the timer period. however this timer type guarantees that it will not queue up new events to fire the callback until the previous callback event finishes firing. if the callback takes a long time, then the next callback will be scheduled immediately afterward, but only once, unlike type_repeating_precise. if you want a non-slack timer, you probably want this one. methods cancel() cancels the timer. this method works on all types, not just on repeating timers -- you might want to cancel a type_one_shot timer, and even reuse it by re-in...
nsIUpdateCheckListener
toolkit/mozapps/update/nsiupdateservice.idlscriptable an interface describing an object that listens to the progress of an update check operation. this object is notified as the check continues, finishes and if it has an error. 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 oncheckcomplete(in nsixmlhttprequest request, [array, size_is(updatecount)] in nsiupdate updates, in unsigned long updatecount); void onerror(in nsixmlhttprequest request, in nsiupdate update); void onprogress(in nsixmlhttprequest request, in unsigned long position, in unsigned long totalsize); methods oncheckcomplete() called when the update check is completed. void oncheckcomplet...
nsIWindowMediator
this will attach the functionality to future opened windows, so if you copy paste this code to scratchpad, then after running this script, you need to open a new window by pressing ctrl + n and then in the new window, selecting tabs will fire the alert. ...
NS_CStringAppendData
s_ok if successful. otherwise, it returns an error code. remarks this function is defined inline as a wrapper around ns_cstringsetdatarange. example nscstringcontainer str; ns_cstringcontainerinit(str); ns_cstringsetdata(str, "hello"); ns_cstringappenddata(str, " world"); const char* data; ns_cstringgetdata(str, &data); printf("%s\n", data); // prints out "hello world" ns_cstringcontainerfinish(str); history this function was frozen for mozilla 1.7. see bug 239123 for details. see also ns_cstringsetdatarange, nsacstring ...
NS_CStringCutData
ks this function is defined inline as a wrapper around ns_cstringsetdatarange . example code nscstringcontainer str; ns_cstringcontainerinit(str); ns_cstringsetdata(str, "hello world"); // remove " world" portion of string ns_cstringcutdata(str, 5, pr_uint32_max); const char* data; ns_cstringgetdata(str, &data); printf("%s\n", data); // prints out "hello" ns_cstringcontainerfinish(str); history this function was frozen for mozilla 1.7. see bug 239123 for details. see also ns_cstringsetdatarange , nsacstring ...
NS_CStringInsertData
therwise, it returns an error code. remarks this function is defined inline as a wrapper around ns_cstringsetdatarange. example code nscstringcontainer str; ns_cstringcontainerinit(str); ns_cstringsetdata(str, "hello"); ns_cstringinsertdata(str, 5, " world"); const char* data; ns_cstringgetdata(str, &data); printf("%s\n", data); // prints out "hello world" ns_cstringcontainerfinish(str); history this function was frozen for mozilla 1.7. see bug 239123 for details. see also ns_cstringsetdatarange, nsacstring, nsacstring ...
NS_CStringSetData
rminated. return values the ns_cstringsetdata function returns ns_ok if successful. otherwise, it returns an error code. example nscstringcontainer str; rv = ns_cstringcontainerinit(str); if (ns_succeeded(rv)) { rv = ns_cstringsetdata(str, "hello world"); if (ns_succeeded(rv)) { // now, pass |str| to some function expecting a |const nsacstring&| parameter. } ns_cstringcontainerfinish(str); } history this function was frozen for mozilla 1.7. see bug 239123 for details. see also nsacstring ...
NS_StringAppendData
ar option to compile this example since prunichar is an unsigned short. this example should compile by default under msvc. example code nsstringcontainer str; ns_stringcontainerinit(str); ns_stringsetdata(str, l"hello"); ns_stringappenddata(str, l" world"); const prunichar* data; ns_stringgetdata(str, &data); // data now points to the string: l"hello world" ns_stringcontainerfinish(str); history this function was frozen for mozilla 1.7. see bug 239123 for details. see also ns_stringsetdatarange, nsastring ...
NS_StringCutData
unichar is an unsigned short. this example should compile by default under msvc. example code nsstringcontainer str; ns_stringcontainerinit(str); ns_stringsetdata(str, l"hello world"); // remove " world" portion of string ns_stringcutdata(str, 5, pr_uint32_max); const prunichar* data; ns_stringgetdata(str, &data); // data now ponts to the string: l"hello" ns_stringcontainerfinish(str); history this function was frozen for mozilla 1.7. see bug 239123 for details. see also ns_stringsetdatarange, nsastring ...
NS_StringInsertData
option to compile this example since prunichar is an unsigned short. this example should compile by default under msvc. example code nsstringcontainer str; ns_stringcontainerinit(str); ns_stringsetdata(str, l"hello"); ns_stringinsertdata(str, 5, l" world"); const prunichar* data; ns_stringgetdata(str, &data); // data now points to the string: l"hello world" ns_stringcontainerfinish(str); history this function was frozen for mozilla 1.7. see bug 239123 for details. see also ns_stringsetdatarange , nsacstring ...
NS_StringSetData
rn values the ns_stringsetdata function returns ns_ok if successful. otherwise, it returns an error code. example code nsstringcontainer str; rv = ns_stringcontainerinit(str); if (ns_succeeded(rv)) { rv = ns_stringsetdata(str, "hello world"); if (ns_succeeded(rv)) { // now, pass |str| to some function expecting a |const nsastring&| parameter. } ns_stringcontainerfinish(str); } history this function was frozen for mozilla 1.7. see bug 239123 for details. see also nsastring ...
Storage
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 you are r...
The Thread Manager
eads. when you dispatch an event to the pool, the pool selects an available worker thread to process the event. nsithreadinternal a subclass of nsithread that is implemented by the xpcom thread object to add support for observing dispatch activity on a thread. nsithreadobserver provides the ability to monitor a thread, to receive notifications when events are dispatched to it and when they're finished being processed. nsithreadeventfilter this interface is used by the nsithreadinternal.pusheventqueue() method in nsithreadinternal to allow event filtering. nsirunnable this interface is the base for all events/runnable objects which are dispatched to threads. tutorials making cross-thread calls using runnables ...
Index
underbird extensions are packaged and distributed in archive files (also known as bundles), with the xpi (pronounced “zippy”) file extension. at a minimum, they contain an install.rdf, the chrome.manifest and a chrome/ folder. a content/ folder sometimes contains the actual content files. these files contain the code that makes your extension actually do something. when this tutorial is finished, our extension will look like this: 76 building a thunderbird extension 3: install manifest extensions, thunderbird the install.rdf file is an xml file that provides general information about the extension. 77 building a thunderbird extension 4: chrome manifest extensions, thunderbird the file called chrome.manifest tells thunderbird what packages and ...
MailNews Filters
the next filter. in the case of pop3, filter execution is synchronous. for each new header, we evaluate the filter criteria and apply the actions synchronously, including moving a message to an other local folder, and advance to the next header. for imap, we tend to initiate the urls synchronously, but because we don't run two urls simultaneously on the same folder, the urls don't run until we've finished downloading headers. we also coalesce moves to the same destination folder, so that we can do them in one url/command to the server, and we playback those moves when the header download is done. after the fact filters these are one or more filters run on one or more folders *after* the headers have been downloaded. these filters are initiated in the filter editor, and implemented in nsmsgfi...
The libmime module
e putting function pointers into the class object, so we declare them here. they can generally all be static, since nobody outside of this file needs to reference them by name; all references to these routines should be through the class object. extern int foobarmethod(foobar *); ...etc... class initialization function the mimedefclass macro expects us to define a function which will finish up any initialization of the class object that needs to happen before the first time it is instantiated. its name must be of the form "<class>initialize", and it should initialize the various method slots in the class as appropriate. any methods or class variables which this class does not wish to override will be automatically inherited from the parent class (by virtue of its class-initializat...
Building a Thunderbird extension 2: extension file layout
information. extensions are packaged and distributed in archive files (also known as bundles), with the xpi (pronounced “zippy”) file extension. at a minimum, they contain an install.rdf, the chrome.manifest and a chrome/ folder. a content/ folder sometimes contains the actual content files. these files contain the code that makes your extension actually do something. ...
Using js-ctypes
standard locations. windows on windows, the following locations are searched for the library, in this order: the application's directory. the system directory. the 16-bit system directory. the windows directory. the current working directory the directories listed in the path environment variable. note: this information comes from this article on msdn. after you're done when you're finished using a library, you should close it by calling the library object's close() method: lib.close(); if you fail to close the library, it will be automatically closed when it is garbage collected. using the library you may need to declare new types. these can be simple types or more complex types such as structures. see declaring types for details. you will almost certainly need to declare one...
js-ctypes reference
ing. the ctypes object also provides numerous predefined types that correspond to primitives and common typedefs in c. working with libraries to load a library, use ctypes.open(). the library object is used mostly to declare native functions provided by the library so that js-ctypes knows how to call them. see library.declare() for instructions on how to declare these functions. once you have finished working with a library, call library.close(). calling conventions see abi. types and data to use js-ctypes effectively, it is important to understand the different kinds of objects that the module provides. there are three major categories: types these represent a type in c, and are thus represented by ctype objects. these objects have two main purposes. first, they provide a concrete rep...
URLs - Plugins
he subsequent npp_urlnotify call (which returns this value) and/or to pass a pointer to some request-related payload. if a request is not completed successfully (for example, because the url is invalid or an http server is down), the browser should call npp_urlnotify as soon as possible. if a request completes successfully, and the target is non-null, the browser calls npp_urlnotify after 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 compl...
Set a conditional breakpoint - Firefox Developer Tools
ssible to debug specific scenarios, such as bugs that only happen on odd entries in a list, or errors that occur the last time through a loop, for example. to set a conditional breakpoint, activate the context menu in the source pane, on the line where you want the breakpoint, and select "add conditional breakpoint". you'll then see a textbox where you can enter the expression. press return to finish. conditional breakpoints are shown as orange arrows laid over the line number. if you context-click on any breakpoint, you'll see a menu item "edit breakpoint". you can use this to modify an existing condition or to add a condition to a normal breakpoint. ...
Tutorial: Set a breakpoint - Firefox Developer Tools
get a debugger.object referring to the window's `report` // function. var reportdo = windowdo.getownpropertydescriptor('report').value; // set a breakpoint at the entry point of `report`. reportdo.script.setbreakpoint(0, { hit: function (frame) { console.log('hit breakpoint in ' + frame.callee.name); console.log('what = ' + frame.eval('what').return); } }); console.log('finished setting breakpoint!'); in the scratchpad, ensure that no text is selected, and press the “run” button. now, click on the text that says “click me!” in the web page. this runs the div element’s onclick handler. when control reaches the start of the report function, debugger calls the breakpoint handler’s hit method, passing a debugger.frame instance. the hit method logs the ...
Migrating from Firebug - Firefox Developer Tools
ommand line called command editor. the devtools do not have a side panel like the command editor (which is requested in bug 1133849), but therefore has a separate tool called scratchpad, which can be added as panel to the toolbox or opened in a separate window via firefox menu > developer > scratchpad or shift + f4. also, the normal command line smartly enters a line break when it recognizes an unfinished command like document. and you hit enter. you can also manually enter a line break by pressing shift + enter. response preview there is a preview tab when a network request logged to the console is expanded in firebug. the web console displays a preview within the response tab. it is currently missing the preview for html, xml and svg, though, which is tracked in bug 1247392 and bug 1262796, ...
Network request details - Firefox Developer Tools
line bar, so it is easy to locate performance bottlenecks. this tab can include the following sections. queued, started, downloaded new in firefox 72, we now show the following timings at the top of the timings tab, making dependency analysis a lot easier: queued: when the resource was queued for download. started: when the resource started downloading. downloaded: when the the resource finished downloading. note: future versions will also show this information when entries in the network monitor timeline graph are moused over (see bug 1580493). request timing the request timing section breaks a network request down into the following subset of the stages defined in the http archive specification: name description blocked time spent in a queue wa...
Allocations - Firefox Developer Tools
ke this are executing, the javascript engine must be paused, so your program is suspended and will be completely unresponsive. to reduce the impact on responsiveness, spidermonkey (the javascript engine in firefox) can perform gc in small increments, letting the program run in between. sometimes, though, it needs to perform a full non-incremental collection, and the program has to wait for it to finish. gc events are shown as red markers in the waterfall view, and are a big red flag for responsiveness, sometimes running for hundreds of milliseconds: if you're seeing gc events in your site's performance profile, what can you do? spidermonkey uses a complex set of heuristics to decide when to do what sort of garbage collection. in general, though: allocation pressure - allocating a lot of m...
Flame Chart - Firefox Developer Tools
// 1345 -> swap() // 252 -> selectionsort() // 190 -> swap() // 1 -> quicksort() // 103 -> partition() // 12 first, we'll just select the whole section in which the program was active: at the top, colored purple, is the sortall() call, running throughout the program from start to finish. underneath that, colored olive-green, are the calls it's making to sort(). underneath that, like the teeth of a comb, are all the calls being made to each sorting algorithm. let's zoom in: this slice is about 140 ms long, and shows us more details of the functions being called by sort(). the sort() code is just this: function sort(unsorted) { console.log(bubblesort(unsorted)); console.l...
Frame rate - Firefox Developer Tools
be made synchronously in response to some event. however, consistency is especially important: if you can't deliver 60fps, it's better to deliver lower frame rates more consistently, and avoid sudden dips in the frame rate which cause the site to freeze. frame rate graph the frame rate graph is found in the recording overview part of the performance tool. it takes a timestamp when the browser finishes a frame, and uses this to keep track of the frame rate over the course of the recording. the x-axis is time over the profile period, and there are three annotations: the maximum frame rate, 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 migh...
The JavaScript input interpreter - Firefox Developer Tools
r expressions in single-line mode, type at the prompt and press enter. to enter multi-line expressions, press shift+enter after typing each line, then enter to run all the entered lines. the expression you type is echoed under the input prompt, followed by the result. if your input does not appear to be complete when you press enter, then the console treats this as shift+enter , enabling you to finish your input. for example, if you type: function foo() { and then enter, the console does not immediately execute the input, but behaves as if you had pressed shift+enter , so you can finish entering the function definition. multi-line mode for multi-line entry, click the "split pane" icon at the right hand side of the single-line entry field, or press ctrl+b (windows/linux) or cmd+b (macos).
AbstractRange - Web APIs
the second child is the text node " is a paragraph.". with the text node reference in hand, we create a new range object by calling createrange() on the document itself. we set the starting position of the range to the sixth character of the text node's string, and the end position to the length of the text node's string minus one. this sets the range to encompass the word "paragraph". we then finish up by calling clonecontents() on the range to create a new documentfragment object which contains the portion of the document encompassed by the range. after that, we use appendchild() to add that fragment at the end of the document's body, as obtained from document.body. the result looks like this: specifications specification status comment domthe definition of ...
Animation.cancel() - Web APIs
Web › API › Animation › cancel
he animation interface clears all keyframeeffects caused by this animation and aborts its playback. when an animation is cancelled, its starttime and currenttime are set to null. syntax animation.cancel(); parameters none. return value none. exceptions this method doesn't directly throw exceptions; however, if the animation's playstate is anything but "idle" when cancelled, the current finished promise is rejected with a domexception named aborterror. specifications specification status comment web animationsthe definition of 'animation.cancel()' in that specification. working draft editor's draft. ...
Animation.oncancel - Web APIs
the oncancel property of the web animations api's animation interface is the event handler for the cancel event. the cancel event can be triggered manually with animation.cancel() when the animation enters the "idle" play state from another state, such as when the animation is removed from an element before it finishes playing creating a new animation that is initially idle does not trigger a cancel event on the new animation. syntax var cancelhandler = animation.oncancel; animation.oncancel = cancelhandler; value a function to be executed when the animation is cancelled, or null if there is no cancel event handler. examples if this animation is canceled, remove its element. animation.oncancel = function() { animation.effect.target.remove(); }; specifications specifica...
Animation.play() - Web APIs
Web › API › Animation › play
syntax animation.play(); parameters none. return value undefined example in the growing/shrinking alice game example, clicking or tapping the cake causes alice's growing animation (alicechange) to play forward, causing her to get bigger, as well as triggering the cake's animation. ...
Animation.playState - Web APIs
ate of an animation. this property is read-only for css animations and transitions. syntax var currentplaystate = animation.playstate; animation.playstate = newstate; value idle the current time of the animation is unresolved and there are no pending tasks. running the animation is running. paused the animation was suspended and the animation.currenttime property is not updating. finished the animation has reached one of its boundaries and the animation.currenttime 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 endin...
AudioBufferSourceNode - Web APIs
nodes are very inexpensive to create, and the actual audiobuffers can be reused for multiple plays of the sound. indeed, you can use these nodes in a "fire and forget" manner: create the node, call start() to begin playing the sound, and don't even bother to hold a reference to it. it will automatically be garbage-collected at an appropriate time, which won't be until sometime after the sound has finished playing. multiple calls to stop() are allowed. the most recent call replaces the previous one, if the audiobuffersourcenode has not already reached the end of the buffer. number of inputs 0 number of outputs 1 channel count defined by the associated audiobuffer constructor audiobuffersourcenode() creates and returns a new audiobuffersourcenod...
AudioContext - Web APIs
ontext, temporarily halting audio hardware access and reducing cpu/battery usage in the process. examples basic audio context declaration: var audioctx = new audiocontext(); cross browser variant: var audiocontext = window.audiocontext || window.webkitaudiocontext; var audioctx = new audiocontext(); var oscillatornode = audioctx.createoscillator(); var gainnode = audioctx.creategain(); var finish = audioctx.destination; // etc. specifications specification status comment web audio apithe definition of 'audiocontext' in that specification. working draft ...
AudioParam.setValueCurveAtTime() - Web APIs
ned. exceptions invalidstateerror the specified array of values has fewer than 2 items in it. rangeerror the specified starttime is either negative or a non-finite value, or duration is not a finite, strictly positive number. typeerror one or more of the values in the values array is non-finite. non-finite values are nan, infinity, and -infinity. usage notes when the parameter's value finishes following the curve, its value is guaranteed to match the last value in the set of values specified in the values parameter. note: some early implementations of the web audio api did not ensure this to be the case, causing unexpected results. examples in this example, we have a media source with a single button (see the webaudio-examples repo for the source code, or view the example live.)...
BaseAudioContext.decodeAudioData() - Web APIs
ta(arraybuffer, successcallback, errorcallback); newer promise-based syntax: promise<decodeddata> baseaudiocontext.decodeaudiodata(arraybuffer); parameters arraybuffer an arraybuffer containing the audio data to be decoded, usually grabbed from xmlhttprequest, windoworworkerglobalscope.fetch() or filereader. successcallback a callback function to be invoked when the decoding successfully finishes. the single argument to this callback is an audiobuffer representing the decodeddata (the decoded pcm audio data). usually you'll want to put the decoded data into an audiobuffersourcenode, from which it can be played and manipulated how you want. errorcallback an optional error callback, to be invoked if an error occurs when the audio data is being decoded. return value void, or a promise...
BaseAudioContext - Web APIs
s method only works on complete files, not fragments of audio files. examples basic audio context declaration: const audiocontext = new audiocontext(); cross browser variant: const audiocontext = window.audiocontext || window.webkitaudiocontext; const audiocontext = new audiocontext(); const oscillatornode = audiocontext.createoscillator(); const gainnode = audiocontext.creategain(); const finish = audiocontext.destination; specifications specification status comment web audio apithe definition of 'baseaudiocontext' in that specification. working draft ...
Body.arrayBuffer() - Web APIs
Web › API › Body › arrayBuffer
gg music track. we also use audiocontext.createbuffersource to create an audio buffer source. when the fetch is successful, we read an arraybuffer out of the response using arraybuffer(), decode the audio data using audiocontext.decodeaudiodata, set the decoded data as the audio buffer source's buffer (source.buffer), then connect the source up to the audiocontext.destination. ...
Basic animations - Web APIs
t original state. draw animated shapes the step where you do the actual frame rendering. restore the canvas state if you've saved the state, restore it before drawing a new frame. controlling an animation shapes are drawn to the canvas by using the canvas methods directly or by calling custom functions. in normal circumstances, we only see these results appear on the canvas when the script finishes executing. for instance, it isn't possible to do an animation from within a for loop. that means we need a way to execute our drawing functions over a period of time. there are two ways to control an animation like this. scheduled updates first there's the window.setinterval(), window.settimeout(), and window.requestanimationframe() functions, which can be used to call a specific function ov...
Basic usage of canvas - Web APIs
this function, or one like it, could also be called using window.settimeout(), window.setinterval(), or any other event handler, as long as the page has been loaded first. here is how a template would look in action. as shown here, it is initially blank. a simple example to begin, let's take a look at a simple example t...
Finale - Web APIs
Web › API › Canvas API › Tutorial › Finale
more examples and tutorials there are a variety of demos and further explanations about canvas on these sites: codepen.io front end developer playground & code editor in the browser. html5 canvas tutorials examples for most canvas apis. game development gaming is one of the most popular computer activities. new technologies are constantly arriving to make it possible to develop better and more powerful games that can be run in any standards-compliant web browser. ...
Using images - Web APIs
the other larger canvas. creating an image from scratch another option is to create new htmlimageelement objects in our script. to do this, you can use the convenient image() constructor: var img = new image(); // create new img element img.src = 'myimage.png'; // set source path when this script gets executed, the image starts loading. if you try to call drawimage() before the image has finished loading, it won't do anything (or, in older browsers, may even throw an exception). so you need to be sure to use the load event so you don't try this before the image has loaded: var img = new image(); // create new img element img.addeventlistener('load', function() { // execute drawimage statements here }, false); img.src = 'myimage.png'; // set source path if you're only using one ex...
Clipboard - Web APIs
Web › API › Clipboard
board, returning a promise. when the data has been retrieved, the promise is resolved with a datatransfer object that provides the data. readtext() requests text from the system clipboard; returns a promise which is resolved with a domstring containing the clipboard's text once it's available. write() writes arbitrary data to the system clipboard. this asynchronous operation signals that it's finished by resolving the returned promise. writetext() writes text to the system clipboard, returning a promise which is resolved once the text is fully copied into the clipboard. clipboard availability the asynchronous clipboard api is a relatively recent addition, and the process of implementing it in browsers is not yet complete. due to both potential security concerns and technical complexitie...
CredentialsContainer.get() - Web APIs
on for every visit to the website. valid values are "silent", "optional", or "required". unmediated: a boolean indicating the returned credential instance should not require user mediation. signal: an instance of abortsignal that can indicate that an ongoing get() operation should be halted. an aborted operation may complete normally (generally if the abort was received after the operation finished) or reject with an "aborterror" domexception. returns a promise that resolves with a credential instance that matches the provided parameters. if a single credential cannot be unambigiously obtained, the promise will resolve to null. specifications specification status comment credential management level 1the definition of 'get()' in that specification. worki...
DOMException - Web APIs
(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 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 ...
Document.close() - Web APIs
Web › API › Document › close
syntax document.close(); example // open a document to write to it document.open(); // write the content of the document document.write("<p>the one and only content.</p>"); // close the document document.close(); specifications specification status comment html living standardthe definition of 'document.close()' in that specification. ...
Document.exitFullscreen() - Web APIs
) requests that the element on this document which is currently being presented in full-screen mode be taken out of full-screen mode, restoring the previous state of the screen. this usually reverses the effects of a previous call to element.requestfullscreen(). syntax exitpromise = document.exitfullscreen(); parameters none. return value a promise which is resolved once the user agent has finished exiting full-screen mode. if an error occurs while attempting to exit full-screen mode, the catch() handler for the promise is called. example this example causes the current document to toggle in and out of a full-screen presentation whenever the mouse button is clicked within it. document.onclick = function (event) { if (document.fullscreenelement) { document.exitfullscreen() .
Document.fonts - Web APIs
Web › API › Document › fonts
t. syntax let fontfaceset = document.fonts; value the returned value is the fontfaceset interface of the document. the fontfaceset interface is useful for loading new fonts, checking the status of previously loaded fonts etc. examples doing operation after all fonts are loaded document.fonts.ready.then(function() { // any operation that needs to be done only after all the fonts // have finished loading can go here. }); specifications specification status comment css font loading module level 3the definition of 'fontfaceset' in that specification. working draft 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://gith...
Document: transitionend event - Web APIs
tion has completed. in the case where a transition is removed before completion, such as if the transition-property is removed or display is set to none, then the event will not be generated. bubbles yes cancelable yes interface transitionevent event handler property ontransitionend the transitionend event is fired in both directions - as it finishes transitioning to the transitioned state, and when it fully reverts to the default or non-transitioned state. if there is no transition delay or duration, if both are 0s or neither is declared, there is no transition, and none of the transition events are fired. if the transitioncancel event is fired, the transitionend event will not fire. the original target for this event is the element that ...
Document.write() - Web APIs
Web › API › Document › write
newcontent();"> <p>some original document content.</p> </body> </html> notes the text you write is parsed into the document's structure model. in the example above, the h1 element becomes a node in the document. writing to a document that has already loaded without calling document.open() will automatically call document.open(). after writing, call document.close() to tell the browser to finish loading the page. if the document.write() call is embedded within an inline html <script> tag, then it will not call document.open(). for example: <script> document.write("<h1>main title</h1>") </script> note: document.write() and document.writeln do not work in xhtml documents (you'll get an "operation is not supported" [ns_error_dom_not_supported_err] error in the error console). this hap...
EffectTiming.endDelay - Web APIs
the enddelay property of the effecttiming dictionary (part of the web animations api) indicates the number of milliseconds to delay after the active period of an animation sequence. the animation's end time—the time at which an iteration is considered to have finished—is the time at which the animation finishes an iteration (its initial delay, animationeffecttimingreadonly.delay, plus its duration,duration, plus its end delay. this is useful for sequencing animations based on the end time of another animation; note, however, that many of the sequence effectst that will benefit most from this property have not been defined in the specification yet. for now, its main purpose is to represent the value of the svg min attribute. element.animate(), keyframeeffectreadonly(), and keyfr...
Element: MSManipulationStateChanged event - Web APIs
it is a proprietary event specific to microsoft edge and internet explorer. bubbles unknown cancelable unknown interface msmanipulationevent event handler property unknown get manipulation states using the laststate and currentstate properties. ...
Element: compositionend event - Web APIs
the compositionend event is fired when a text composition system such as an input method editor completes or cancels the current composition session. for example, this event could be fired after a user finishes entering a chinese character using a pinyin ime. bubbles yes cancelable yes interface compositionevent event handler property none examples const inputelement = document.queryselector('input[type="text"]'); inputelement.addeventlistener('compositionend', (event) => { console.log(`generated characters were: ${event.data}`); }); live example html <div class="control"> <label for="name">on macos, click in the textbox below,<br> then type <kbd>option</kbd> + <kbd>`</kbd>, then <kbd>a</kbd>:</label> <input type="text" id="exa...
Element.getAnimations() - Web APIs
css pseudo-elements attached to element or one of its descendents. defaults to false. return value an array of animation objects, each representing an animation currently targetting the element on which this method is called, or one of its descendant elements if { subtree: true } is specified. examples the following code snippet will wait for all animations on elem and its descendants to finish before removing the element from the document. promise.all( elem.getanimations({ subtree: true }) .map(animation => animation.finished) ).then(() => elem.remove()); specifications specification status comment web animationsthe definition of 'animatable.getanimations()' in that specification. working draft editor's draft. ...
Event.eventPhase - Web APIs
Web › API › Event › eventPhase
mlelement, and so on through the elements until the target's parent is reached. event listeners registered for capture mode when eventtarget.addeventlistener() was called are triggered during this phase. event.at_target 2 the event has arrived at the event's target. event listeners registered for this phase are called at this time. if event.bubbles is false, processing the event is finished after this phase is complete. event.bubbling_phase 3 the event is propagating back up through the target's ancestors in reverse order, starting with the parent, and eventually reaching the containing window. this is known as bubbling, and occurs only if event.bubbles is true. event listeners registered for this phase are triggered during this process. for more details, see...
FileReader.readAsArrayBuffer() - Web APIs
at that time, the result attribute contains an arraybuffer representing the file's data. newer api available the blob.arraybuffer() method is a newer promise-based api to read a file as an array buffer. syntax instanceoffilereader.readasarraybuffer(blob); parameters blob the blob or file from which to read. ...
FileReader.readAsBinaryString() - Web APIs
at that time, the result attribute contains the raw binary data from the file. note that this method was once removed from the file api specification, but re-introduced for backward compatibility. using filereader.readasarraybuffer() is recommended. syntax instanceoffilereader.readasbinarystring(blob); parameters blob the blob or file from which to read. ...
FileReader.readAsDataURL() - Web APIs
at that time, the result attribute contains the data as a data: url representing the file's data as a base64 encoded string. note: the blob's result cannot be directly decoded as base64 without first removing the data-url declaration preceding the base64-encoded data. to retrieve only the base64 encoded string, first remove data:*/*;base64, from the result. syntax instanceoffilereader.readasdataurl(blob); parameters blob the blob or file from which to read. ...
File and Directory Entries API - Web APIs
synchronous file system calls. there are also two global functions (which are not part of the specification at this time and are implemented only by google chrome). they're available on the window object and implemented in localfilesystem: requestfilesystem() and resolvelocalfilesystemurl(). synchronous api the synchronous api is should only be used in workers; these calls block until they're finished executing, and simply return the results instead of using callbacks. using them on the main thread will block the browser, which is naughty. the interfaces below otherwise mirror the ones from the asynchronous api. filesystemsync represents a file system. filesystementrysync the basic interface representing a single entry in a file system. this is implemented by other interfaces which rep...
FontFaceSet - Web APIs
fontfaceset.ready read only promise which resolves once font loading and layout operations have completed. events fontfaceset.onloading an eventlistener called whenever an event of type loading is fired, indicating a font-face set has started loading. fontfaceset.onloadingdone an eventlistener called whenever an event of type loadingdone is fired, indicating that a font face set has finished loading. fontfaceset.onloadingerror an eventlistener called whenever an event of type loadingerror is fired, indicating that an error occurred whilst loading a font-face set. methods fontfaceset.add() adds a font to the font set. fontfaceset.check() a boolean that indicates whether a font is loaded, but doesn't initiate a load when it isn't. fontfaceset.clear() removes all manually-...
GlobalEventHandlers.onloadeddata - Web APIs
the onloadeddata property of the globaleventhandlers mixin is the eventhandler for processing loadeddata events. the loadeddata event is fired when the first frame of the media has finished loading. syntax element.onloadeddata = handlerfunction; var handlerfunction = element.onloadeddata; handlerfunction is either null or a javascript function specifying the handler for the event. specification specification status comment html living standardthe definition of 'onloadeddata' in that specification. living standard ...
GlobalEventHandlers.onloadend - Web APIs
ce's loadend event fires. examples html content <img src="myimage.jpg"> javascript content // 'loadstart' fires first, then 'load', then 'loadend' image.addeventlistener('load', function(e) { console.log('image loaded'); }); image.addeventlistener('loadstart', function(e) { console.log('image load started'); }); image.addeventlistener('loadend', function(e) { console.log('image load finished'); }); ...
GlobalEventHandlers.onloadstart - Web APIs
's loadstart event fires. examples html content <img src="myimage.jpg"> javascript content // 'loadstart' fires first, then 'load', then 'loadend' image.addeventlistener('load', function(e) { console.log('image loaded'); }); image.addeventlistener('loadstart', function(e) { console.log('image load started'); }); image.addeventlistener('loadend', function(e) { console.log('image load finished'); }); specifications specification status comment html living standardthe definition of 'onloadstart' in that specification. living standard initial definition ...
GlobalEventHandlers - Web APIs
.ontouchstart is an eventhandler representing the code to be called when the touchstart event is raised. globaleventhandlers.ontransitioncancel an eventhandler called when a transitioncancel event is sent, indicating that a css transition has been cancelled. globaleventhandlers.ontransitionend an eventhandler called when a transitionend event is sent, indicating that a css transition has finished playing. globaleventhandlers.ontransitionrun an eventhandler called when a transitionrun event is sent, indicating that a css transition is running, though not nessarilty started. globaleventhandlers.ontransitionstart an eventhandler called when a transitionstart event is sent, indicating that a css transition has started transitioning. globaleventhandlers.onwaiting is an eventhandler rep...
HTMLCanvasElement - Web APIs
llback is a function that is initially null. web content can set this to a javascript function that will be called when the canvas is to be redrawn while the page is being printed. when called, the callback is passed a "printstate" object that implements the mozcanvasprintstate interface. the callback can get the context to draw to from the printstate object and must then call done() on it when finished. the purpose of mozprintcallback is to obtain a higher resolution rendering of the canvas at the resolution of the printer being used. see this blog post. methods inherits methods from its parent, htmlelement. htmlcanvaselement.capturestream() returns a canvascapturemediastream that is a real-time video capture of the surface of the canvas. htmlcanvaselement.getcontext() returns a dr...
HTMLFormElement - Web APIs
submit button and its corresponding configuration. reset() resets the form to its initial state. submit() submits the form to the server. deprecated methods htmlformelement.requestautocomplete() triggers a native browser interface to assist the user in completing the fields which have an autofill field name value that is not off or on. the form will receive an event once the user has finished with the interface, the event will either be autocomplete when the fields have been filled or autocompleteerror when there was a problem. events listen to these events using addeventlistener(), or by assigning an event listener to the oneventname property of this interface. formdata the formdata event fires after the entry list representing the form's data is constructed. also available...
HTMLImageElement.alt - Web APIs
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. ...
HTMLImageElement - Web APIs
eters, new image() is equivalent to calling document.createelement("img"). properties inherits properties from its parent, htmlelement. htmlimageelement.alt a domstring that reflects the alt html attribute, thus indicating the alternate fallback content to be displayed if the image has not been loaded. htmlimageelement.complete read only returns a boolean that is true if the browser has finished fetching the image, whether successful or not. that means this value is also true if the image has no src value indicating an image to load. htmlimageelement.crossorigin a domstring specifying the cors setting for this image element. see cors settings attributes for further details. this may be null if cors is not used. htmlimageelement.currentsrc read only returns a usvstring representing...
HTMLMarqueeElement - Web APIs
re ignored. if truespeed is true, then those values are not ignored. htmlmarqueeelement.vspace sets the vertical margin. htmlmarqueeelement.width sets the width in pixels or percentage value. event handlers htmlmarqueeelement.onbounce fires when the marquee has reached the end of its scroll position. it can only fire when the behavior attribute is set to alternate. htmlmarqueeelement.onfinish fires when the marquee has finished the amount of scrolling that is set by the loop attribute. it can only fire when the loop attribute is set to some number that is greater than 0. htmlmarqueeelement.onstart fires when the marquee starts scrolling. methods inherits methods from its parent, htmlelement. htmlmarqueeelement.start() starts scrolling of the marquee. htmlmarqueeelement.stop...
HTMLMediaElement.ended - Web APIs
if the source of the media is a mediastream, this value is true if the value of the stream's active property is false. ...
HTMLMediaElement: loadeddata event - Web APIs
bubbles no cancelable no interface event target element default action none event handler property globaleventhandlers.onloadeddata specification html5 media note that this event will not fire in mobile/tablet devices if data-saver is on in browser settings. examples these examples add an event listener for the htmlmediaelement's loadeddata event, then post a message when that event handler has reacted to the event firing. ...
HTMLScriptElement - Web APIs
l how the script should be executed. the defer and async attributes must not be specified if the src attribute is absent. there are three possible execution modes: if the async attribute is present, then the script will be executed asynchronously as soon as it downloads. if the async attribute is absent but the defer attribute is present, then the script is executed when the page has finished parsing. if neither attribute is present, then the script is fetched and executed immediately, blocking further parsing of the page. the defer attribute may be specified with the async attribute, so legacy browsers that only support defer (and not async) fall back to the defer behavior instead of the default blocking behavior. note: the exact processing details for these attributes ...
Using microtasks in JavaScript with queueMicrotask() - Web APIs
row gives the results shown in the table below: results when data isn't cached (left) vs. when it is found in the cache data isn't cached data is cached fetching data data fetched loaded data fetching data loaded data data fetched even worse, sometimes the element's data property will be set and other times it won't be by the time this code finishes running. we can ensure consistent ordering of these operations by using a microtask in the if clause to balance the two clauses: customelement.prototype.getdata = url => { if (this.cache[url]) { queuemicrotask(() => { this.data = this.cache[url]; this.dispatchevent(new event("load")); }); } else { fetch(url).then(result => result.arraybuffer()).then(data => { ...
IDBDatabase.transaction() - Web APIs
duplicate items not allowed.</li>'; }; // you would then go on to do something to this database // via an object store var objectstore = transaction.objectstore("todolist"); // etc. specification specification status comment indexed database api 2.0the def...
IDBDatabaseException - Web APIs
a 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 with a version lower than the one it already has. this can only happen with idbopendbrequest. browser compatibility the compatibility table on t...
IDBObjectStore.index() - Web APIs
ers. syntax var index = objectstore.index(name); parameters name the name of the index to open. return value an idbindex object for accessing the index. exceptions this method may raise a domexception of one of the following types: exception description invalidstateerror the source object store has been deleted, or the transaction for the object store has finished. notfounderror there is no index with the given name (case-sensitive) in the database. example in the following example we open a transaction and an object store, then get the index lname from a simple contacts database. we then open a basic cursor on the index using idbindex.opencursor — this works the same as opening a cursor directly on an objectstore using idbobj...
IDBTransaction.abort() - Web APIs
duplicate items not allowed.</li>'; }; // create an object store on the transaction var objectstore = transaction.objectstore("todolist"); // add our newitem object to the object store var objectstorerequest = objectstore.add(newitem[0]); objectstorerequest.ons...
IDBTransaction.commit() - Web APIs
exception description invalidstateerror the transaction state is not active. examples // open a read/write db transaction, ready for adding the data var transaction = db.transaction(["mydb"], "readwrite"); // report on the success of opening the transaction transaction.oncomplete = function(event) { note.innerhtml += '<li>transaction completed: database modification finished.</li>'; }; transaction.onerror = function(event) { note.innerhtml += '<li>transaction not opened due to error. duplicate items not allowed.</li>'; }; // create an object store on the transaction var objectstore = transaction.objectstore("myobjstore"); // add our newitem object to the object store var objectstorerequest = objectstore.add(newitem[0]); objectstorerequest.onsuccess = function...
IDBTransaction.db - Web APIs
Web › API › IDBTransaction › db
duplicate items not allowed.</li>'; }; // create an object store on the transaction var objectstore = transaction.objectstore("todolist"); // add our newitem object to the object store var objectstorerequest = objectstore.add(newitem[0]); objectstorerequest.onsu...
IDBTransaction.mode - Web APIs
duplicate items not allowed.</li>'; }; // create an object store on the transaction var objectstore = transaction.objectstore("todolist"); // add our newitem object to the object store var objectstorerequest = objectstore.add(newitem[0]); objectstorerequest.onsu...
IDBTransaction.onabort - Web APIs
e: "walk dog", hours: 19, minutes: 30, day: 24, month: "december", year: 2013, notified: "no" } ]; // open a read/write db transaction, ready for adding the data var transaction = db.transaction(["todolist"], "readwrite"); // report on the success of opening the transaction transaction.oncomplete = function(event) { note.innerhtml += '<li>transaction completed: database modification finished.</li>'; }; transaction.onerror = function(event) { note.innerhtml += '<li>transaction not opened due to error: ' + transaction.error + '</li>'; }; // create an object store on the transaction var objectstore = transaction.objectstore("todolist"); // add our newitem object to the object store var objectstorerequest = objectstore.add(newitem[0]); objectstorerequest.onsucce...
IDBTransaction.oncomplete - Web APIs
e: "walk dog", hours: 19, minutes: 30, day: 24, month: "december", year: 2013, notified: "no" } ]; // open a read/write db transaction, ready for adding the data var transaction = db.transaction(["todolist"], "readwrite"); // report on the success of opening the transaction transaction.oncomplete = function(event) { note.innerhtml += '<li>transaction completed: database modification finished.</li>'; }; transaction.onerror = function(event) { note.innerhtml += '<li>transaction not opened due to error: ' + transaction.error + '</li>'; }; // create an object store on the transaction var objectstore = transaction.objectstore("todolist"); // add our newitem object to the object store var objectstorerequest = objectstore.add(newitem[0]); objectstorerequest.onsucce...
IDBTransaction.onerror - Web APIs
e: "walk dog", hours: 19, minutes: 30, day: 24, month: "december", year: 2013, notified: "no" } ]; // open a read/write db transaction, ready for adding the data var transaction = db.transaction(["todolist"], "readwrite"); // report on the success of opening the transaction transaction.oncomplete = function(event) { note.innerhtml += '<li>transaction completed: database modification finished.</li>'; }; transaction.onerror = function(event) { note.innerhtml += '<li>transaction not opened due to error: ' + transaction.error + '</li>'; }; // create an object store on the transaction var objectstore = transaction.objectstore("todolist"); // add our newitem object to the object store var objectstorerequest = objectstore.add(newitem[0]); objectstorerequest.onsucc...
IdleDeadline.timeRemaining() - Web APIs
the timeremaining() method on the idledeadline interface returns the estimated number of milliseconds remaining in the current idle period. the callback can call this method at any time to determine how much time it can continue to work before it must return. for example, if the callback finishes a task and has another one to begin, it can call timeremaining() to see if there's enough time to complete the next task. if there isn't, the callback can just return immediately, or look for other work to do with the remaining time. by the time timeremaining() reaches 0, it is suggested that the callback should return control to the user agent's event loop. syntax timeremaining = idledeadline.timeremaining(); return value a domhighrestimestamp value (which is a floating-point number) represent...
Basic concepts - Web APIs
under the definitions section. the indexeddb api is mostly asynchronous. the api doesn't give you data by returning values; instead, you have to pass a callback function. you don't "store" a value into the database, or "retrieve" a value out of the database through synchronous means. instead, you "request" that a database operation happens. you get notified by a dom event when the operation finishes, and the type of event you get lets you know if the operation succeeded or failed. this sounds a little complicated at first, but there are sanity measures baked in. it's not that different from the way that xmlhttprequest works. indexeddb uses a lot of requests. requests are objects that receive the success or failure dom events that were mentioned previously. they have onsuccess and one...
Intersection Observer API - Web APIs
atio" in this string will be replaced with the target's current visibility ratio, so that the element not only changes color but also becomes increasingly opaque as it becomes less obscured. decreasingcolor similarly, this is a string defining a color we'll apply when the visibility ratio is decreasing. we call window.addeventlistener() to start listening for the load event; once the page has finished loading, we get a reference to the element with the id "box" using queryselector(), then call the createobserver() method we'll create in a moment to handle building and installing the intersection observer. creating the intersection observer the createobserver() method is called once page load is complete to handle actually creating the new intersectionobserver and starting the process of ob...
MediaStream.ended - Web APIs
Web › API › MediaStream › ended
olean value which is true if the stream has been completely read, or false if the end of the stream has not been reached. this value once the ended event has been fired. this property has been removed from the specification; you should instead rely on the ended event or check the value of mediastreamtrack.readystate to see if its value is "ended" for the track or tracks you want to ensure have finished playing. syntax var hasended = mediastream.ended; value a boolean value that returns true if the end of the stream has been reached. specifications no longer part of any specification. this property was part of earlier drafts of the media capture and streams specification. ...
MediaStream - Web APIs
eam.active read only a boolean value that returns true if the mediastream is active, or false otherwise. mediastream.ended read only a boolean value set to true if the end of the stream has been reached. this has been removed from the specification; you should instead check the value of mediastreamtrack.readystate to see if its value is ended for the track or tracks you want to ensure have finished playing. mediastream.id read only a domstring containing 36 characters denoting a universally unique identifier (uuid) for the object. event handlers mediastream.onaddtrack an eventhandler containing the action to perform when an addtrack event is fired when a new mediastreamtrack object is added. mediastream.onremovetrack an eventhandler containing the action to perform when a re...
MediaStream Recording API - Web APIs
about using the mediastream recording api, see using the mediastream recording api, which shows how to use the api to record audio clips. a second article, recording a media element, describes how to receive a stream from an <audio> or <video> element and use the captured stream (in this case, recording it and saving it to a local disk). reference blobevent each time a chunk of media data is finished being recorded, it's delivered to consumers in blob form using a blobevent of type dataavailable. mediarecorder the primary interface that implements the mediastream recording api. mediarecordererrorevent the interface that represents errors thrown by the mediastream recording api. its error property is a domexception that specifies that error occurred. specifications specificat...
Navigation Timing API - Web APIs
deventend). this gives you the perceived page load time. calculate request response time you can calculate the time elapsed between the beginning of a request and the completion of getting the response using code like this: const connecttime = perfdata.responseend - perfdata.requeststart; here, the time at which the request was initiated (requeststart). from the time at which the response was finished being received (responseend). calculate page render time as another example of an interesting piece of data you can obtain using the navigation timing api that you can't otherwise easily get, you can get the amount of time it took to render the page: const rendertime = perfdata.domcomplete - perfdata.domloading; this is obtained by starting with the time at which loading of the dom and its ...
OfflineAudioContext.startRendering() - Web APIs
browsers currently support two versions of the startrendering() method — an older event-based version and a newer promise-based version. ...
OffscreenCanvas - Web APIs
ained in the canvas. offscreencanvas.transfertoimagebitmap() creates an imagebitmap object from the most recently rendered image of the offscreencanvas. examples synchronous display of frames produced by an offscreencanvas one way to use the offscreencanvas api, is to use a renderingcontext that has been obtained from an offscreencanvas object to generate new frames. once a new frame has finished rendering in this context, the transfertoimagebitmap() method can be called to save the most recent rendered image. this method returns an imagebitmap object, which can be used in a variety of web apis and also in a second canvas without creating a transfer copy. to display the imagebitmap, you can use a imagebitmaprenderingcontext context, which can be created by calling canvas.getcontext("b...
Page Visibility API - Web APIs
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 this throttling behavior. in these cases, you can use the page visibility api to reduce the tabs' performance impact while they're hidden. tabs which are playing audio are co...
PerformanceNavigationTiming - Web APIs
the response from relevant application caches, or from local resources or from the server. performancenavigationtiming.type read only a string representing the navigation type. must be: "navigate", "reload", "back_forward" or "prerender". performancenavigationtiming.unloadeventend read only a domhighrestimestamp representing the time value equal to the time immediately after the user agent finishes the unload event of the previous document. performancenavigationtiming.unloadeventstart read only a domhighrestimestamp representing the time value equal to the time immediately before the user agent starts the unload event of the previous document. methods performancenavigationtiming.tojson() returns a domstring that is the json representation of the performancenavigationtiming object...
PerformanceResourceTiming.connectEnd - Web APIs
the timestamp value includes the time interval to establish the transport connection, as well as other time intervals such as ssl handshake and socks authentication. note: this feature is available in web workers. syntax resource.connectend; return value a domhighrestimestamp representing the time after a connection is established. example in the following example, the value of the *start and *end properties of all "resource" type events are logged. ...
PerformanceTiming.domComplete - Web APIs
this interface of this property is deprecated in the navigation timing level 2 specification. please use the performancenavigationtiming interface instead. the legacy performancetiming.domcomplete read-only property returns an unsigned long long representing the moment, in miliseconds since the unix epoch, when the parser finished its work on the main document, that is when its document.readystate changes to 'complete' and the corresponding readystatechange event is thrown. syntax time = performancetiming.domcomplete; specifications specification status comment navigation timingthe definition of 'performancetiming.domcomplete' in that specification. recommendation initial definition. ...
PerformanceTiming.domInteractive - Web APIs
this interface of this property is deprecated in the navigation timing level 2 specification. please use the performancenavigationtiming interface instead. the legacy performancetiming.dominteractive read-only property returns an unsigned long long representing the moment, in miliseconds since the unix epoch, when the parser finished its work on the main document, that is when its document.readystate changes to 'interactive' and the corresponding readystatechange event is thrown. this property can be used to measure the speed of loading web sites that users feels. nevertheless there are a few caveats that happens if scripts are blocking rendering and not loaded asynchronously or with custom web fonts. check if you are in one of these cases before using this property as a proxy for the user ...
PerformanceTiming.domainLookupEnd - Web APIs
this interface of this property is deprecated in the navigation timing level 2 specification. please use the performancenavigationtiming interface instead. the legacy performancetiming.domainlookupend read-only property returns an unsigned long long representing the moment, in miliseconds since the unix epoch, where the domain lookup is finished. if a persistent connection is used, or the information is stored in a cache or a local resource, the value will be the same as performancetiming.fetchstart. syntax time = performancetiming.domainlookupend; specifications specification status comment navigation timingthe definition of 'performancetiming.domainlookupend' in that specification. recommendation initial definition. ...
PerformanceTiming.unloadEventEnd - Web APIs
this interface of this property is deprecated in the navigation timing level 2 specification. please use the performancenavigationtiming interface instead. the legacy performancetiming.unloadeventend read-only property returns an unsigned long long representing the moment, in miliseconds since the unix epoch, the unload event handler finishes. if there is no previous document, or if the previous document, or one of the needed redirects, is not of the same origin, the value returned is 0. syntax time = performancetiming.unloadeventend; specifications specification status comment navigation timingthe definition of 'performancetiming.unloadeventend' in that specification. recommendation initial definition. ...
RTCDTMFSender.ontonechange - Web APIs
to the rtcdtmfsender each time a tone begins or ends. the event handler receives as input a single parameter of type rtcdtmftonechangeevent, which describes the change. syntax rtcdtmfsender.ontonechange = tonechangehandlerfunction; value a function which is called when a tonechange event is sent to the rtcdtmfsender, indicating that a dtmf tone has either started playing, or if all tones have finished playing. example tbd specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'ontonechange' in that specification. candidate recommendation ...
RTCDTMFToneChangeEvent.tone - Web APIs
syntax var tone = dtmftonechangeevent.tone; example this example establishes a handler for the tonechange event which updates an element to display the currently playing tone in its content, or, if all tones have played, the string "<none>". ...
RTCDataChannel.close() - Web APIs
the sequence of events which occurs in response to this method being called: rtcdatachannel.readystate is set to "closing". ...
RTCDataChannel.send() - Web APIs
in using webrtc data channels. syntax rtcdatachannel.send(data); parameters data the data to transmit across the connection. this may be a usvstring, a blob, an arraybuffer, or an arraybufferview. return value undefined. exceptions invalidstateerror since the data channel uses a separate transport channel from the media content, it must establish its own connection; if it hasn't finished doing so (that is, its readystate is "connecting"), this error occurs without sending or buffering the data. networkerror the specified data would need to be buffered, and there isn't room for it in the buffer. in this scenario, the underlying transport is immediately closed. typeerror the specified data is too large for the other peer to receive. since there are multiple techniques for bre...
RTCIceGathererState - Web APIs
the rtcicegathererstate enumerated type provides the string values which can be returned by an rtcicetransport object's gatheringstate. values "new" the rtcicetransport is newly created and has not yet started to gather ice candidates. "gathering" the transport is in the process of gathering candidates. "complete" the transport has finished gathering ice candidates and has sent the end-of-candidates indicator to the remote device. the transport won't gather any further candidates unless an ice restart occurs, at which point the gathering process starts over from scratch. specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcicegathererstate' in that specification. candidate recommendation i...
RTCIceTransport.gatheringState - Web APIs
tax gatherstate = rtcicetransport.gatheringstate; value a string from the rtcicegathererstate enumerated type whose value indicates the current state of the ice agent's candidate gathering process: "new" the rtcicetransport is newly created and has not yet started to gather ice candidates. "gathering" the transport is in the process of gathering candidates. "complete" the transport has finished gathering ice candidates and has sent the end-of-candidates indicator to the remote device. the transport won't gather any further candidates unless an ice restart occurs, at which point the gathering process starts over from scratch. specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcicetransport.gath...
RTCIceTransport.ongatheringstatechange - Web APIs
sport's gatheringstate property changes. syntax rtcicetransport.ongatheringstatechange = statechangehandler; value a function to be called when the rtcicetransport object's gathering state changes. to determine the new state, examine the value of gatheringstate. the gathering state indicates whether or not the ice agent has begun gathering candidates, and if so, whether or not gathering has finished. its possible values are: "new" the rtcicetransport is newly created and has not yet started to gather ice candidates. "gathering" the transport is in the process of gathering candidates. "complete" the transport has finished gathering ice candidates and has sent the end-of-candidates indicator to the remote device. the transport won't gather any further candidates unless an ice restart...
RTCPeerConnection.currentLocalDescription - Web APIs
also included is a list of any ice candidates that may already have been generated by the ice agent since the offer or answer represented by the description was first instantiated. ...
RTCPeerConnection.currentRemoteDescription - Web APIs
also included is a list of any ice candidates that may already have been generated by the ice agent since the offer or answer represented by the description was first instantiated. ...
RTCPeerConnection.iceConnectionState - Web APIs
ll underway. "connected" a usable pairing of local and remote candidates has been found for all components of the connection, and the connection has been established. it's possible that gathering is still underway, and it's also possible that the ice agent is still checking candidates against one another looking for a better connection to use. "completed" the ice agent has finished gathering candidates, has checked all pairs against one another, and has found a connection for all components. "failed" the ice candidate has checked all candidates pairs against one another and has failed to find compatible matches for all components of the connection. it is, however, possible that the ice agent did find compatible connections for some components. "discon...
RTCPeerConnection.onicecandidate - Web APIs
icecandidate = eventhandler; value this should be set to a function which you provide that accepts as input an rtcpeerconnectioniceevent object representing the icecandidate event. the function should deliver the ice candidate, whose sdp can be found in the event's candidate property, to the remote peer through the signaling server. if the event's candidate property is null, ice gathering has finished. this message should not be sent to the remote peer. when this happens, the connection's icegatheringstate has also changed to complete. you don't need to watch for this explicitly; instead, if you need to sense the end of signaling, you should watch for a icegatheringstatechange event indicating that the ice negotiation has transitioned to the complete state. example the example below, which...
RTCPeerConnection: signalingstatechange event - Web APIs
ngstate property, has changed. bubbles no cancelable no interface event event handler property rtcpeerconnection.onsignalingstatechange examples given an rtcpeerconnection, pc, and an updatestatus() function that presents status information to the user, this code sets up an event handler to let the user know when the ice negotiation process finishes up. pc.addeventlistener("signalingstatechange", ev => { switch(pc.signalingstate) { case "stable": updatestatus("ice negotiation complete"); break; } }, false); using onsignalingstatechange, it looks like this: pc.onsignalingstatechange = ev => { switch(pc.signalingstate) { case "stable": updatestatus("ice negotiation complete"); break; } }; specif...
ReadableStream.getReader() - Web APIs
"byob" or undefined. typeerror the stream you are trying to create a reader for is not a readablestream. examples in the following simple example, a previously-created custom readablestream is read using a readablestreamdefaultreader created using getreader(). (see our simple random stream example for the full code). each chunk is read sequentially and output to the ui, until the stream has finished being read, at which point we return out of the recursive function and print the entire stream to another part of the ui. function fetchstream() { const reader = stream.getreader(); let charsreceived = 0; // read() returns a promise that resolves // when a value has been received reader.read().then(function processtext({ done, value }) { // result objects contain two properties:...
ReadableStream - Web APIs
onst reader = response.body.getreader(); const stream = new readablestream({ start(controller) { // the following function handles each data chunk function push() { // "done" is a boolean and value a "uint8array" reader.read().then(({ done, value }) => { // is there no more data to read? ...
ReadableStreamBYOBReader.releaseLock() - Web APIs
ter the lock is released, the reader is no longer active. if the associated stream is errored when the lock is released, the reader will appear errored in that same way subsequently; otherwise, the reader will appear closed. a reader’s lock cannot be released while it still has a pending read request, i.e., if a promise returned by the reader’s readablestreambyobreader.read() method has not finished. this will result in a typeerror being thrown. syntax readablestreambyobreader.releaselock(); parameters none. return value undefined. exceptions typeerror the source object is not a readablestreambyobreader, or a read request is pending. examples tbd. specifications specification status comment streamsthe definition of 'releaselock()' in that specificati...
ReadableStreamDefaultReader.ReadableStreamDefaultReader() - Web APIs
e supplied stream parameter is not a readablestream, or it is already locked for reading by another reader. examples in the following simple example, a previously-created custom readablestream is read using a readablestreamdefaultreader created using getreader(). (see our simple random stream example for the full code). each chunk is read sequentially and output to the ui, until the stream has finished being read, at which point we return out of the recursive function and print the entire stream to another part of the ui. function fetchstream() { const reader = stream.getreader(); let charsreceived = 0; // read() returns a promise that resolves // when a value has been received reader.read().then(function processtext({ done, value }) { // result objects contain two properties:...
ReadableStreamDefaultReader.read() - Web APIs
t try to deal with complications like stream chunks not ending on line boundaries for example. in this example stream is a previously-created custom readablestream. it is read using a readablestreamdefaultreader created using getreader(). (see our simple random stream example for the full code). each chunk is read sequentially and output to the ui as an array of utf-8 bytes, until the stream has finished being read, at which point we return out of the recursive function and print the entire stream to another part of the ui. function fetchstream() { const reader = stream.getreader(); let charsreceived = 0; // read() returns a promise that resolves // when a value has been received reader.read().then(function processtext({ done, value }) { // result objects contain two properties:...
ReadableStreamDefaultReader.releaseLock() - Web APIs
er interface releases the reader's lock on the stream. if the associated stream is errored when the lock is released, the reader will appear errored in that same way subsequently; otherwise, the reader will appear closed. a reader’s lock cannot be released while it still has a pending read request, i.e., if a promise returned by the reader’s readablestreamdefaultreader.read() method has not finished. this will result in a typeerror being thrown. syntax readablestreamdefaultreader.releaselock(); parameters none. return value undefined. exceptions typeerror the source object is not a readablestreamdefaultreader, or a read request is pending. examples function fetchstream() { const reader = stream.getreader(); ... reader.releaselock() ... } specifications s...
ReadableStreamDefaultReader - Web APIs
ader = response.body.getreader(); const stream = new readablestream({ start(controller) { // the following function handles each data chunk function push() { // "done" is a boolean and value a "uint8array" return reader.read().then(({ done, value }) => { // is there no more data to read? ...
ServiceWorkerContainer - Web APIs
th a serviceworkercontainer in an array. the method returns a promise that resolves to an array of serviceworkerregistration. serviceworkercontainer.startmessages() explicitly starts the flow of messages being dispatched from a service worker to pages under its control (e.g. sent via client.postmessage()). this can be used to react to sent messages earlier, even before that page's content has finished loading. examples the example below first checks to see if the browser supports service workers. if supported, the code registers the service worker and determines if the page is actively controlled by the service worker. if it isn't, it prompts the user to reload the page so the service worker can take control. the code also reports any registration failures. if ('serviceworker' in navigat...
ServiceWorkerRegistration.unregister() - Web APIs
() method of the serviceworkerregistration interface unregisters the service worker registration and returns a promise. the promise will resolve to false if no registration was found, otherwise it resolves to true irrespective of whether unregistration happened or not (it may not unregister if someone else just called serviceworkercontainer.register() with the same scope.) the service worker will finish any ongoing operations before it is unregistered. note: this feature is available in web workers. syntax serviceworkerregistration.unregister().then(function(boolean) { }); parameters none. return value promise resolves with a boolean indicating whether the service worker has unregistered or not. example the following simple example registers a service worker example, but then immediat...
ServiceWorkerRegistration - Web APIs
lves to an array of notification objects. serviceworkerregistration.shownotification() displays the notification with the requested title. serviceworkerregistration.update() checks the server for an updated version of the service worker without consulting caches. serviceworkerregistration.unregister() unregisters the service worker registration and returns a promise. the service worker will finish any ongoing operations before it is unregistered. examples in this example, the code first checks whether the browser supports service workers and if so registers one. next, it adds an updatefound listener in which it uses the service worker registration to listen for further changes to the service worker's state. if the service worker hasn't changed since the last time it was registered, then...
SpeechRecognition: audioend event - Web APIs
the audioend event of the web speech api is fired when the user agent has finished capturing audio for speech recognition. bubbles no cancelable no interface event event handler onaudioend examples you can use the audioend event in an addeventlistener method: var recognition = new webkitspeechrecognition() || new speechrecognition(); recognition.addeventlistener('audioend', function() { console.log('audio capturing ended'); }); or use the onaudioend event handler property: recognition.onaudioend = function() { console.log('audio capturing ended'); } specifications specification status comment web speech apithe definition of 'speech recognition events' in that specification. draft ...
SpeechRecognition.onaudioend - Web APIs
the onaudioend property of the speechrecognition interface represents an event handler that will run when the user agent has finished capturing audio (when the audioend event fires.) syntax myspeechrecognition.onaudioend = function() { ... }; examples var recognition = new speechrecognition(); recognition.onaudioend = function() { console.log('audio capturing ended'); } specifications specification status comment web speech apithe definition of 'onaudioend' in that specification. draft ...
SpeechRecognition - Web APIs
to incoming audio, and attempts to return a speechrecognitionresult using the audio captured so far. events listen to these events using addeventlistener() or by assigning an event listener to the oneventname property of this interface. audiostart fired when the user agent has started to capture audio. also available via the onaudiostart property. audioend fired when the user agent has finished capturing audio. also available via the onaudioend property. end fired when the speech recognition service has disconnected. also available via the onend property. error fired when a speech recognition error occurs. also available via the onerror property. nomatch fired when the speech recognition service returns a final result with no significant recognition. this may involve some deg...
SpeechSynthesisUtterance - Web APIs
. speechsynthesisutterance.volume gets and sets the volume that the utterance will be spoken at. events listen to these events using addeventlistener() or by assigning an event listener to the oneventname property of this interface. boundary fired when the spoken utterance reaches a word or sentence boundary. also available via the onboundary property. end fired when the utterance has finished being spoken. also available via the onend property. error fired when an error occurs that prevents the utterance from being succesfully spoken. also available via the onerror property mark fired when the spoken utterance reaches a named ssml "mark" tag. also available via the onmark property. pause fired when the utterance is paused part way through. also available via the onpause pr...
Using readable streams - Web APIs
in our example we are using the controller’s enqueue() method to enqueue a value into the custom stream after it is read from the fetch body. in addition, when we are done reading the fetch body we use the controller’s close() method to close the custom stream — any previously-enqueued chunks can still be read from it, but no more can be enqueued, and the stream is closed when reading has finished. reading from custom streams in our simple stream pump example, we consume the custom readable stream by passing it into a response constructor call, after which we consume it as a blob(). .then(stream => new response(stream)) .then(response => response.blob()) .then(blob => url.createobjecturl(blob)) .then(url => console.log(image.src = url)) .catch(err => console.error(err)); but a custom...
Streams API - Web APIs
uld then be passed to a windoworworkerglobalscope.fetch() to commence fetching the stream. body the response body returned by a successful fetch request is exposed by default as a readablestream, and can have a reader attached to it, etc. bytestream-related interfaces important: these are not implemented anywhere as yet, and questions have been raised as to whether the spec details are in a finished enough state for them to be implemented. this may change over time. readablestreambyobreader represents a byob ("bring your own buffer") reader that can be used to read stream data supplied by the developer (e.g. a custom readablestream() constructor). readablebytestreamcontroller represents a controller allowing control of a readablestream's state and internal queue. byte stream control...
TextTrack.mode - Web APIs
Web › API › TextTrack › mode
by the user agent or the web site or web app to construct and present an interface for navigating the named chapters, where each cue in the list represents a chapter in the media. the user can then navigate to the desired chapter, which begins at the cue's start position and ends at the cue's end position. example in this example, we configure the text track's cues so that every time a cue is finished, the video automatically pauses playback. this is done by setting the pauseonexit property on each cue to true. however, to ensure that the track's cues are available, we first set mode to showing. window.addeventlistener("load", event => { let trackelem = document.queryselector("track"); let track = trackelem.track; track.mode = "showing"; for (let index=0; index < track.cues.length...
TransitionEvent - Web APIs
rty. transitionevent.pseudoelement read only is a domstring, starting with ::, containing the name of the pseudo-element the animation runs on. if the transition doesn't run on a pseudo-element but on the element, an empty string: ''. types of transitionevent transitioncancel an event fired when a css transition has been cancelled. transitionend an event fired when a css transition has finished playing. transitionrun an event fired when a css transition is created, when it is added to a set of running transitions, though not nessarilty started transitionstart an event fired when a css transition has started transitioning. methods also inherits properties from its parent event. transitionevent.inittransitionevent() initializes a transitionevent created using the deprecate...
URL.revokeObjectURL() - Web APIs
note: this feature is available in web workers. note: this method is not available from service workers, due to issues with the blob interface's life cycle and the potential for leaks. syntax url.revokeobjecturl(objecturl) parameters objecturl a domstring representing a object url that was previously created by calling createobjecturl(). ...
WebGLRenderingContext - Web APIs
ingcontext.vertexattribpointer() specifies the data formats and locations of vertex attributes in a vertex attributes array. drawing buffers webglrenderingcontext.clear() clears specified buffers to preset values. webglrenderingcontext.drawarrays() renders primitives from array data. webglrenderingcontext.drawelements() renders primitives from element array data. webglrenderingcontext.finish() blocks execution until all previously called commands are finished. webglrenderingcontext.flush() empties different buffer commands, causing all commands to be executed as quickly as possible. working with extensions these methods manage webgl extensions: webglrenderingcontext.getsupportedextensions() returns an array of domstring elements with all the supported webgl extensions. web...
WebGLShader - Web APIs
the webglshader is part of the webgl api and can either be a vertex or a fragment shader. a webglprogram requires both types of shaders. description to create a webglshader use webglrenderingcontext.createshader, then hook up the glsl source code using webglrenderingcontext.shadersource(), and finally invoke webglrenderingcontext.compileshader() to finish and compile the shader. at this point the webglshader is still not in a usable form and must still be attached to a webglprogram. function createshader (gl, sourcecode, type) { // compiles either a shader of type gl.vertex_shader or gl.fragment_shader var shader = gl.createshader( type ); gl.shadersource( shader, sourcecode ); gl.compileshader( shader ); if ( !gl.getshaderparameter(shader, gl.compile_status) ) { var info = gl...
WebRTC connectivity - Web APIs
: host a host candidate is one for which its ip address is the actual, direct ip address of the remote peer. prflx a peer reflexive candidate is one whose ip address comes from a symmetric nat between the two peers, usually as an additional candidate during trickle ice (that is, additional candidate exchanges that occur after primary signaling but before the connection verification phase is finished). srflx a server reflexive candidate is generated by a stun/turn server; the connection's initiator requests a candidate from the stun server, which forwards the request through the remote peer's nat, which creates and returns a candidate whose ip address is local to the remote peer. the stun server then replies to the initiator's request with a candidate whose ip address is unrelated to the ...
Establishing a connection: The WebRTC perfect negotiation pattern - Web APIs
the code checks to see if the message is an offer, and if so, if the local signaling state isn't stable. if it's not stable, and the local peer is the polite one, we need to trigger rollback so we can replace the outgoing offer with the new incoming ...
Signaling and video calling - Web APIs
r of the closed iceconnectionstate. we are watching for it here to add a bit of backward compatibility. ice gathering state icegatheringstatechange events are used to let you know when the ice candidate gathering process state changes. our example doesn't use this for anything, but it can be useful to watch these events for debugging purposes, as well as to detect when candidate collection has finished. function handleicegatheringstatechangeevent(event) { // our sample just logs information to console here, // but you can do whatever you need. } next steps you can now try out this example on glitch to see it in action. open the web console on both devices and look at the logged output—although you don't see it in the code as shown above, the code on the server (and on github) has a ...
A simple RTCDataChannel sample - Web APIs
the user interface is updated correspondingly by enabling the text input box for the message to send, focusing the input box so that the user can immediately begin to type, enabling the "send" and "disconnect" buttons, now that they're usable, and disabling the "connect" button, since it is not needed when the conneciton is open. if the state has ch...
Taking still photos with WebRTC - Web APIs
oading. canvas this will be a reference to the <canvas> element after the page is done loading. photo this will be a reference to the <img> element after the page is done loading. startbutton this will be a reference to the <button> element that's used to trigger capture. we'll get that after the page is done loading. the startup() function the startup() function is run when the page has finished loading, courtesy of window.addeventlistener(). this function's job is to request access to the user's webcam, initialize the output <img> to a default state, and to establish the event listeners needed to receive each frame of video from the camera and react when the button is clicked to capture an image. getting element references first, we grab references to the major elements we need to b...
Writing WebSocket client applications - Web APIs
ox").innerhtml = ul; break; } if (text.length) { f.write(text); document.getelementbyid("chatbox").contentwindow.scrollbypages(1); } }; here we use json.parse() to convert the json object back into the original object, then examine and act upon its contents. text data format text received over a websocket connection is in utf-8 format. closing the connection when you've finished using the websocket connection, call the websocket method close(): examplesocket.close(); it may be helpful to examine the socket's bufferedamount attribute before attempting to close the connection to determine if any data has yet to be transmitted on the network. if this value isn't 0, there's pending data still, so you may wish to wait before closing the connection. security consideratio...
Web Video Text Tracks Format (WebVTT) - Web APIs
examples, and look at the cue structure in a bit more detail. webvtt 00:01.000 --> 00:04.000 - never drink liquid nitrogen. 00:05.000 --> 00:09.000 - it will perforate your stomach. - you could die. in the case of each cue: the first line is started with a time, which is the starting time for showing the text that appears underneath. on the same line, we then have a string of "-->". we finish the first line with a second time, which is the ending time for showing the associated text. we can then have one or more lines that start with a hyphen (-), each containing part of the text track to be shown. we can also place comments in our .vtt file, to help us remember important information about the parts of our file. these should be on separate lines, starting with the string note. you'...
Fundamentals of WebXR - Web APIs
aries are available to make it much easier to deal with all of that. how is webxr different from webvr? webvr was generally considered to be an experimental api designed to help specification writers determine the best approaches to creating an api for virtual reality on the web. as browser developers built support for webvr and allowed developers to experiment, it became clear that in order to finish an api for virtual environments on the web, it would make more sense to start a new specification than to try to "fix" webvr. thus, webxr was created. the most obvious difference, at the highest level, is that webxr supports not just virtual reality applications, but also augmented reality, which blends virtual objects with the user's true physical environment. another key difference is that we...
Movement, orientation, and motion: A WebXR example - Web APIs
the viewer reference space. the glmatrix library's fromtranslation() function for 4x4 matrices is used to convert the viewer's start position as given in the viewerstartposition constant into a transform matrix. the viewer's starting orientation, viewerstartorientation, is copied into the cubeorientation property, which will be used to track the rotation of the cube over time. sessionstarted() finishes up by calling the session's requestreferencespace() method to get a reference space object describing the space in which the object is being created. when the promise returned resolves to a xrreferencespace object, we call its getoffsetreferencespace function to obtain a reference space object to represent the object's coordinate system. the origin of the new space is located at the world coor...
Rendering and the WebXR frame animation callback - Web APIs
the player themself. after interpreting inputs from the controls (both xr-affliated and otherwise), you need to apply those changes to the scene in order to simulate the user's movement. see the article movement, orientation, and motion for details and a thorough example of how this works. next steps once you've got your renderer written—or at least got something that works, even if it's not finished—you can begin to deal with the camera and its movement through the scene. this is covered in our article about viewpoints and viewers in webxr. ...
Web Audio API best practices - Web APIs
o fetch the file and decode it into a buffer. both are legitimate ways of working, however, it's more common to use the former when you are working with full-length tracks, and the latter when working with shorter, more sample-like tracks. media elements have streaming support out of the box. the audio will start playing when the browser determines it can load the rest of the file before playing finishes. you can see an example of how to use this with the web audio api in the using the web audio api tutorial. you will, however, have more control if you use a buffer node. you have to request the file and wait for it to load (this section of our advanced article shows a good way to do it), but then you have access to the data directly, which means more precision, and more precise manipulation. ...
Visualizations with Web Audio API - Web APIs
data point value form the array, then moving the line across to the place where the next wave segment should be drawn: for(var i = 0; i < bufferlength; i++) { var v = dataarray[i] / 128.0; var y = v * height/2; if(i === 0) { canvasctx.moveto(x, y); } else { canvasctx.lineto(x, y); } x += slicewidth; } finally, we finish the line in the middle of the right hand side of the canvas, then draw the stroke we've defined: canvasctx.lineto(canvas.width, canvas.height/2); canvasctx.stroke(); }; at the end of this section of code, we invoke the draw() function to start off the whole process: draw(); this gives us a nice waveform display that updates several times a second: creating a frequency b...
Web Locks API - Web APIs
re separate origins. the main entry point is navigator.locks.request() which requests a lock. it takes a lock name, an optional set of options, and a callback. the callback is invoked when the lock is granted. the lock is automatically released when the callback returns, so usually the callback is an async function, which causes the lock to be released only when the async function has completely finished. the request() method itself returns a promise which resolves once the lock has been released; within an async function, a script can await the call to make the asynchronous code flow linear. for example: await do_something_without_lock(); // request the lock. await navigator.locks.request('my_resource', async lock => { // the lock has been acquired. await do_something_with_lock(); awa...
Using the Web Speech API - Web APIs
return its transcript property to get a string containing the individual recognised result as a string, set the background color to that color, and report the color recognised as a diagnostic message in the ui. we also use a speechrecognition.onspeechend handler to stop the speech recognition service from running (using speechrecognition.stop()) once a single word has been recognised and it has finished being spoken: recognition.onspeechend = function() { recognition.stop(); } handling errors and unrecognised speech the last two handlers are there to handle cases where speech was recognised that wasn't in the defined grammar, or an error occured. speechrecognition.onnomatch seems to be supposed to handle the first case mentioned, although note that at the moment it doesn't seem to fire co...
Using Web Workers - Web APIs
ame we want to query. then we can pass in the arguments that the method needs. */ this.sendquery = function() { if (arguments.length < 1) { throw new typeerror('queryableworker.sendquery takes at least one argument'); return; } worker.postmessage({ 'querymethod': arguments[0], 'queryarguments': array.prototype.slice.call(arguments, 1) }); } we finish queryableworker with the onmessage method. if the worker has the corresponding methods we queried, it should return the name of the corresponding listener and the arguments it needs, we just need to find it in listeners.: worker.onmessage = function(event) { if (event.data instanceof object && event.data.hasownproperty('querymethodlistener') && event.data.hasownproperty('quer...
Window: DOMContentLoaded event - Web APIs
bubbles yes cancelable yes (although specified as a simple event that isn't cancelable) interface event event handler property none the original target for this event is the document that has loaded. you can listen for this event on the window interface to handle it in the capture or bubbling phases. for full details on this event please see the page on the document: domcontentloaded event. ...
Window: load event - Web APIs
Web › API › Window › load event
the load event is fired when the whole page has loaded, including all dependent resources such as stylesheets and images. this is in contrast to domcontentloaded, which is fired as soon as the page dom has been loaded, without waiting for resources to finish loading. bubbles no cancelable no interface event event handler property onload examples log a message when the page is fully loaded: window.addeventlistener('load', (event) => { console.log('page is fully loaded'); }); the same, but using the onload event handler property: window.onload = (event) => { console.log('page is fully loaded'); }; live example html <div class="controls"> <button id="reload" type="button">reload</button> </div> <div class="event-log"> <label>...
Window.open() - Web APIs
Web › API › Window › open
eter specifies the url to be fetched and loaded in the new window. if url is an empty string, then a new blank, empty window (url about:blank) is created with the default toolbars of the main window. note that remote urls won't load immediately. when window.open() returns, the window always contains about:blank. the actual fetching of the url is deferred and starts after the current script block finishes executing. the window creation and the loading of the referenced resource are done asynchronously. examples var windowobjectreference; var windowfeatures = "menubar=yes,location=yes,resizable=yes,scrollbars=yes,status=yes"; function openrequestedpopup() { windowobjectreference = window.open("http://www.cnn.com/", "cnn_windowname", windowfeatures); } var windowobjectreference; function op...
Window.pageYOffset - Web APIs
a specific element within the document is scrolled into view in the frame. once that's done, the vertical scroll position is checked by looking at the value of pageyoffset in the frame's contentwindow. html the html is extremely simple and has just two elements: an <iframe> that contains the document we're going to scroll, and a <div> into which we'll output the value of pageyoffset when we've finished the scroll. <iframe id="frame"> </iframe> <div id="info"> </div> javascript var frame = document.getelementbyid("frame"); var framedoc = frame.contentdocument; var info = document.getelementbyid("info"); var target = framedoc.getelementbyid("overview"); framedoc.scrollingelement.scrolltop = target.offsettop; info.innertext = "y offset after scrolling: " + frame.contentwin...
window.postMessage() - Web APIs
and possibly source properties enables cross-site scripting attacks. as with any asynchronously-dispatched script (timeouts, user-generated events), it is not possible for the caller of postmessage to detect when an event handler listening for events sent by postmessage throws an exception. postmessage() schedules the messageevent to be dispatched only after all pending execution contexts have finished. for example, if postmessage() is invoked in an event handler, that event handler will run to completion, as will any remaining handlers for that same event, before the messageevent is dispatched. the value of the origin property of the dispatched event is not affected by the current value of document.domain in the calling window. for idn host names only, the value of the origin property is n...
Window: transitionend event - Web APIs
tion has completed. in the case where a transition is removed before completion, such as if the transition-property is removed or display is set to none, then the event will not be generated. bubbles yes cancelable yes interface transitionevent event handler property ontransitionend the transitionend event is fired in both directions - as it finishes transitioning to the transitioned state, and when it fully reverts to the default or non-transitioned state. if there is no transition delay or duration, if both are 0s or neither is declared, there is no transition, and none of the transition events are fired. if the transitioncancel event is fired, the transitionend event will not fire. the original target for this event is the element that ...
Worker.terminate() - Web APIs
Web › API › Worker › terminate
syntax myworker.terminate(); parameters none. returns void. example the following code snippet shows creation of a worker object using the worker() constructor, which is then immediately terminated. ...
Worker - Web APIs
Web › API › Worker
error is an eventhandler representing the code to be called when the messageerror event is raised. methods inherits methods from its parent, eventtarget, and implements methods from abstractworker. worker.postmessage() sends a message — consisting of any javascript object — to the worker's inner scope. worker.terminate() immediately terminates the worker. this does not let worker finish its operations; it is halted at once. serviceworker instances do not support this method. events message fires when the worker's parent receives a message from that worker. also available via the onmessage property. messageerror fires when a worker object receives a message that can't be deserialized. also available via the onmessageerror property. rejectionhandled fires every time...
WritableStream.WritableStream() - Web APIs
this method is a writablestreamdefaultcontroller that can be used by the developer to control the stream as more chunks are submitted for writing. this method will be called only after previous writes have succeeded, and never after the stream is closed or aborted (see below). close(controller) optional this method, also defined by the developer, will be called if the app signals that it has finished writing chunks to the stream. the contents should do whatever 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 ...
WritableStreamDefaultWriter.close() - Web APIs
during this time any further attempts to write will fail (without erroring the stream). syntax var promise = writablestreamdefaultwriter.close(); parameters none. return value a promise, which fulfills with the undefined if all remaining chunks were successfully written before the close, or rejects with an error if a problem was encountered during the process. exceptions typeerror the stream you are trying to close is not a writablestream. ...
WritableStreamDefaultWriter.ready - Web APIs
essure. syntax var promise = writablestreamdefaultwriter.ready; value a promise. example the following example shows two uses of the ready property. the first uses ready to ensure that the writablestream is done writing and thus able to receive data before sending a binary chunk. the second also checks whether the the writablestream is done writing, but this time because the writing must be finished before the writer can be closed. function sendmessage(message, writablestream) { // defaultwriter is of type writablestreamdefaultwriter var defaultwriter = writablestream.getwriter(); var encoder = new textencoder(); var encoded = encoder.encode(message, {stream: true}); encoded.foreach(function(chunk) { // make sure the stream and its writer are able to // receive data. ...
XDomainRequest.onload - Web APIs
you can find the entire server response in the xdomainrequest.responsetext property. ...
Synchronous and asynchronous requests - Web APIs
ction xhrsuccess., and ultimately supplied to the callback function (in this case, showmessage) which is invoked by function xhrsuccess. line 15 specifies true for its third parameter to indicate that the request should be handled asynchronously. line 16 actually initiates the request. example: using a timeout you can use a timeout to prevent your code from hanging while waiting for a read to finish. this is done by setting the value of the timeout property on the xmlhttprequest object, as shown in the code below: function loadfile(url, timeout, callback) { var args = array.prototype.slice.call(arguments, 3); var xhr = new xmlhttprequest(); xhr.ontimeout = function () { console.error("the request for " + url + " timed out."); }; xhr.onload = function() { ...
Using XMLHttpRequest - Web APIs
y only watching the "progress" event. note: as of gecko 12.0, if your progress event is called with a responsetype of "moz-blob", the value of response is a blob containing the data received so far. one can also detect all three load-ending conditions (abort, load, or error) using the loadend event: req.addeventlistener("loadend", loadend); function loadend(e) { console.log("the transfer finished (although we don't know if it succeeded or not)."); } note there is no way to be certain, from the information received by the loadend event, as to which condition caused the operation to terminate; however, you can use this to handle tasks that need to be performed in all end-of-transfer scenarios. submitting forms and uploading files instances of xmlhttprequest can be used to submit forms...
XMLHttpRequest.timeout - Web APIs
a timeout for synchronous requests with an owning window. using a timeout with an asynchronous request in internet explorer, the timeout property may be set only after calling the open() method and before calling the send() method. example var xhr = new xmlhttprequest(); xhr.open('get', '/server', true); xhr.timeout = 2000; // time in milliseconds xhr.onload = function () { // request finished. do processing here. }; xhr.ontimeout = function (e) { // xmlhttprequest timed out. do something here. }; xhr.send(null); specifications specification status comment xmlhttprequest living standard whatwg living standard ...
XMLHttpRequest.upload - Web APIs
ss made so far. abort onabort the upload operation was aborted. error onerror the upload failed due to an error. load onload the upload completed successfully. timeout ontimeout the upload timed out because a reply did not arrive within the time interval specified by the xmlhttprequest.timeout. loadend onloadend the upload finished. this event does not differentiate between success or failure, and is sent at the end of the upload regardless of the outcome. prior to this event, one of load, error, abort, or timeout will already have been delivered to indicate why the upload ended. specifications specification status comment xmlhttprequest living standard whatwg living standard ...
XRSession.onsqueeze - Web APIs
only to events on the user's off-hand (that is, the hand that isn't their dominant hand). this is determined by comparing the input source's handedness against the value of a handedness property on a user object we've established previously. xrsession.onsqueeze = event => { if (event.inputsource.handedness != user.handedness) { handleoffhandsqueeze(event.inputsource, event.frame); } }; finishing an ongoing squeeze action this example exapnds somewhat on the previous example by demonstrating a way to implement the ability for the user to drop an object that was previously picked up by the user.. this is just a snippet of code, but should establish the general idea. after checking that the event occurred on the user's dominant hand, the pose's target ray is obtained. then we pass the ...
XRSession - Web APIs
Web › API › XRSession
zable gesture. the select event is sent after the selectstart event is sent and immediately before the selectend event is sent. if select is not sent, then the select action was aborted before being completed. also available through the onselect event handler property. selectend an event of type xrinputsourceevent which gets sent to the session object when one of its input devices finishes its primary action or gets disconnected while in the process of handling a primary action. for example: for button or trigger actions, this means the button has been released; for spoken commands, it means the user has finished speaking. this is the last of the three select* events to be sent. also available through the onselectend event handler property. selectstart an event of...
XRView.transform - Web APIs
Web › API › XRView › transform
ill simulate the movement of the camera even though we're actually moving the object. we then compute the normals for the model view matrix by inverting it, then transposing it. finally, we call the object's render() routine, passing along the modelviewmatrix and normalmatrix so the renderer can place and light the object properly. note: this example is derived from a larger example... <<<--- finish and add link --->>> specifications specification status comment webxr device apithe definition of 'xrview.transform' in that specification. working draft initial definition. ...
Using the alert role - Accessibility
indicate that an alert occurred and what the alert text was. note: opinons may differ on how assistive technology should handle this technique. the information provided above is one of those opinions and therefore not normative. examples example 1: adding the role in the html code the snippet below shows how the alert role is added directly into the html source code. the moment the element finishes loading the screen reader should be notified of the alert. if the element was already in the original source code when the page loaded, the screen reader will announce the error immediately after announcing the page title. <h2 role="alert">your form could not be submitted because of 3 validation errors.</h2> example 2: dynamically adding an element with the alert role this snippet dynamicall...
Using the progressbar role - Accessibility
should omit the aria-valuenow attribute. as the task progresses, the aria-valuenow value has to be updated dynamically to indicate this progress to assistive technology products. if the progressbar is describing the loading progress of a particular region of a page, the author should use aria-describedby to point to the status, and set the aria-busy attribute to true on the region until it is finished loading. it is not possible for the user to alter the value of a progressbar because it is always readonly. note: assistive technologies generally will render the value of aria-valuenow as a percent of the range between the value of aria-valuemin and aria-valuemax, unless aria-valuetext is specified. it is best to set the values for aria-valuemin, aria-valuemax, and aria-valuenow in a manner t...
ARIA: application role - Accessibility
ny 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 streamlined to a single-column view. a keyboard interaction model is generated that is very similar to a word processor where users can read line by line, sentence by sentence, or pa...
Implementing a Microsoft Active Accessibility (MSAA) Server - Accessibility
if you're not using a hash table to keep track of unique id's, store the child id's and objects for the last 50 or so events in a circular array. in practice, this is enough to keep accessibleobjectfromevent() happy. missing functionality in msaa problem and solutions: assistive technology vendors need some things which msaa does not provide, such as: no way of signifying that a document has finished loading. fire event_object_statechange for a window/client/pane object when it starts to load a new document. use state_busy to indicate that a new document is being loaded. when the loading has finished, fire another event_object_statechange event and clear the state_busy flag. no method to get clipped/unclipped bounds of a piece of text within a text object. this is needed by screen magnifie...
-webkit-overflow-scrolling - CSS: Cascading Style Sheets
the -webkit-overflow-scrolling css property controls whether or not touch devices use momentum-based scrolling for a given element. syntax values auto use "regular" scrolling, where the content immediately ceases to scroll when you remove your finger from the touchscreen. touch use momentum-based scrolling, where the content continues to scroll for a while after finishing the scroll gesture and removing your finger from the touchscreen. the speed and duration of the continued scrolling is proportional to how vigorous the scroll gesture was. also creates a new stacking context. formal definition initial valueautoapplies toscrolling boxesinheritedyescomputed valueas specifiedanimation typediscrete formal syntax auto | touch examples html <div class="scroll-touch"> <p> ...
::-moz-progress-bar - CSS: Cascading Style Sheets
the ::-moz-progress-bar css pseudo-element is a mozilla extension that represents the progress bar inside a <progress> element. (the bar represents the amount of progress that has been made.) if you want to select the unfinished part of <progress> in mozilla, please select the <progress> directly. syntax ::-moz-progress-bar examples html <progress value="30" max="100">30%</progress> <progress max="100">indeterminate</progress> css ::-moz-progress-bar { background-color: red; } /* force indeterminate bars to have zero width */ :indeterminate::-moz-progress-bar { width: 0; } result specifications not part of any standard. ...
:disabled - CSS: Cascading Style Sheets
Web › CSS › :disabled
illing-checkbox">same as shipping address:</label> <input type="checkbox" id="billing-checkbox" checked> <br> <input type="text" placeholder="name" disabled> <input type="text" placeholder="address" disabled> <input type="text" placeholder="zip code" disabled> </fieldset> </form> css input[type="text"]:disabled { background: #ccc; } javascript // wait for the page to finish loading document.addeventlistener('domcontentloaded', function () { // attach `change` event listener to checkbox document.getelementbyid('billing-checkbox').onchange = togglebilling; }, false); function togglebilling() { // select the billing text fields var billingitems = document.queryselectorall('#billing input[type="text"]'); // toggle the billing text fields for (var i = 0; i ...
Detecting CSS animation support - CSS: Cascading Style Sheets
pecified by the variable elem is set. this means the browser supports css animation without any prefix, which, to date, none of them do. if the browser does not support non-prefixed animation and animation is still false, we iterate over all the possible prefixes, since all the major browsers are currently prefixing this property and changing its name to animationname instead. once this code is finished running, the value of animation will be false if css animation support isn't available, or it will be true. if it is true then both the animation property name and the keyframe prefix will be the right ones. so if you use a new firefox, the property will be mozanimation and the keyframe prefix -moz- and with chrome it'll be webkitanimation and -webkit-. notice browsers don't make it easy with t...
Ordering Flex Items - CSS: Cascading Style Sheets
s helpful. used carefully the order property can allow for some useful common patterns to be easily implemented. you might have a design, perhaps a card that will display a news item. the heading of the news item is the key thing to highlight and would be the element that a user might jump to if they were tabbing between headings to find content they wanted to read. the card also has a date; the finished design we want to create is something like this. visually the date appears above the heading, in the source. however, if the card was read out by a screen reader i would prefer that the title was announced first and then the publication date. we can make this so using the order property. the card is going to be our flex container, with flex-direction set to column. i then give the date an o...
Relationship of flexbox to other layout methods - CSS: Cascading Style Sheets
the definitions in box alignment level 3 will supersede those of flexbox: "note: while the alignment properties are defined in css box alignment [css-align-3], flexible box layout reproduces the definitions of the relevant ones here so as to not create a normative dependency that may slow down advancement of the spec. these properties apply only to flex layout until css box alignment level 3 is finished and defines their effect for other layout modes. additionally, any new values defined in the box alignment module will apply to flexible box layout; in otherwords, the box alignment module, once completed, will supercede the definitions here." in a later article in this series — aligning items in a flex container — we will take a thorough look at how the box alignment properties apply to ...
Line-based placement with CSS Grid - CSS: Cascading Style Sheets
n-start/grid-column-end. the following two examples will create the same grid area. in the first we set the start row line, then the end line we explain that we want to span 3 lines. the area will start at line 1 and span 3 lines to line 4. .box1 { grid-column-start: 1; grid-row-start: 1; grid-row-end: span 3; } in the second example, we specify the end row line we want the item to finish at and then set the start line as span 3. this means the item will need to span upwards from the specified row line. the area will start at line 4 and span 3 lines to line 1. .box1 { grid-column-start: 1; grid-row-start: span 3; grid-row-end: 4; } to become familiar with line based positioning in grid try to build a few common layouts by placing items onto grids with varying number...
Basic concepts of CSS Scroll Snap - CSS: Cascading Style Sheets
whether the content has to snap to a certain point, no matter where the scroll is. the proximity keyword means that it may snap to the point, but does not have to. using mandatory gives a very consistent experience — you know that the browser will always snap to each defined point. this means you can be confident that something you expect to be at the top of the screen will be when scrolling finishes. however, it can cause problems if the content is larger than you expect — users may find themselves in the frustrating position of never being able to scroll and view a certain point in the content. therefore, use of mandatory should be carefully considered and only used in situations where you know how much content is on the screen at any one time. the proximity value will only snap to a p...
Introducing the CSS Cascade - CSS: Cascading Style Sheets
Web › CSS › Cascade
3 author normal 4 animations 5 author !important 6 user !important 7 user agent !important 8 transitions in case of equality, the specificity of a value is considered to choose one or the other. resetting styles after your content has finished altering styles, it may find itself in a situation where it needs to restore them to a known state. this may happen in cases of animations, theme changes, and so forth. the css property all lets you quickly set (almost) everything in css back to a known state. all lets you opt to immediately restore all properties to any of their initial (default) state, the state inherited from the previous l...
conic-gradient() - CSS: Cascading Style Sheets
-gradient() function is an object of the <gradient> data type, which is a special kind of <image>. 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. ...
font-family - CSS: Cascading Style Sheets
space should be quoted. <generic-name> generic font families are a fallback mechanism, a means of preserving some of the style sheet author's intent when none of the specified fonts are available. generic family names are keywords and must not be quoted. a generic font family should be the last item in the list of font family names. the following keywords are defined: serif glyphs have finishing strokes, flared or tapering ends, or have actual serifed endings. e.g. lucida bright, lucida fax, palatino, "palatino linotype", palladio, "urw palladio", serif. sans-serif glyphs have stroke endings that are plain. e.g. "open sans", "fira sans", "lucida sans", "lucida sans unicode", "trebuchet ms", "liberation sans", "nimbus sans l", sans-serif. monospace all glyphs have the same ...
radial-gradient() - CSS: Cascading Style Sheets
is an object of the <gradient> data type, which is a special kind of <image>. 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 /* a gradient at the center of its container, starting red, changing to blue, and finishing green */ radial-gradient(circle at center, red 0, blue, green 100%) values <position> the position of the gradient, interpreted in the same way as background-position or transform-origin. if unspecified, it defaults to center. <shape> the gradient's shape. the value can be circle (meaning that the gradient's shape is a circle with constant radius) or ellipse (meaning that the shape is a...
repeating-linear-gradient() - CSS: Cascading Style Sheets
e, 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-linear-gradient(to left top, blue, red 20px); /* a gradient going from the bottom to top, starting blue, turning green after 40%, and finishing red. this gradient doesn't r...
repeating-radial-gradient() - CSS: Cascading Style Sheets
tio. 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. ...
scroll-snap-type-x - CSS: Cascading Style Sheets
scroll-snap-type-x: inherit; scroll-snap-type-x: initial; scroll-snap-type-x: unset; syntax values none when the visual viewport of this scroll container is scrolled horizontally, it must ignore snap points. mandatory the visual viewport of this scroll container will rest on a snap point if it isn't currently scrolled horizontally. that means it snaps on that point when the scroll action finished, if possible. if content is added, moved, deleted or resized the scroll offset will be adjusted to maintain the resting on that snap point. proximity the visual viewport of this scroll container may come to rest on a snap point if it isn't currently scrolled horizontally considering the user agent's scroll parameters. if content is added, moved, deleted or resized the scroll offset may be adj...
scroll-snap-type-y - CSS: Cascading Style Sheets
*/ scroll-snap-type-y: inherit; scroll-snap-type-y: initial; scroll-snap-type-y: unset; syntax values none when the visual viewport of this scroll container is scrolled vertically, it must ignore snap points. mandatory the visual viewport of this scroll container will rest on a snap point if it isn't currently scrolled vertically. that means it snaps on that point when the scroll action finished, if possible. if content is added, moved, deleted or resized the scroll offset will be adjusted to maintain the resting on that snap point. proximity the visual viewport of this scroll container may come to rest on a snap point if it isn't currently scrolled vertically considering the user agent's scroll parameters. if content is added, moved, deleted or resized the scroll offset may be adjus...
scroll-snap-type - CSS: Cascading Style Sheets
ly. inline the scroll container snaps to snap positions in its inline axis only. both the scroll container snaps to snap positions in both of its axes independently (potentially snapping to different elements in each axis). mandatory the visual viewport of this scroll container will rest on a snap point if it isn't currently scrolled. that means it snaps on that point when the scroll action finished, if possible. if content is added, moved, deleted or resized the scroll offset will be adjusted to maintain the resting on that snap point. proximity the visual viewport of this scroll container may come to rest on a snap point if it isn't currently scrolled considering the user agent's scroll parameters. if content is added, moved, deleted or resized the scroll offset may be adjusted to main...
Used value - CSS: Cascading Style Sheets
the used values of dimensions (e.g., width, line-height) are in pixels. the used values of shorthand properties (e.g., background) are consistent with those of their component properties (e.g., background-color or background-size) and with position and float. note: the getcomputedstyle() dom api returns the resolved value, which may either be the computed value or the used value, depending on the property. ...
Getting Started - Developer guides
st.done) { // everything is good, the response was received. } else { // not ready yet. } the full list of the readystate values is documented at xmlhttprequest.readystate and is as follows: 0 (uninitialized) or (request not initialized) 1 (loading) or (server connection established) 2 (loaded) or (request received) 3 (interactive) or (processing request) 4 (complete) or (request finished and response is ready) next, check the http response status codes of the http response. the possible codes are listed at the w3c. in the following example, we differentiate between a successful and unsuccessful ajax call by checking for a 200 ok response code. if (httprequest.status === 200) { // perfect! } else { // there was a problem with the request. // for example, the respo...
Cross-browser audio basics - Developer guides
attribute has caused playback to begin. this is when the state of the media switches from paused to playing. pause the pause event is triggered after the pause() method is returned. this is when the states switch from playing to paused. ended the ended event is initiated when the end of the media is reached. myaudio.addeventlistener("ended", function() { //do something once audio track has finished playing }); volumechange the volumechange event signifies that the volume has changed; that includes being muted. an audio player with feedback consider this snippet of html: <audio id="my-audio"> <source src="https://udn.realityripple.com/samples/6c/d385042de2.mp3" type="audio/mpeg"> <source src="https://udn.realityripple.com/samples/28/191a7bd2a5.ogg" type="audio/ogg"> <!-- place f...
Printing - Developer guides
se this to adjust the user interface presented during printing (such as by displaying or hiding user interface elements during the print process). note: you can also use window.onbeforeprint and window.onafterprint to assign handlers for these events, but using eventtarget.addeventlistener() is preferred. examples here are some common examples. ...
Applying color to HTML elements using CSS - HTML: Hypertext Markup Language
provide one for your use through the <input> element, by using "color" as the value of its type attribute. the <input> element represents a color only in the hexadecimal string notation covered above. example: picking a color let's look at a simple example, in which the user can choose a color. as the user adjusts the color, the border around the example changes to reflect the new color. after finishing up and picking the final color, the color picker's value is displayed. on macos, you indicate that you've finalized selection of the color by closing the color picker window. html the html here creates a box that contains a color picker control (with a label created using the <label> element) and an empty paragraph element (<p>) into which we'll output some text from our javascript code...
HTML attribute reference - HTML: Hypertext Markup Language
loading <img>, <iframe> indicates if the element should be loaded lazily (loading="lazy") or loaded immediately (loading="eager"). wip: whatwg pr #3752 list <input> identifies a list of pre-defined options to suggest to the user. loop <audio>, <bgsound>, <marquee>, <video> indicates whether the media should start playing from the start when it's finished. low <meter> indicates the upper bound of the lower range. manifest <html> specifies the url of the document's cache manifest. note: this attribute is obsolete, use <link rel="manifest"> instead. max <input>, <meter>, <progress> indicates the maximum value allowed. maxlength <input>, <textarea> defines the maximum number of cha...
<body>: The Document Body element - HTML: Hypertext Markup Language
Web › HTML › Element › body
function to call when the document fails to load properly. onfocus function to call when the document receives focus. onhashchange function to call when the fragment identifier part (starting with the hash ('#') character) of the document's current address has changed. onlanguagechange function to call when the preferred languages changed. onload function to call when the document has finished loading. onmessage function to call when the document has received a message. onoffline function to call when network communication has failed. ononline function to call when network communication has been restored. onpopstate function to call when the user has navigated session history. onredo function to call when the user has moved forward in undo transaction history. onresize fu...
<input>: The Input (Form Input) element - HTML: Hypertext Markup Language
Web › HTML › Element › input
for all input types except checkbox, radio, file, or any of the button types. see the html autocomplete attribute for additional information, including information on password security and how autocomplete is slightly different for hidden than for other input types. autofocus a boolean attribute which, if present, indicates that the input should automatically have focus when the page has finished loading (or when the <dialog> containing the element has been displayed). note: an element with the autofocus attribute may gain focus before the domcontentloaded event is fired. no more than one element in the document may have the autofocus attribute. if put on more than one element, the first one with the attribute receives focus. the autofocus attribute cannot be used on inputs of...
<marquee>: The Marquee element (Obsolete) - HTML: Hypertext Markup Language
Web › HTML › Element › marquee
by default, scrolldelay values lower than 60 are ignored. if truespeed is present, those values are not ignored. vspace sets the vertical margin in pixels or percentage value. width sets the width in pixels or percentage value. event handlers onbounce fires when the marquee has reached the end of its scroll position. it can only fire when the behavior attribute is set to alternate. onfinish fires when the marquee has finished the amount of scrolling that is set by the loop attribute. it can only fire when the loop attribute is set to some number that is greater than 0. onstart fires when the marquee starts scrolling. methods start() starts scrolling of the marquee. stop() stops scrolling of the marquee. examples <marquee>this text will scroll from right to left</marque...
<ol>: The Ordered List element - HTML: Hypertext Markup Language
Web › HTML › Element › ol
t items; if the meaning changes, use the <ol> element — otherwise you can use <ul>. ...
<p>: The Paragraph element - HTML: Hypertext Markup Language
Web › HTML › Element › p
ndentation, can be achieved with css: html <p>separating paragraphs with blank lines is easiest for readers to scan, but they can also be separated by indenting their first lines. this is often used to take up less space, such as to save paper in print.</p> <p>writing that is intended to be edited, such as school papers and rough drafts, uses both blank lines and indentation for separation. in finished works, combining both is considered redundant and amateurish.</p> <p>in very old writing, paragraphs were separated with a special character: ¶, the <i>pilcrow</i>. nowadays, this is considered claustrophobic and hard to read.</p> <p>how hard to read? see for yourself: <button data-toggle-text="oh no! switch back!">use pilcrow for paragraphs</button> </p> css p { margin: 0; text-ind...
<script>: The Script element - HTML: Hypertext Markup Language
Web › HTML › Element › script
this attribute. see cors settings attributes for a more descriptive explanation of its valid arguments. defer this boolean attribute is set to indicate to a browser that the script is meant to be executed after the document has been parsed, but before firing domcontentloaded. scripts with the defer attribute will prevent the domcontentloaded event from firing until the script has loaded and finished evaluating. this attribute must not be used if the src attribute is absent (i.e. for inline scripts), in this case it would have no effect. the defer attribute has no effect on module scripts — they defer by default. scripts with the defer attribute will execute in the order in which they appear in the document. this attribute allows the elimination of parser-blocking javascript w...
Connection - HTTP
if the value sent is keep-alive, the connection is persistent and not closed, allowing for subsequent requests to the same server to be done. connection-specific header fields such as connection and keep-alive are prohibited in http/2. chrome and firefox ignore them in http/2 responses, but safari conforms to the http/2 spec requirements and won’t load any response which contains them. ...
Index - HTTP
Web › HTTP › Headers › Index
clear-site-data header clears browsing data (cookies, storage, cache) associated with the requesting website. it allows web developers to have more control over the data stored locally by a browser for their origins. 21 connection http, headers, reference, web the connection general header controls whether or not the network connection stays open after the current transaction finishes. if the value sent is keep-alive, the connection is persistent and not closed, allowing for subsequent requests to the same server to be done. 22 content-disposition http, reference, header in a multipart/form-data body, the http content-disposition general header is a header that can be used on the subpart of a multipart body to give information about the field it applies ...
Set-Cookie - HTTP
with names starting with __host- must be set with the secure flag, must be from a secure page (https), must not have a domain specified (and therefore aren't sent to subdomains) and the path must be /. expires=<date> optional the maximum lifetime of the cookie as an http-date timestamp. see date for the required formatting. if unspecified, the cookie becomes a session cookie. a session finishes when the client shuts down, and session cookies will be removed. warning: many web browsers have a session restore feature that will save all tabs and restore them next time the browser is used. session cookies will also be restored, as if the browser was never closed. when an expires date is set, the deadline is relative to the client the cookie is being set on, not the server. max-...
HTTP headers - HTTP
Web › HTTP › Headers
pecific range with previous ones, or to implement an optimistic concurrency control system when modifying existing documents. vary determines how to match request headers to decide whether a cached response can be used rather than requesting a fresh one from the origin server. connection management connection controls whether the network connection stays open after the current transaction finishes. keep-alive controls how long a persistent connection should stay open. content negotiation accept informs the server about the types of data that can be sent back. accept-charset which character encodings the client understands. accept-encoding the encoding algorithm, usually a compression algorithm, that can be used on the resource sent back. accept-language informs the server a...
Redirections in HTTP - HTTP
the rewrite directive: rewrite ^/images/(.*)$ https://images.example.com/$1 redirect; rewrite ^/images/(.*)$ https://images.example.com/$1 permanent; iis in iis, you use the <httpredirect> element to configure redirections. redirection loops redirection loops happen when additional redirections follow the one that has already been followed. in other words, there is a loop that will never be finished and no page will ever be found. most of the time this is a server problem, and if the server cannot detect it, it will send back a 500 internal server error. if you encounter such an error soon after modifying a server configuration, this is likely a redirection loop. sometimes, the server won't detect it: a redirection loop can spread over several servers which each don't have the full pictu...
100 Continue - HTTP
Web › HTTP › Status › 100
to have a server check the request's headers, a client must send expect: 100-continue as a header in its initial request and receive a 100 continue status code in response before sending the body. ...
HTTP response status codes - HTTP
Web › HTTP › Status
ction 10 of rfc 2616. you can find an updated specification in rfc 7231. if you receive a response that is not in this list, it is a non-standard response, possibly custom to the server's software. information responses 100 continue this interim response indicates that everything so far is ok and that the client should continue the request, or ignore the response if the request is already finished. 101 switching protocol this code is sent in response to an upgrade request header from the client, and indicates the protocol the server is switching to. 102 processing (webdav) this code indicates that the server has received and is processing the request, but no response is available yet. 103 early hints this status code is primarily intended to be used with the link header, letting th...
Closures - JavaScript
he previous example of the init() function above. what's different (and interesting) is that the displayname() inner function is returned from the outer function before being executed. at first 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 variable...
Control flow and error handling - JavaScript
atch (catchid) { statements } the catch block specifies an identifier (catchid in the preceding syntax) that holds the value specified by the throw statement. you can use this identifier to get information about the exception that was thrown. javascript creates this identifier when the catch block is entered. the identifier lasts only for the duration of the catch block. once the catch block finishes executing, the identifier no longer exists. for example, the following code throws an exception. when the exception occurs, control transfers to the catch block. try { throw 'myexception'; // generates an exception } catch (err) { // statements to handle any exceptions logmyerrors(err); // pass exception object to error handler } best practice: when logging errors to the console i...
Iterators and generators - JavaScript
« previousnext » ...
Atomics - JavaScript
not a constructor. you cannot use it with a new operator or invoke the atomics object as a function. all properties and methods of atomics are static (as is the case with the math object, for example). atomic operations when memory is shared, multiple threads can read and write the same data in memory. atomic operations make sure that predictable values are written and read, that operations are finished before the next operation starts and that operations are not interrupted. wait and notify the wait() and notify() methods are modeled on linux futexes ("fast user-space mutex") and provide ways for waiting until a certain condition becomes true and are typically used as blocking constructs. static methods atomics.add() adds the provided value to the existing value at the specified index ...
Generator.prototype.return() - JavaScript
syntax gen.return(value) parameters value the value to return. return value the value that is given as an argument. examples using return() the following example shows a simple generator and the return method. function* gen() { yield 1; yield 2; yield 3; } const g = gen(); g.next(); // { value: 1, done: false } g.return('foo'); // { value: "foo", done: true } g.next(); // { value: undefined, done: true } if return(value) is called on a generator that is already in "completed" state, the generator will remain in "completed" state. if no argument is provided, the value property of returned object is the same as if .next(). ...
Generator - JavaScript
ocol. constructor this object cannot be instantiated directly. instead, a generator instance can be returned from a generator function: function* generator() { yield 1; yield 2; yield 3; } const gen = generator(); // "generator { }" instance methods generator.prototype.next() returns a value yielded by the yield expression. generator.prototype.return() returns the given value and finishes the generator. generator.prototype.throw() throws an error to a generator (also finishes the generator, unless caught from within that generator). examples an infinite iterator function* infinite() { let index = 0; while (true) { yield index++; } } const generator = infinite(); // "generator { }" console.log(generator.next().value); // 0 console.log(generator.next()...
Map.prototype.forEach() - JavaScript
ided to foreach, it will be passed to callback when invoked, for use as its this value. otherwise, the value undefined will be passed for use as its this value. the this value ultimately observable by callback is determined according to the usual rules for determining the this seen by a function. each value is visited once, except in the case when it was deleted and re-added before foreach has finished. callback is not invoked for values deleted before being visited. new values added before foreach has finished will be visited. foreach executes the callback function once for each element in the map object. it does not return a value. examples printing the contents of a map object the following code logs a line for each element in an map object: function logmapelements(value, key, map) { ...
Object.assign() - JavaScript
, foo3: 3 }, { baz: 4 }); // typeerror: "foo" is read-only // the exception is thrown when assigning target.foo console.log(target.bar); // 2, the first source was copied successfully. console.log(target.foo2); // 3, the first property of the second source was copied successfully. console.log(target.foo); // 1, exception is thrown here. console.log(target.foo3); // undefined, assign method has finished, foo3 will not be copied. console.log(target.baz); // undefined, the third source will not be copied either. copying accessors const obj = { foo: 1, get bar() { return 2; } }; let copy = object.assign({}, obj); console.log(copy); // { foo: 1, bar: 2 } // the value of copy.bar is obj.bar's getter's return value. // this is an assign function that copies full descriptors function ...
Set.prototype.forEach() - JavaScript
to foreach(), it will be passed to callback when invoked, for use as its this value. otherwise, the value undefined will be passed for use as its this value. the this value ultimately observable by callback is determined according to the usual rules for determining the this seen by a function. each value is visited once, except in the case when it was deleted and re-added before foreach() has finished. callback is not invoked for values deleted before being visited. new values added before foreach() has finished will be visited. foreach() executes the callback function once for each element in the set object; it does not return a value. examples logging the contents of a set object the following code logs a line for each element in a set object: function logsetelements(value1, value2, s...
Destructuring assignment - JavaScript
examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax let a, b, rest; [a, b] = [10, 20]; console.log(a); // 10 console.log(b); // 20 [a, b, ...rest] = [10, 20, 30, 40, 50]; console.log(a); // 10 console.log(b); // 20 console.log(rest); // [30, 40, 50] ({ a, b } = { a: 10, b: 20 }); console.log(a); // 10 console.log(b); // 20 // stage 4(finished) proposal ({a, b, ...rest} = {a: 10, b: 20, c: 30, d: 40}); console.log(a); // 10 console.log(b); // 20 console.log(rest); // {c: 30, d: 40} description the object and array literal expressions provide an easy way to create ad hoc packages of data. const x = [1, 2, 3, 4, 5]; the destructuring assignment uses similar syntax, but on the left-hand side of the assignment to define what values ...
yield* - JavaScript
...
try...catch - JavaScript
ins statements that specify what to do if an exception is thrown in the try-block. if any statement within the try-block (or in a function called from within the try-block) throws an exception, control is immediately shifted to the catch-block. if no exception is thrown in the try-block, the catch-block is skipped. the finally-block will always execute after the try-block and catch-block(s) have finished executing. it always executes, regardless of whether an exception was thrown or caught. you can nest one or more try statements. if an inner try statement does not have a catch-block, the enclosing try statement's catch-block is used instead. you can also use the try statement to handle javascript exceptions. see the javascript guide for more information on javascript exceptions. uncondition...
Handling media support issues in web content - Web media technologies
our image has been converted to progressive form, you can simply use it as usual. <img src="/images/stafff-photo-huge-progressive.jpg" alt="staff photo, taken in january of 1972"> when using a progressive image, the data is stored in such a way that the browser is able to render a low-quality representation of the image as soon as possible, then update the image as it loads—or after it's finished loading—to present it in full quality. note: progressive (or interlaced) images are inherently slightly larger than the non-progressive versions of the same images. whether the interlacing will benefit your users is up to you to determine. specifying multiple sources checking compatibility in javascript htmlmediaelement.canplaytype and mediasource.istypesupported... detecting playback ...
Web video codec guide - Web media technologies
has moved in each direction. then that shift is stored, along with a description of the pixels that have moved that can't be described just by that shift. in essence, the encoder finds the moving objects, then builds an internal frame of sorts that looks like the original but with all the objects translated to their new locations. in theory, this approximates the new frame's appearance. then, to finish the job, the remaining differences are found, then the set of object shifts and the set of pixel differences are stored in the data representing the new frame. this object that describes the shift and the pixel differences is called a residual frame. original frame inter-frame differences difference after motion compensation the first full frame as s...
Lazy loading - Web Performance
user scrolls near them. <img src="image.jpg" loading="lazy" alt="..." /> <iframe src="video-player.html" loading="lazy"></iframe> the load event fires when the eagerly-loaded content has all been loaded; at that time, it's entirely possible (or even likely) that there may be lazily-loaded images that are within the visual viewport that haven't yet loaded. you can determine if a given image has finished loading by examining the value of its boolean complete property. polyfill include this polyfill to provide support for older and currently incompatible browsers: loading-attribute-polyfill intersection observer api intersection observers allow the user to know when an observed element enters or exits the browser’s viewport. event handlers when browser compatibility is crucial, there ar...
Add to Home screen - Progressive web apps (PWAs)
note that the type member in each icon's object specifies the icon's mimetype, so the browser can quickly read what type the icon is, and then ignore it and move to a different icon if it doesn't support it. in terms of how to design the icon, you should follow the same best practices you'd follow for any android icon (see the android icon design guidelines). link the html to the manifest to finish setting up your manifest, you need to reference it from the html of your application's home page: <link rel="manifest" href="manifest.webmanifest"> browsers that support a2hs will know where to look for your manifest once this is in place. what does a2hs not give you? bear in mind that when you add an app to your home screen, it just makes the app easily accessible — it doesn't download the...
Making PWAs work offline with Service workers - Progressive web apps (PWAs)
shell and content'); return cache.addall(contenttocache); }) ); }); there are two things that need an explanation here: what extendableevent.waituntil does, and what the caches object is. the service worker does not install until the code inside waituntil is executed. it returns a promise — this approach is needed because installing may take some time, so we have to wait for it to finish. caches is a special cachestorage object available in the scope of the given service worker to enable saving data — saving to web storage won't work, because web storage is synchronous. with service workers, we use the cache api instead. here, we open a cache with a given name, then add all the files our app uses to the cache, so they are available next time it loads (identified by request ur...
textLength - SVG: Scalable Vector Graphics
der's new value, using the svglength interface's svg_lengthtype_px unit type to indicate that the value represents pixels. note that we have to dive into textlength to get its baseval property; textlength is stored as an svglength object, so we can't treat it like a plain number. after updating the text width, the contents of the widthdisplay box are updated with the new value as well, and we're finished. result here's what the example looks like. try dragging the slider around to get a feel for what it does. specifications specification status comment scalable vector graphics (svg) 2the definition of 'textlength' in that specification. candidate recommendation allowed percentages and numbers as values. scalable vector graphics (svg) 1.1 (second ...
Index - XSLT: Extensible Stylesheet Language Transformations
Web › XSLT › Index
5 the xslt/javascript interface in gecko xslt no summary! 6 advanced example xslt this advanced example sorts several divs based on their content. the example allows sorting the content multiple times, alternating between ascending and descending order. the javascript loads the .xsl file only on the first sort and sets the xslloaded variable to true once it has finished loading the file. using the xsltprocessor.getparameter() method, the code can figure whether to sort in ascending or descending order. it defaults to ascending if the parameter is empty (the first time the sorting happens, as there is no value for it in the xslt file). the sorting value is set using xsltprocessor.setparameter(). 7 basic example xslt the basic example will l...
Advanced Example - XSLT: Extensible Stylesheet Language Transformations
using the xsltprocessor.getparameter() method, the code can figure whether to sort in ascending or descending order. ...
Caching compiled WebAssembly modules - WebAssembly
a somewhat old-fashioned api, we wanted to provide a library function to speed up writing caching code, and make it work better along with today's more modern apis. in our wasm-utils.js library script, you'll find instantiatecachedurl() — this function fetches the wasm module at url with a version of dbversion, instantiates it with the given importobject, and returns a promise resolving to the finished wasm instance. additionally, it handles creating a database to cache the compiled wasm modules in, attempts to store new modules in the database, and retrieves previously cached modules from the database, saving you from having to download them again. note: the entire site's wasm cache (not just the given url) is versioned by the specified dbversion passed into the function. if the wasm modul...
Index - WebAssembly
your module into memory before compilation/instantiation. this article provides a reference for the different mechanisms that can be used to fetch webassembly bytecode, as well as how to compile/instantiate then run it. 10 understanding webassembly text format functions, javascript, s-expressions, webassembly, calls, memory, shared address, table, text format, was, wasm this finishes our high-level tour of the major components of the webassembly text format and how they get reflected in the webassembly js api. 11 using the webassembly javascript api api, devtools, javascript, webassembly, compile, instantiate, memory, table this article has taken you through the basics of using the webassembly javascript api to include a webassembly module in a javascri...
Loading and running WebAssembly code - WebAssembly
a new xmlhttprequest() instance, and use its open() method to open a request, setting the request method to get, and declaring the path to the file we want to fetch. the key part of this is to set the response type to 'arraybuffer' using the responsetype property. next, send the request using xmlhttprequest.send(). we then use the onload event handler to invoke a function when the response has finished downloading — in this function we get the array buffer from the response property, and then feed that into our webassembly.instantiate() method as we did with fetch. the final code looks like this: request = new xmlhttprequest(); request.open('get', 'simple.wasm'); request.responsetype = 'arraybuffer'; request.send(); request.onload = function() { var bytes = request.response; webasse...