Search completed in 1.31 seconds.
513 results for "push":
Your results are loading. Please wait...
PushEvent.PushEvent() - Web APIs
the pushevent() constructor creates a new pushevent object.
... syntax var mypushevent = new pushevent(type, eventinitdict); parameters type a domstring defining the type of pushevent.
... this can be push or pushsubscriptionchange.
...And 7 more matches
nsIPushService
dom/interfaces/push/nsipushservice.idlscriptable a service for components to subscribe and receive push messages from remote servers.
... inherits from: nsisupports last changed in gecko 46.0 (firefox 46.0 / thunderbird 46.0 / seamonkey 2.43) push lets a remote server send payloads to a web site, add-on, or component running in the browser.
... nsipushservice supports the push api implementation in firefox, and can be used directly from privileged code to create system subscriptions.
...And 26 more matches
How to make PWAs re-engageable using Notifications and Push - Progressive web apps (PWAs)
but instead of relying only on user actions, we can do more, using push messages and notifications to automatically re-engage and deliver new content whenever it is available.
... two apis, one goal the push api and notifications api are two separate apis, but they work well together when you want to provide engaging functionality in your app.
... push is used to deliver new content from the server to the app without any client-side intervention, and its operation is handled by the app's service worker.
...And 26 more matches
Push API - Web APIs
WebAPIPush API
the push api gives web applications the ability to receive messages pushed to them from a server, whether or not the web app is in the foreground, or even currently loaded, on a user agent.
... push concepts and usage when implementing pushmanager subscriptions, it is vitally important that you protect against csrf/xsrf issues in your app.
... see the following articles for more information: cross-site request forgery (csrf) prevention cheat sheet preventing csrf and xsrf attacks for an app to receive push messages, it has to have an active service worker.
...And 25 more matches
PushManager - Web APIs
the pushmanager interface of the push api provides a way to receive notifications from third-party servers as well as request urls for push notifications.
... this interface is accessed via the serviceworkerregistration.pushmanager property.
... note: this interface replaces functionality previously offered by the obsolete pushregistrationmanager interface.
...And 18 more matches
Web Push API Notifications best practices - Web APIs
this article provides a useful summary of best practices to keep in mind when developing web sites and applications that use push notifications for user engagement.
... “if done well, it's nice to have, but if not done well, it's really annoying.” — overheard conversation between two browser developers discussing the ethics of push notifications.
... overview of web push notifications web push notifications (created using a combination of the notifications, push, and service worker apis) are part of the rising noise that product developers and marketers are using to get attention for their sites.
...And 18 more matches
PushEvent - Web APIs
WebAPIPushEvent
the pushevent interface of the push api represents a push message that has been received.
...it contains the information sent from an application server to a pushsubscription.
... constructor pushevent.pushevent() creates a new pushevent object.
...And 11 more matches
PushManager.subscribe() - Web APIs
the subscribe() method of the pushmanager interface subscribes to a push service.
... it returns a promise that resolves to a pushsubscription object containing details of a push subscription.
... a new push subscription is created if the current service worker does not have an existing subscription.
...And 9 more matches
Array.prototype.push() - JavaScript
the push() method adds one or more elements to the end of an array and returns the new length of the array.
... syntax arr.push([element1[, ...[, elementn]]]) parameters elementn the element(s) to add to the end of the array.
... description the push method appends values to an array.
...And 9 more matches
nsIPushSubscription
dom/interfaces/push/nsipushservice.idlscriptable includes information needed to send a push message to privileged code.
... inherits from: nsisupports last changed in gecko 46.0 (firefox 46.0 / thunderbird 46.0 / seamonkey 2.43) each subscription is associated with a unique url generated by the push service.
... this interface resembles pushsubscription from the push api.
...And 7 more matches
History.pushState() - Web APIs
WebAPIHistorypushState
in an html document, the history.pushstate() method adds a state to the browser's session history stack.
... syntax history.pushstate(state, title[, url]) parameters state the state object is a javascript object which is associated with the new history entry created by pushstate().
...if you pass a state object whose serialized representation is larger than this to pushstate(), the method will throw an exception.
...And 7 more matches
PushSubscription - Web APIs
the pushsubscription interface of the push api provides a subcription's url endpoint and allows unsubscription from a push service.
... properties pushsubscription.endpoint read only a usvstring containing the endpoint associated with the push subscription.
... pushsubscription.expirationtime read only a domhighrestimestamp of the subscription expiration time associated with the push subscription, if there is one, or null otherwise.
...And 6 more matches
ServiceWorkerGlobalScope.onpushsubscriptionchange - Web APIs
the serviceworkerglobalscope.onpushsubscriptionchange event of the serviceworkerglobalscope interface is fired to indicate a change in push subscription that was triggered outside the application's control, e.g.
... when browser refresh the push subscription.
... previously, it was defined as the event interface that is fired whenever a push subscription has been invalidated (or is about to become so).
...And 6 more matches
PushManager.getSubscription() - Web APIs
the pushmanager.getsubscription() method of the pushmanager interface retrieves an existing push subscription.
... it returns a promise that resolves to a pushsubscription object containing details of an existing subscription.
... syntax ​pushmanager.getsubscription().then(function(pushsubscription) { ...
...And 5 more matches
PR_PushIOLayer
syntax #include <prio.h> prstatus pr_pushiolayer( prfiledesc *stack, prdescidentity id, prfiledesc *layer); parameters the function has the following parameters: stack a pointer to a prfiledesc object representing the stack.
... returns the function returns one of the following values: if the layer is successfully pushed onto the stack, pr_success.
... if the layer is not successfully pushed onto the stack, pr_failure.
...And 4 more matches
JS_PushArguments
syntax jsval * js_pusharguments(jscontext *cx, void **markp, const char *format, ...); jsval * js_pushargumentsva(jscontext *cx, void **markp, const char *format, va_list ap); name type description cx jscontext * the context in which to perform any necessary conversions.
... various (in js_pusharguments) a variable number of arguments to be converted to jsvals.
... ap va_list (in js_pushargumentsva) the list of arguments to be converted to jsvals.
...And 4 more matches
PushManager.permissionState() - Web APIs
the permissionstate() method of the pushmanager interface returns a promise that resolves to a domstring indicating the permission state of the push manager.
... note: as of firefox 44, the permissions for notifications and push have been merged.
... if permission is granted for notifications, push will also be enabled.
...And 4 more matches
PushManager.registrations() - Web APIs
the registrations method is used to ask the system about existing push endpoint registrations.
... syntax var request = navigator.push.registrations(); return a domrequest object to handle the success or failure of the method call.
... if the method call is successful, the request's result will be an array of pushregistration objects.
...And 4 more matches
PushMessageData - Web APIs
the pushmessagedata interface of the push api provides methods which let you retrieve the push data sent by a server in various formats.
... messages received through the push api are sent encrypted by push services and then automatically decrypted by browsers before they are made accessible through the methods of the pushmessagedata interface.
... methods pushmessagedata.arraybuffer() extracts the data as an arraybuffer object.
...And 4 more matches
PushRegistrationManager - Web APIs
returns an interface to register or unregister a push registration, get an active registration, or check the permission status of the registration.
... this interface has been superceded by pushmanager.
... methods pushregistrationmanager.register() returns a promise that resolves to a pushregistration with details of a new registration.
...And 4 more matches
ServiceWorkerGlobalScope.onpush - Web APIs
the serviceworkerglobalscope.onpush event of the serviceworkerglobalscope interface is fired whenever a push message is received by a service worker via a push server.
... syntax serviceworkerglobalscope.onpush = function(pushevent) { ...
... } self.addeventlistener('push', function(pushevent) { ...
...And 4 more matches
ServiceWorkerGlobalScope: pushsubscriptionchange event - Web APIs
the pushsubscriptionchange event is sent to the global scope of a serviceworker to indicate a change in push subscription that was triggered outside the application's control.
... bubbles no cancelable no interface pushsubscriptionchangeevent event handler property onpushsubscriptionchange usage notes although examples demonstrating how to share subscription related information with the application server tend to use fetch(), this is not necessarily the best choice for real-world use, since it will not work if the app is offline, for example.
... note: in earlier drafts of the specification, this event was defined to be sent when a pushsubscription has expired.
...And 4 more matches
PushEvent.data - Web APIs
WebAPIPushEventdata
the data read-only property of the pushevent interface returns a reference to a pushmessagedata object containing data sent to the pushsubscription.
... syntax var mypushdata = pushevent.data; value a pushmessagedata object.
... examples the following example takes data from a pushevent and displays it on all of the service workers' clients.
...And 3 more matches
PushSubscription.getKey() - Web APIs
the getkey() method of the pushsubscription interface returns an arraybuffer representing a client public key, which can then be sent to a server and used in encrypting push message data.
... auth: an authentication secret, as described in message encryption for web push.
... example reg.pushmanager.getsubscription() .then(function(subscription) { // enable any ui which subscribes / unsubscribes from // push messages.
...And 3 more matches
nsIPushMessage
dom/interfaces/push/nsipushnotifier.idlscriptable a push message sent to a system subscription.
... inherits from: nsisupports last changed in gecko 46.0 (firefox 46.0 / thunderbird 46.0 / seamonkey 2.43) nsipushmessage is the subject of a push-message observer notification.
... this interface resembles pushmessagedata from the push api.
...And 2 more matches
PushManager.hasPermission() - Web APIs
the pushmanager.haspermission() method of the pushmanager interface returns a promise that resolves to the pushpermissionstatus of the requesting webapp, which will be one of granted, denied, or default.
... syntax ​pushmanager.haspermission().then(function(pushpermissionstatus) { ...
... } ); example // tbd specification specification status comment push api working draft defines the pushmanager interface.
...And 2 more matches
PushManager.supportedContentEncodings - Web APIs
the supportedcontentencodings read-only property of the pushmanager interface returns an array of supported content codings that can be used to encrypt the payload of a push message.
... syntax var encodings[] = pushmanager.supportedcontentencodings value an array of strings.
... specifications specification status comment push apithe definition of 'supportedcontentencodings' in that specification.
...And 2 more matches
PushManager.unregister() - Web APIs
in the updated api, a subscription is can be unregistered via the pushsubscription.unsubscribe() method.
... syntax var request = navigator.push.unregister(pushendpoint); properties pushendpoint a pushendpoint to be unregistered.
... if the method call is successful, the request's result will be a pushregistration object representing the endpoint that has been unregistered.
...And 2 more matches
PushMessageData.json() - Web APIs
the json()method of the pushmessagedata interface extracts push message data by parsing it as a json string and returning the result.
... syntax var mydata = pushevent.data.json(); parameters none.
... returns the result of parsing push event data as json.
...And 2 more matches
PushSubscription.endpoint - Web APIs
the endpoint read-only property of the pushsubscription interface returns a usvstring containing the endpoint associated with the push subscription.
... the endpoint takes the form of a custom url pointing to a push server, which can be used to send a push message to the particular service worker instance that subscribed to the push service.
... for this reason, it is a good idea to keep your endpoint a secret, so others do not hijack it and abuse the push functionality.
...And 2 more matches
PushSubscription.options - Web APIs
the options read-only property of the pushsubscription interface is an object containing containing the options used to create the subscription.
... syntax var options = pushsubscription.options value an read-only options object containing the following values: uservisibleonly: a boolean, indicating that the returned push subscription will only be used for messages whose effect is made visible to the user.
... applicationserverkey: a public key your push server will use to send messages to client apps via a push server.
...And 2 more matches
ServiceWorkerRegistration.pushManager - Web APIs
the pushmanager property of the serviceworkerregistration interface returns a reference to the pushmanager interface for managing push subscriptions; this includes support for subscribing, getting an active subscription, and accessing push permission status.
... syntax var pushmanager = serviceworkerregistration.pushmanager; value a pushmanager object.
... examples this.onpush = function(event) { console.log(event.data); // from here we can write the data to indexeddb, send it to any open // windows, display a notification, etc.
...And 2 more matches
PushManager.register() - Web APIs
this method has been superceded by pushmanager.subscribe().
... syntax var request = navigator.push.register(); return a domrequest object to handle the success or failure of the method call.
... note: if you do not need the url any more, please use pushmanager.unregister() to clean up after yourself.
... example var req = navigator.push.register(); req.onsuccess = function(e) { var endpoint = req.result; debug("new endpoint: " + endpoint ); } req.onerror = function(e) { debug("error getting a new endpoint: " + json.stringify(e)); } specification specification status comment push api working draft defines the pushmanager interface.
PushMessageData.arrayBuffer() - Web APIs
the arraybuffer()method of the pushmessagedata interface extracts push message data as an arraybuffer object.
... syntax var myarraybuffer = pushevent.data.arraybuffer(); parameters none.
... examples self.addeventlistener('push', function(event) { var buffer = event.data.arraybuffer(); // do something with your array buffer }); specifications specification status comment push apithe definition of 'arraybuffer()' in that specification.
...tarraybuffer experimentalchrome full support 50edge full support ≤79firefox full support 44notes full support 44notes notes extended support releases (esr) before firefox 78 esr do not support service workers and the push api.ie no support noopera full support 37safari no support nowebview android no support nochrome android full support 50firefox android full support ...
PushMessageData.blob() - Web APIs
the blob()method of the pushmessagedata interface extracts push message data as a blob object.
... syntax var myblob = pushevent.data.blob(); parameters none.
... examples self.addeventlistener('push', function(event) { var blob = event.data.blob(); // do something with your blob }); specifications specification status comment push apithe definition of 'blob()' in that specification.
...internetblob experimentalchrome full support 50edge full support ≤79firefox full support 44notes full support 44notes notes extended support releases (esr) before firefox 78 esr do not support service workers and the push api.ie no support noopera full support 37safari no support nowebview android no support nochrome android full support 50firefox android full support ...
PushMessageData.text() - Web APIs
the text()method of the pushmessagedata interface extracts push message data as a plain text string.
... syntax var mytext = pushevent.data.text(); parameters none.
... examples self.addeventlistener('push', function(event) { var textobj = event.data.text(); // do something with your text }); specifications specification status comment push apithe definition of 'text()' in that specification.
...internettext experimentalchrome full support 50edge full support ≤79firefox full support 44notes full support 44notes notes extended support releases (esr) before firefox 78 esr do not support service workers and the push api.ie no support noopera full support 37safari no support nowebview android no support nochrome android full support 50firefox android full support ...
PushSubscription.expirationTime - Web APIs
the expirationtime read-only property of the pushsubscription interface returns a domhighrestimestamp of the subscription expiration time associated with the push subscription, if there is one, or null otherwise.
... syntax var expirationtime = pushsubscription.expirationtime value a domhighrestimestamp.
... specifications specification status comment push apithe definition of 'expirationtime' in that specification.
PushSubscription.unsubscribe() - Web APIs
the unsubscribe() method of the pushsubscription interface returns a promise that resolves to a boolean when the current subscription is successfully unsubscribed.
... syntax ​pushsubscription.unsubscribe().then(function(boolean) { ...
... example navigator.serviceworker.ready.then(function(reg) { reg.pushmanager.getsubscription().then(function(subscription) { subscription.unsubscribe().then(function(successful) { // you've successfully unsubscribed }).catch(function(e) { // unsubscription failed }) }) }); specifications specification status comment push apithe definition of 'unsubscribe()' in that specification.
ServiceWorkerGlobalScope: push event - Web APIs
the push event is sent to a service worker's global scope (represented by the serviceworkerglobalscope interface) when the service worker has received a push message.
... bubbles no cancelable no interface pushevent event handler property onpush example this example sets up a handler for push events that takes json data, parses it, and dispatches the message for handling based on information contained within the message.
... self.addeventlistener("push", event => { let message = event.data.json(); switch(message.type) { case "init": doinit(); break; case "shutdown": doshutdown(); break; } }, false); specifications specification status comment push apithe definition of 'push' in that specification.
PushSubscription.subscriptionId - Web APIs
the endpoint read-only property of the pushsubscription interface returns a domstring containing the subscription id associated with the push subscription.
... syntax var subid = pushsubscription.subscriptionid; specifications specification status comment push api working draft initial definition browser compatibility the compatibility table on this page is generated from structured data.
PushSubscription.toJSON() - Web APIs
the tojson() method of the pushsubscription interface is a standard serializer: it returns a json representation of the subscription properties, providing a useful shortcut.
... example navigator.serviceworker.ready.then(function(reg) { reg.pushmanager.getsubscription().then(function(subscription) { var mysubscription = subscription.tojson(); // do something with subscription details }) }); specifications specification status comment push apithe definition of 'pushsubscription: tojson' in that specification.
Patches and pushes
below you'll find instructions on creating a patch and pushing it to your repository.
Bytecode Descriptions
constants undefined stack: ⇒ undefined push undefined.
... null stack: ⇒ null push null.
... false, true stack: ⇒ true/false push a boolean constant.
...And 121 more matches
Index - Web APIs
WebAPIIndex
594 canvasrenderingcontext2d.save() api, canvas, canvasrenderingcontext2d, method, reference the canvasrenderingcontext2d.save() method of the canvas 2d api saves the entire state of the canvas by pushing the current state onto a stack.
... 1983 history.pushstate() api, html dom, method, reference, web in an html document, the history.pushstate() method adds a state to the browsers history.
...to see how it works, please create the following files (or git clone https://github.com/giabao/mdn-ajax-nav-example.git ): 1992 working with the history api advanced, dom, history api, history api tutorial html5 introduced the pushstate() and replacestate() methods for add and modifying history entries, respectively.
...And 42 more matches
Deploying our app - Learn web development
we push the code to github, deploy it using netlify, and even show you how to add a simple test into the process.
... although netlify offers a drag and drop deployment service, we are intending to trigger a new deployment to netlify each time we push to a github repo.
...we can commit our code and push to github and the updated code will automatically trigger the entire build routine.
...And 16 more matches
jspage - Archive of obsolete content
e=function(a,b){if(!a.type){a.type=function(c){return($type(c)===b); };}};(function(){var a={array:array,date:date,function:function,number:number,regexp:regexp,string:string};for(var h in a){new native({name:h,initialize:a[h],protect:true}); }var d={"boolean":boolean,"native":native,object:object};for(var c in d){native.typize(d[c],c);}var f={array:["concat","indexof","join","lastindexof","pop","push","reverse","shift","slice","sort","splice","tostring","unshift","valueof"],string:["charat","charcodeat","concat","indexof","lastindexof","match","replace","search","slice","split","substr","substring","tolowercase","touppercase","valueof"]}; for(var e in f){for(var b=f[e].length;b--;){native.genericize(a[e],f[e][b],true);}}})();var hash=new native({name:"hash",initialize:function(a){if($type(a)=...
...$extend(a,document.prototype);},afterimplement:function(b,a){document[b]=document.prototype[b]=a;}});document.prototype={$family:{name:"document"}}; new document(document);array.implement({every:function(c,d){for(var b=0,a=this.length;b<a;b++){if(!c.call(d,this[b],b,this)){return false;}}return true; },filter:function(d,e){var c=[];for(var b=0,a=this.length;b<a;b++){if(d.call(e,this[b],b,this)){c.push(this[b]);}}return c;},clean:function(){return this.filter($defined); },indexof:function(c,d){var a=this.length;for(var b=(d<0)?math.max(0,a+d):d||0;b<a;b++){if(this[b]===c){return b;}}return -1;},map:function(d,e){var c=[]; for(var b=0,a=this.length;b<a;b++){c[b]=d.call(e,this[b],b,this);}return c;},some:function(c,d){for(var b=0,a=this.length;b<a;b++){if(c.call(d,this[b],b,this)){return true; }}...
...return false;},associate:function(c){var d={},b=math.min(this.length,c.length);for(var a=0;a<b;a++){d[c[a]]=this[a];}return d;},link:function(c){var a={}; for(var e=0,b=this.length;e<b;e++){for(var d in c){if(c[d](this[e])){a[d]=this[e];delete c[d];break;}}}return a;},contains:function(a,b){return this.indexof(a,b)!=-1; },extend:function(c){for(var b=0,a=c.length;b<a;b++){this.push(c[b]);}return this;},getlast:function(){return(this.length)?this[this.length-1]:null;},getrandom:function(){return(this.length)?this[$random(0,this.length-1)]:null; },include:function(a){if(!this.contains(a)){this.push(a);}return this;},combine:function(c){for(var b=0,a=c.length;b<a;b++){this.include(c[b]);}return this; },erase:function(b){for(var a=this.length;a--;a){if(this[a]===b){this.splice(a,1);}}return this;}...
...And 15 more matches
Working with the History API - Web APIs
html5 introduced the pushstate() and replacestate() methods for add and modifying history entries, respectively.
... adding and modifying history entries using pushstate() changes the referrer that gets used in the http header for xmlhttprequest objects created after you change the state.
... example of pushstate() method suppose http://mozilla.org/foo.html executes the following javascript: let stateobj = { foo: "bar", } history.pushstate(stateobj, "page 2", "bar.html") this will cause the url bar to display http://mozilla.org/bar.html, but won't cause the browser to load bar.html or even check that bar.html exists.
...And 13 more matches
Release phase
you can pull using both, but you can only push through ssh.
... consequently, if you already have a local clone that you pulled using http, you'll need to modify a config file to tell mercurial to push through ssh.
...configuration before you try pushing, you need to tell ssh which username you wish to use for connecting with hg.mozilla.org.
...And 11 more matches
Deployment and next steps - Learn web development
automatic deployment to gitlab pages for hosting static files there are several online services that allow you to automatically deploy your site whenever you push changes to a git repository.
... most of them involve setting up a deployment pipeline that gets triggered on every git push, and takes care of building and deploying your web site.
...follow the steps listed under the push an existing folder heading: cd your_root_directory # go into your project's root directory git init git remote add origin https://gitlab.com/[your-user]/mdn-svelte-todo.git git add .
...And 8 more matches
QA phase
before a team becomes official, we like to get the localizers comfortable with the hg commands that allow for cloning, pulling, committing, and pushing work to an experimental repository.
... pushing to your repository there are a couple of things you should take note of before you push to your repository: make sure that your files have been encoded in unicode without bom (byte order mark).
... remember that here you are pushing an entire directory, not a .zip archive file or an .xpi lang pack.
...And 8 more matches
Streams - Plugins
the browser calls the plug-in methods npp_newstream, npp_writeready, npp_write, and npp_destroystream to, respectively, create a stream, find out how much data the plug-in can handle, push data into the stream, and delete it.
...stream data can be pushed by the browser, pulled by the plug-in, or saved to a local file and passed to the plug-in.
... normal mode: the browser uses the npp_write method to "push" stream data to the instance incrementally as it is available.
...And 7 more matches
Bootstrapping a new locale
hg allows localizers to work locally on their machines and then "push" changes to their official mozilla repository.
... working with bit bucket before a team becomes official, we like to get the localizers comfortable with the hg commands that allow for cloning, pulling, committing, and pushing work to an experimental repository.
... with that level of authority, you will be able to push and pull and manage the repository remotely.
...And 6 more matches
JXON - Archive of obsolete content
evalue.trim() : onode.nodevalue; } // nodetype is "text" (3) or "cdatasection" (4) else if (onode.nodetype === 1 && !onode.prefix) { // nodetype is "element" (1) sprop = onode.nodename.tolowercase(); vcontent = new jxontree(onode); if (this.hasownproperty(sprop)) { if (this[sprop].constructor !== array) { this[sprop] = [this[sprop]]; } this[sprop].push(vcontent); } else { this[sprop] = vcontent; nlength++; } } } this.keyvalue = parsetext(scollectedtxt); } else { this.keyvalue = null; } if (oparentnode.hasattributes && oxmlparent.hasattributes()) { var oattrib; this.keyattributes = {}; for (nattrlen; nattrlen < oxmlparent.attributes.length; nattrlen++) { oattrib = oxmlparent.attributes.item(nattrlen); ...
...onode.nodevalue.trim() : onode.nodevalue; } else if (onode.nodetype === 1 && !onode.prefix) { sprop = onode.nodename.tolowercase(); vcontent = new jxontree(onode); if (this.hasownproperty(sprop)) { if (this[sprop].constructor !== array) { this[sprop] = [this[sprop]]; } this[sprop].push(vcontent); } else { this[sprop] = vcontent; } } } if (scollectedtxt) { this.keyvalue = parsetext(scollectedtxt); } } if (oparentnode.hasattributes && oxmlparent.hasattributes()) { var oattrib; for (var nattrib = 0; nattrib < oxmlparent.attributes.length; nattrib++) { oattrib = oxmlparent.attributes.item(nattrib); this["@" + oattrib.name.tolowercase()]...
...ype is "text" (3) */ else if (onode.nodetype === 1 && !onode.prefix) { /* nodetype is "element" (1) */ if (nlength === 0) { vresult = {}; } sprop = onode.nodename.tolowercase(); vcontent = getjxontree(onode); if (vresult.hasownproperty(sprop)) { if (vresult[sprop].constructor !== array) { vresult[sprop] = [vresult[sprop]]; } vresult[sprop].push(vcontent); } else { vresult[sprop] = vcontent; nlength++; } } } } if (scollectedtxt) { nlength > 0 ?
...And 4 more matches
MMgc - Archive of obsolete content
with such a leak, you can be pushing hundreds of megabytes of ram real quick.
...at the beginning all the gc roots are pushed onto the work queue.
... items on the queue are conservatively marked and unmarked gc pointers discovered while processing each item are pushed on to the queue.
...And 4 more matches
about:debugging (before Firefox 68) - Firefox Developer Tools
workers the workers page shows your workers, categorised as follows: all registered service workers all registered shared workers other workers, including chrome workers and dedicated workers you can connect the developer tools to each worker, and send push notifications to service workers.
... this section uses a simple serviceworker demo, hosted at https://serviceworke.rs/push-simple/.
... debugging workers for a service worker, if it is already running, you'll see two buttons next to it, labeled "debug" and "push".
...And 4 more matches
Linear-gradient Generator - CSS: Cascading Style Sheets
ic].setpickermode(mode); }; var setcolor = function setcolor(topic, color) { if (pickers[topic]) pickers[topic].setcolor(color); }; var getcolor = function getcolor(topic) { if (pickers[topic]) return new color(pickers[topic].color); }; var subscribe = function subscribe(topic, callback) { if (subscribers[topic] === undefined) subscribers[topic] = []; subscribers[topic].push(callback); }; var unsubscribe = function unsubscribe(callback) { subscribers.indexof(callback); subscribers.splice(index, 1); }; var notify = function notify(topic, value) { if (subscribers[topic] === undefined || subscribers[topic].length === 0) return; var color = new color(value); for (var i in subscribers[topic]) subscribers[topic][i](color); }; var init = function i...
...value = function setvalue(topic, index, send_notify) { if (dropdowns[topic] === undefined || index >= dropdowns[topic].dropmenu.children.length) return; dropdowns[topic].setnodevalue(dropdowns[topic].dropmenu.children[index], send_notify); }; var subscribe = function subscribe(topic, callback) { if (subscribers[topic] === undefined) subscribers[topic] = []; subscribers[topic].push(callback); }; var unsubscribe = function unsubscribe(topic, callback) { var index = subscribers[topic].indexof(callback); subscribers[topic].splice(index, 1); }; var notify = function notify() { if (subscribers[this.topic] === undefined) return; for (var i in subscribers[this.topic]) { subscribers[this.topic][i](this.value); } }; var init = function init() { var elem, ...
...: 5; }; var getnode = function getnode(topic) { return sliders[topic].node; }; var getprecision = function getprecision(topic) { return sliders[topic].precision; }; var getstep = function getstep(topic) { return sliders[topic].step; }; var subscribe = function subscribe(topic, callback) { if (subscribers[topic] === undefined) subscribers[topic] = []; subscribers[topic].push(callback); }; var unsubscribe = function unsubscribe(topic, callback) { subscribers[topic].indexof(callback); subscribers[topic].splice(index, 1); }; var notify = function notify() { if (subscribers[this.topic] === undefined) return; for (var i = 0; i < subscribers[this.topic].length; i++) subscribers[this.topic][i](this.value); }; var createslider = function createslider(t...
...And 4 more matches
Arrays - Learn web development
if you've not already followed that section, create the array first in your console: let myarray = ['manchester', 'london', 'liverpool', 'birmingham', 'leeds', 'carlisle']; first of all, to add or remove an item at the end of an array we can use push() and pop() respectively.
... let's use push() first — note that you need to include one or more items that you want to add to the end of your array.
... try this: myarray.push('cardiff'); myarray; myarray.push('bradford', 'brighton'); myarray; the new length of the array is returned when the method call completes.
...And 3 more matches
TypeScript support in Svelte - Learn web development
let's see a quick example, a simple stack class that let's us push and pop elements, like this: export class stack { private elements = [] push = (element) => this.elements.push(element) pop() { if (this.elements.length === 0) throw new error('the stack is empty!') return this.elements.pop() } } in this case elements is an array of type any, and accordingly the push() and pop() methods both receive and return a variable of type any.
... so it's perfectly valid to do something like the following: const anystack = new stack() anystack.push(1) anystack.push('hello') but what if we wanted to have a stack that would only work with type string?
... we could do the following: export class stringstack { private elements: string[] = [] push = (element: string) => this.elements.push(element) pop(): string { if (this.elements.length === 0) throw new error('the stack is empty!') return this.elements.pop() } } that would work.
...And 3 more matches
Dynamic behavior in Svelte: working with variables and props - Learn web development
next up we'll create a function to add the new todo — addtodo() — which will push a new todo object onto the todos array.
... add this to the bottom of your <script> block inside src/components/todo.svelte: function addtodo() { todos.push({ id: 999, name: newtodoname, completed: false }) newtodoname = '' } note: for the moment we are just assigning the same id to every todo, but don't worry, we will fix that soon.
...that means that the addtodo() function is executed, the element is added to the todos array, but svelte won't detect that the push method modified the array, so it won't refresh the tasks <ul>.
...And 3 more matches
SVN for Localizers
here you'll learn the process of using svn to obtain mozilla website source files from the mozilla servers and pushing your localizations right back to them.
...you use it to copy files from the server to your computer and to push changed or localized files back onto the server.
...also, we use https instead of http because changes can only be pushed back to the mozilla svn repository through a secure connection.
...And 3 more matches
DMD
desktop firefox (linux) build build firefox with these options: ac_add_options --enable-dmd if building via try server, modify browser/config/mozconfigs/linux64/common-opt or a similar file before pushing.
... desktop firefox (mac) build build with these options: ac_add_options --enable-dmd if building via try server, modify browser/config/mozconfigs/macosx64/common-opt or a similar file before pushing.
...first, you will need to push the libdmd.so library to the device so that it can by dynamically loaded by fennec.
...And 3 more matches
Redis Tips
counters set, incr, incrby list manipulation lpush, rpush, lpop, rpop, llen, linsert, lindex, etc.
... event logging lists, zsets, pubsub queues lists (rpush, blpop, blpoprpush, etc.) priority queues zsets membership sets, bitstrings state hashes heartbeats zsets hit counters zsets message broadcast pubsub search reverse indexes (never use keys in production) documentation redis has fantastic documentation.
... use commands like blpop rpush blpoprpush the commands that start with b are blocking.
...And 3 more matches
Window: popstate event - Web APIs
it changes the current history entry to that of the last page the user visited or, if history.pushstate() has been used to add a history entry to the history stack, that history entry is used instead.
... bubbles yes cancelable no interface popstateevent event handler property onpopstate the history stack if the history entry being activated was created by a call to history.pushstate() or was affected by a call to history.replacestate(), the popstate event's state property contains a copy of the history entry's state object.
... note that just calling history.pushstate() or history.replacestate() won't trigger a popstate event.
...And 3 more matches
Color picker tool - CSS: Cascading Style Sheets
ic].setpickermode(mode); }; var setcolor = function setcolor(topic, color) { if (pickers[topic]) pickers[topic].setcolor(color); }; var getcolor = function getcolor(topic) { if (pickers[topic]) return new color(pickers[topic].color); }; var subscribe = function subscribe(topic, callback) { if (subscribers[topic] === undefined) subscribers[topic] = []; subscribers[topic].push(callback); }; var unsubscribe = function unsubscribe(callback) { subscribers.indexof(callback); subscribers.splice(index, 1); }; var notify = function notify(topic, value) { if (subscribers[topic] === undefined || subscribers[topic].length === 0) return; var color = new color(value); for (var i in subscribers[topic]) subscribers[topic][i](color); }; var init = function i...
...: 5; }; var getnode = function getnode(topic) { return sliders[topic].node; }; var getprecision = function getprecision(topic) { return sliders[topic].precision; }; var getstep = function getstep(topic) { return sliders[topic].step; }; var subscribe = function subscribe(topic, callback) { if (subscribers[topic] === undefined) subscribers[topic] = []; subscribers[topic].push(callback); }; var unsubscribe = function unsubscribe(topic, callback) { subscribers[topic].indexof(callback); subscribers[topic].splice(index, 1); }; var notify = function notify() { if (subscribers[this.topic] === undefined) return; for (var i = 0; i < subscribers[this.topic].length; i++) subscribers[this.topic][i](this.value); }; var createslider = function createslider(t...
...orsample(id) { var node = document.createelement('div'); node.classname = 'sample'; this.uid = samples.length; this.node = node; this.color = new color(); node.setattribute('sample-id', this.uid); node.setattribute('draggable', 'true'); node.addeventlistener('dragstart', this.dragstart.bind(this)); node.addeventlistener('click', this.pickcolor.bind(this)); samples.push(this); }; colorsample.prototype.updatebgcolor = function updatebgcolor() { this.node.style.backgroundcolor = this.color.getcolor(); }; colorsample.prototype.updatecolor = function updatecolor(color) { this.color.copy(color); this.updatebgcolor(); }; colorsample.prototype.updatehue = function updatehue(color, degree, steps) { this.color.copy(color); var hue = (steps *...
...And 3 more matches
Array - JavaScript
tions create an array let fruits = ['apple', 'banana'] console.log(fruits.length) // 2 access an array item using the index position let first = fruits[0] // apple let last = fruits[fruits.length - 1] // banana loop over an array fruits.foreach(function(item, index, array) { console.log(item, index) }) // apple 0 // banana 1 add an item to the end of an array let newlength = fruits.push('orange') // ["apple", "banana", "orange"] remove an item from the end of an array let last = fruits.pop() // remove orange (from the end) // ["apple", "banana"] remove an item from the beginning of an array let first = fruits.shift() // remove apple from the front // ["banana"] add an item to the beginning of an array let newlength = fruits.unshift('strawberry') // add to the front // [...
..."strawberry", "banana"] find the index of an item in the array fruits.push('mango') // ["strawberry", "banana", "mango"] let pos = fruits.indexof('banana') // 1 remove an item by index position let removeditem = fruits.splice(pos, 1) // this is how to remove an item // ["strawberry", "mango"] remove items from an index position let vegetables = ['cabbage', 'turnip', 'radish', 'carrot'] console.log(vegetables) // ["cabbage", "turnip", "radish", "carrot"] let pos = 1 let n = 2 let removeditems = vegetables.splice(pos, n) // this is how to remove items, n defines the number of items to be removed, // starting at the index position specified by pos and progressing toward the end of array.
... other methods (e.g., push(), splice(), etc.) also result in updates to an array's length property.
...And 3 more matches
Introduction to progressive web apps - Progressive web apps (PWAs)
an app could be considered a pwa when it meets certain requirements, or implements a set of given features: works offline, is installable, is easy to synchronize, can send push notifications, etc.
... re-engaging with users through the use of system notifications and push messages, leading to more engaged users and better conversion rates.
... for service worker and push specific information, be sure to check the service worker cookbook, a collection of recipes using service workers in modern sites.
...And 3 more matches
Progressive web apps (PWAs)
e explains how a2hs is used, and what you need to do as a developer to allow your users to take advantage of it.how to make pwas installablein this article, we learned about how we can make pwas installable with a properly-configured web manifest, and how the user can then install the pwa with the "add to home screen" feature of their browser.how to make pwas re-engageable using notifications and pushhaving the ability to cache the contents of an app to work offline is a great feature.
...but instead of relying only on user actions, we can do more, using push messages and notifications to automatically re-engage and deliver new content whenever it is available.introduction to progressive web appsthis article provides an introduction to progressive web apps (pwas), discussing what they are and the advantages they offer over regular web apps.making pwas work offline with service workersin this article we took a simple look at how you can make your pwa work offline with service workers.
... progressive loadingin previous articles we covered apis that help us make our js13kpwa example a progressive web app: service workers, web manifests, notifications and push.
...And 3 more matches
How to Write and Land Nanojit Patches - Archive of obsolete content
but don't push that update, as that should only be done by a member of that public repo.] once it passes testing, file the patch to bugzilla (file a bug under the "nanojit" component in the "core" product) and get a review.
... in this case, you have to look through the converted revisions you're about to push (run hg outgoing to list them) and figure out which patch(es) caused the breakage.
... then find the corresponding bug(s) and commit the (hopefully already-reviewed!) tr/tm portion of the patch(es) on top of your current, un-pushed tip.
...And 2 more matches
The box model - Learn web development
padding, margin and border will cause other elements to be pushed away from the box unless we decide to change the display type to inline, elements such as headings (e.g.
...it pushes other elements away from the box.
... we can control all margins of an element at once using the margin property, or each side individually using the equivalent longhand properties: margin-top margin-right margin-bottom margin-left in the example below, try changing the margin values to see how the box is pushed around due to the margin creating or removing space (if it is a negative margin) between this element and the containing element.
...And 2 more matches
Client-side tooling overview - Learn web development
you then "push" changes to a "master" version of the code inside a remote repository stored on a server somewhere.
...with your code in a git repository, you can push it to your own server instance, or use a hosted source control website such as github, gitlab, or bitbucket.
... testing tools these generally take the form of a tool that will automatically run tests against your code to make sure it is correct before you go any further (for example, when you attempt to push changes to a github repo).
...And 2 more matches
Continuous Integration
when you push a commit to mozilla-central or a related repository, it initiates a large chain of builds and tests across multiple types of infrastructure.
... taskcluster and treeherder taskcluster, mozilla's continuous integration (ci) system picks up changes pushed to hg.
... results in treeherder are ordered by mercurial pushes.
...And 2 more matches
Uplifting a localization from Central to Aurora
all you need to do is to push from your l10n-central clone to your aurora repo.
...you can safely push this to l10n-central already, in particular if you don't plan to do further updates on aurora.
... you don't want to push this to aurora before there's been the notification that the status of aurora has been lifted up to beta.
...And 2 more matches
Index
MozillaTechXPCOMIndex
862 nsipushmessage interfaces, interfaces:scriptable, push, xpcom, xpcom interface reference nsipushmessage is the subject of a push-message observer notification.
... 863 nsipushservice interfaces, interfaces:scriptable, push, xpcom, xpcom interface reference push lets a remote server send payloads to a web site, add-on, or component running in the browser.
... nsipushservice supports the push api implementation in firefox, and can be used directly from privileged code to create system subscriptions.
...And 2 more matches
nsIThreadInternal
last changed in gecko 1.9 (firefox 3) inherits from: nsithread method overview void popeventqueue(); void pusheventqueue(in nsithreadeventfilter filter); attributes attribute type description observer nsithreadobserver get/set the current thread observer; set to null to disable observing.
... methods popeventqueue() reverts a call to pusheventqueue().
... pusheventqueue() causes any events currently enqueued on the thread to be suppressed until popeventqueue() is called.
...And 2 more matches
about:debugging - Firefox Developer Tools
workers the workers section shows all the workers you've got registered on your firefox, categorised as follows: all registered service workers all registered shared workers other workers, including chrome workers and dedicated workers you can connect the developer tools to each worker, and send push notifications to service workers.
... this section uses a simple serviceworker demo, hosted at https://serviceworke.rs/push-simple/.
... sending push events to service workers to debug push notifications, you can set a breakpoint in the push event listener.
...And 2 more matches
Permissions.query() - Web APIs
WebAPIPermissionsquery
firefox for example currently supports geolocation, notifications, push, and persistent-storage (see our permissions.webidl file).
... uservisibleonly: (push only, not supported in firefox — see the browser support section below) indicates whether you want to show a notification for every message or be able to send silent push notifications.
... note: as of firefox 44, the permissions for notifications and push have been merged.
...And 2 more matches
Permissions.revoke() - Web APIs
valid values are 'geolocation', 'midi', 'notifications', and 'push'.
... uservisibleonly: (push only, not supported in firefox — see the browser compatibility section below) indicates whether you want to show a notification for every message or be able to send silent push notifications.
... note: as of firefox 44, the permissions for notifications and push have been merged.
...And 2 more matches
ServiceWorkerGlobalScope - Web APIs
push occurs when a server push notification is received.
... also available via the serviceworkerglobalscope.onpush property.
... pushsubscriptionchange occurs when a push subscription has been invalidated, or is about to be invalidated (e.g.
...And 2 more matches
JavaScript Daemons Management - Archive of obsolete content
"px"; } } function prepare () { // build letters list // http://tyleregeto.com/text-animation-in-javascript this.textcontent = ""; aletters.length = 0; for (var ospan, oletter, nletter = 0, nlen = stext.length; nletter < nlen; nletter++) { ospan = document.createelement("span"); ospan.textcontent = stext[nletter]; oletter = { "elem": ospan, "parent": this }; aletters.push(oletter); oletter.pos = math.random() * 50; oletter.elem.style.position = "relative"; this.appendchild(ospan); } } var nmaxdist = 25, aletters = [], stext = "do you feel lucky, punk?", orecompose = new daemon(document.createelement("p"), perform, 33, 30, prepare); onload = function () { orecompose.owner.id = "perform-me"; document.body.appendchild(orecompose.owner); orec...
...ocument.createelement("p"), "create": function () { // build letters list this.target.textcontent = ""; this.letters.length = 0; for (var ospan, oletter, nletter = 0, nlen = stext.length; nletter < nlen; nletter++) { ospan = document.createelement("span"); ospan.textcontent = stext[nletter]; oletter = { "elem": ospan, "parent": this.target }; this.letters.push(oletter); oletter.index = this.numletters; oletter.elem.style.position = "relative"; oletter.val = oletter.elem.textcontent; this.numletters++; this.target.appendchild(ospan); } }, "perform": function (nindex, nlength, bbackw) { for (var oletter, nletter = 0; nletter < this.letters.length; nletter++) { oletter = this.letters[nletter]; if (nlen...
... "px"; } } function prepare () { // build letters list // http://tyleregeto.com/text-animation-in-javascript this.textcontent = ""; aletters.length = 0; for (var ospan, oletter, nletter = 0, nlen = stext.length; nletter < nlen; nletter++) { ospan = document.createelement("span"); ospan.textcontent = stext[nletter]; oletter = { "elem": ospan, "parent": this }; aletters.push(oletter); oletter.pos = math.random() * 50; oletter.elem.style.position = "relative"; this.appendchild(ospan); } } var nmaxdist = 25, aletters = [], stext = "do you feel lucky, punk?", orecompose = new daemon.safe(document.createelement("p"), perform, 33, 30, prepare); onload = function () { orecompose.owner.id = "perform-me"; document.body.appendchild(orecompose.owner); ...
...ocument.createelement("p"), "create": function () { // build letters list this.target.textcontent = ""; this.letters.length = 0; for (var ospan, oletter, nletter = 0, nlen = stext.length; nletter < nlen; nletter++) { ospan = document.createelement("span"); ospan.textcontent = stext[nletter]; oletter = { "elem": ospan, "parent": this.target }; this.letters.push(oletter); oletter.index = this.numletters; oletter.elem.style.position = "relative"; oletter.val = oletter.elem.textcontent; this.numletters++; this.target.appendchild(ospan); } }, "perform": function (nindex, nlength, bbackw) { for (var oletter, nletter = 0; nletter < this.letters.length; nletter++) { oletter = this.letters[nletter]; if (nlen...
NPN_Write - Archive of obsolete content
« gecko plugin api reference « browser side plug-in api summary pushes data into a stream produced by the plug-in and consumed by the browser.
... stream pointer to the stream into which to push the data.
...example this example pushes a snippet of html over a newly created stream, then destroys the stream when it's done.
...*/ err = npn_newstream(instance, "text/html", "_blank", &stream) /* push data into the stream.
Accessibility API cross-reference
definition <dd>, <dfn> <lbody> iconified version of an app (n/a - use either pushbutton or listitem) desktop_icon desktop_icon n/a a specific kind of a graphic - a diagram.
... <p> <p> shows percentage completion for task progressbar progress_bar n/a progressbar page showing properties of something propertypage n/a n/a n/a your average, run-of-the-mill button pushbutton push_button push_button button <button> only one radio button in a group is selectable.
... term dt <lbl> text that might be editable, depending on state text text text textbox (if editable) the text nodes of html elements are uneditable by default, apart from <input type=text>, or those with a contenteditable attribute title or caption of window titlebar n/a n/a <title> a button that can be pushed in or out, but doesn't provide separate indicator of checked state n/a toggle_button toggle_button button with aria-pressed attribute a toolbar toolbar tool_bar tool_bar toolbar the little piece of help text that comes up when you put your mouse over something tooltip tool_tip tool_tip tooltip ...
.../a n/a aria-live=polite low-priority info such as a tip or hint alert_low n/a n/a n/a this object is changing or moving rapidly animated n/a n/a n/a indicates that the user input is currently directed to that object and it is "armed for selection." example: a highlighted menu item or a pressed push button.
Localizing with Mercurial
mercurial allows localizers to work locally (on their machines) and then push (an hg term) changes to a remote repository, which usually is hosted on the mozilla servers (hg.mozilla.org).
...let's face it, it's just more convenient to commit and push your work to the remote repo yourself, rather than creating patches and asking someone else to push them for you.
...the next step will send your changes to your remote repo via push.
... to push to mozilla-hosted repositories, you have to have committer access, and you must edit the file (your-local-hg-root aka the directory you pulled your locale into)/.hg/hgrc (note, this is not your ~/.hgrc) to add these lines (replacing ab-cd with your locale code): [paths] default = https://hg.mozilla.org/l10n-central/ab-cd/ default-push = ssh://hg.mozilla.org/l10n-central/ab-cd/ you’ll also need to tell ssh which account to use for your pushes, too, by editing ~/.ssh/config and adding these lines, where user@host.domain is your account: host hg.mozilla.org user user@host.domain now you can push your work to the repository (and check the result on the dashboard) by entering this command from your local directory: hg push and tah dah!
Hacking Tips
0x7ffff7ff6000: push %r15 0x7ffff7ff6002: push %r14 0x7ffff7ff6004: push %r13 0x7ffff7ff6006: push %r12 0x7ffff7ff6008: push %rbp 0x7ffff7ff6009: push %rbx 0x7ffff7ff600a: movabs $0xea4f80,%r10 0x7ffff7ff6014: mov 0x178(%r10),%r10 0x7ffff7ff601b: mov %rsp,0x40(%r10) 0x7ffff7ff601f: mov (%rsi),%r15 0x7ffff7ff6022: mov %rdi,%r10 0x7f...
...fff7ff6025: push %r10 0x7ffff7ff6027: test $0xf,%spl 0x7ffff7ff602b: je 0x7ffff7ff6032 0x7ffff7ff6031: int3 0x7ffff7ff6032: callq 0x7ffff7ff5000 <------ right here x/64i address (in this case: x/64i 0x7ffff7ff6032).
... (gdb) dprintf js::jit::ionbuilder::ionbuilder, "compiling %s:%d:%d-%d\n", info->script_->scriptsource()->filename_.mtuple.mfirsta, info->script_->lineno_, info->script_->sourcestart_, info->script_->sourceend_ dprintf 1 at 0x7fb4f6a104eb: file /home/nicolas/mozilla/contrib-push/js/src/jit/ionbuilder.cpp, line 159.
...(2 locations) (gdb) dprintf ion.cpp:3196, "invalidate %s:%d:%d-%d\n", co->script_->scriptsource()->filename_.mtuple.mfirsta, co->script_->lineno_, co->script_->sourcestart_, co->script_->sourceend_ dprintf 3 at 0x7fb4f6a0b62a: file /home/nicolas/mozilla/contrib-push/js/src/jit/ion.cpp, line 3196.
JS_AddArgumentFormatter
add or remove a format string handler for js_convertarguments, js_pusharguments, js_convertargumentsva, and js_pushargumentsva.
...when called from js_pushargumentsva, the formatter is invoked thus: formatter(cx, "aa...", js_false, &sp, &ap); where js_false for fromjs means to wrap the c values at ap according to the format specifier and store them at sp, updating ap and sp appropriately.
... the "..." after "aa" is the rest of the format string that was passed into js_{convert,push}arguments{,va}.
... the actual format trailing substring used in each convert or pusharguments call is passed to the formatter, so that one such function may implement several formats, in order to share code.
JS_PopArguments
frees the stack entry allocated by js_pusharguments.
... mark void * pointer to a void * which holds the stack frame pointer previously supplied by js_pusharguments.
... description js_poparguments frees the stack frame pointer previously allocated by js_pusharguments and unroots the jsvals which have been associated with it (those returned by js_pusharguments as well).
... see also js_pusharguments js_convertvalue js_addargumentformatter js_convertarguments bug 542091 ...
Task graph
after a change to the gecko source code is pushed to version-control, jobs for that change appear on treeherder.
... a "decision task" is created to decide what to do with the push.
... the result of each task is sent to treeherder where developers and sheriffs can track the status of the push.
... this means it's easy to add a new job or tweak the parameters of a job in a try push, eventually landing that change on an integration branch.
nsITransactionManager
a value of zero means the transaction manager will execute each transaction, then immediately release all references it has to the transaction without pushing it on the undo stack.
...dotransaction() calls a transaction's nsitransaction.dotransaction() method, then pushes it on the undo stack.
...redotransaction() pops the topmost transaction on the redo stack, calls it's nsitransaction.redotransaction() method, then pushes it on the undo stack.
... undotransaction() pops the topmost transaction on the undo stack, calls it's nsitransaction.undotransaction() method, then pushes it on the redo stack.
Debugger.Frame - Firefox Developer Tools
even though the debuggee and debugger share the same javascript stack, frames pushed for spidermonkey’s calls to handler methods to report events in the debuggee are never considered visible frames.) invocation functions and “debugger” frames aninvocation function is any function in this interface that allows the debugger to invoke code in the debuggee: debugger.object.prototype.call, debugger.frame.prototype.eval, and so on.
...(this is never one of the the debugger’s own frames; those never appear as debugger.frame instances.) push a "debugger" frame on the stack, witholder as its older property.
...for example, debugger.frame.prototype.eval pushes an "eval" frame for code it runs, whereas debugger.object.prototype.call pushes a "call" frame.
...pushing a "debugger" frame makes this continuation explicit, and makes it easier to find the extent of the stack created for the invocation.
Intensive JavaScript - Firefox Developer Tools
0000000; function calculateprimes(iterations, multiplier) { var primes = []; for (var i = 0; i < iterations; i++) { var candidate = i * (multiplier * math.random()); var isprime = true; for (var c = 2; c <= math.sqrt(candidate); ++c) { if (candidate % c === 0) { // not prime isprime = false; break; } } if (isprime) { primes.push(candidate); } } return primes; } function dopointlesscomputationswithblocking() { var primes = calculateprimes(iterations, multiplier); pointlesscomputationsbutton.disabled = false; console.log(primes); } we're just running a (very inefficient) primality test 50 times, for some quite large numbers.
...console.log(primes); pointlesscomputationsbutton.disabled = false; return; } // test this number var candidate = index * (multiplier * math.random()); var isprime = true; for (var c = 2; c <= math.sqrt(candidate); ++c) { if (candidate % c === 0) { // not prime isprime = false; break; } } if (isprime) { primes.push(candidate); } // schedule the next var testfunction = testcandidate.bind(this, index + 1); window.requestanimationframe(testfunction); } var primes = []; var testfunction = testcandidate.bind(this, 0); window.requestanimationframe(testfunction); } let's test this version out: select the radio button labeled "use requestanimationframe" and capture another profile.
... }); } function calculateprimes(iterations, multiplier) { var primes = []; for (var i = 0; i < iterations; i++) { var candidate = i * (multiplier * math.random()); var isprime = true; for (var c = 2; c <= math.sqrt(candidate); ++c) { if (candidate % c === 0) { // not prime isprime = false; break; } } if (isprime) { primes.push(candidate); } } return primes; } in the worker, we have to listen for a message telling us to start, and send a "done" message back when we are done.
...you should see something like this: in this profile we pushed the button three times.
History.state - Web APIs
WebAPIHistorystate
the value is null until the pushstate() or replacestate() method is used.
... examples the code below logs the value of history.state before using the pushstate() method to push a value to the history.
... // should be null because we haven't modified the history stack yet console.log(`history.state before pushstate: ${history.state}`); // now push something on the stack history.pushstate({name: 'example'}, "pushstate example", 'page3.html'); // now state has a value.
... console.log(`history.state after pushstate: ${history.state}`); specificationse specification status comment html living standardthe definition of 'history.state' in that specification.
MediaDeviceInfo.groupId - Web APIs
const getdevicegroup = maindevinfo => { let devlist = []; navigator.mediadevices.enumeratedevices() .then(devices => { devices.foreach(device => { if (device.groupid === maindevinfo.groupid) { devlist.push(device); } }); }); return devlist; }; the getdevicegroup() function takes as input the mediadeviceinfo object describing the device for which a group list is to be built.
...for each device, if its groupid matches the main device's groupid, we push the mediadeviceinfo object onto the list.
... this could be altered easily to either leave out the passed-in device from the returned list, or to place it at the top of the list, by comparing the two objects' deviceid values, only pushing the device onto the result list if it doesn't match.
...assed-in device at the top of the result list, then adds any other members of the group that are found: const getdevicegroup = maindevinfo => { let devlist = [maindevinfo]; navigator.mediadevices.enumeratedevices() .then(devices => { devices.foreach(device => { if ((device.groupid === maindevinfo.groupid) && (device.deviceid !== maindevinfo.deviceid)) { devlist.push(device); } }); }); return devlist; }; ...
NotificationEvent - Web APIs
icationevent experimentalchrome full support 42edge full support ≤18firefox full support 44notes full support 44notes notes extended support releases (esr) before firefox 78 esr do not support service workers and the push api.ie ?
... constructor experimentalchrome full support 42edge full support ≤18firefox full support 44notes full support 44notes notes extended support releases (esr) before firefox 78 esr do not support service workers and the push api.ie ?
... 4.0action experimentalchrome full support 48edge full support ≤18firefox full support 44notes full support 44notes notes extended support releases (esr) before firefox 78 esr do not support service workers and the push api.ie ?
...notification experimentalchrome full support 42edge full support ≤18firefox full support 44notes full support 44notes notes extended support releases (esr) before firefox 78 esr do not support service workers and the push api.ie ?
Using XMLHttpRequest - Web APIs
submitting..."); */ submitdata (odata); } function pushsegment (ofrevt) { this.owner.segments[this.segmentidx] += ofrevt.target.result + "\r\n"; this.owner.status--; processstatus(this.owner); } function plainescape (stext) { /* how should i treat a text/plain form encoding?
... /* enctype is multipart/form-data */ for (nfile = 0; nfile < ofield.files.length; nfile++) { ofile = ofield.files[nfile]; osegmreq = new filereader(); /* (custom properties:) */ osegmreq.segmentidx = this.segments.length; osegmreq.owner = this; /* (end of custom properties) */ osegmreq.onload = pushsegment; this.segments.push("content-disposition: form-data; name=\"" + ofield.name + "\"; filename=\"" + ofile.name + "\"\r\ncontent-type: " + ofile.type + "\r\n\r\n"); this.status++; osegmreq.readasbinarystring(ofile); } } else { /* enctype is application/x-www-form-urlencoded or text/plain or ...
...*/ for (nfile = 0; nfile < ofield.files.length; this.segments.push(ffilter(ofield.name) + "=" + ffilter(ofield.files[nfile++].name))); } } else if ((sfieldtype !== "radio" && sfieldtype !== "checkbox") || ofield.checked) { /* note: this will submit _all_ submit buttons.
...*/ /* field type is not file or is file but is empty */ this.segments.push( this.technique === 3 ?
Box-shadow generator - CSS: Cascading Style Sheets
llback) { elem.addeventlistener("mousedown", function(e) { callback(e); document.addeventlistener("mousemove", callback); }); document.addeventlistener("mouseup", function(e) { document.removeeventlistener("mousemove", callback); }); } var subscribe = function subscribe(topic, callback) { if (subscribers[topic] === undefined) subscribers[topic] = []; subscribers[topic].push(callback); } var unsubscribe = function unsubscribe(topic, callback) { subscribers[topic].indexof(callback); subscribers[topic].splice(index, 1); } var notify = function notify() { if (subscribers[this.topic] === undefined) return; for (var i in subscribers[this.topic]) { subscribers[this.topic][i](this.value); } } var init = function init() { var elem, size; elem =...
...ion getnode(topic) { return buttons[topic].node; } var setvalue = function setvalue(topic, value) { try { buttons[topic].checkbox.checked = value; notify.call(buttons[topic]); } catch(error) { console.log(error, topic, value); } } var subscribe = function subscribe(topic, callback) { if (subscribers[topic] === undefined) subscribers[topic] = []; subscribers[topic].push(callback); } var unsubscribe = function unsubscribe(topic, callback) { subscribers[topic].indexof(callback); subscribers[topic].splice(index, 1); } var notify = function notify() { if (subscribers[this.topic] === undefined) return; for (var i = 0; i < subscribers[this.topic].length; i++) subscribers[this.topic][i](this.checkbox.checked); } var init = function init() { var...
...tener("mousemove", callback); }); } /* * observer */ var setcolor = function setcolor(obj) { if(obj instanceof color !== true) { console.log("typeof instance not color"); return; } color.copy(obj); updateui(); } var subscribe = function subscribe(topic, callback) { if (subscribers[topic] === undefined) subscribers[topic] = []; subscribers[topic].push(callback); } var unsubscribe = function unsubscribe(callback) { subscribers.indexof(callback); subscribers.splice(index, 1); } var notify = function notify(topic, value) { for (var i in subscribers[topic]) subscribers[topic][i](value); } var init = function init() { colorpicker = getelembyid("colorpicker"); hue_area = getelembyid("hue"); gradient_area = gete...
... var dragend = function dragend(e) { if (e.button !== 0) return; if (active === true) { active = false; document.removeeventlistener('mousemove', mousedrag, false); } } var mousedrag = function mousedrag(e) { notify(e.clientx - lastx, e.clienty - lasty); lastx = e.clientx; lasty = e.clienty; } var subscribe = function subscribe(callback) { subscribers.push(callback); } var unsubscribe = function unsubscribe(callback) { var index = subscribers.indexof(callback); subscribers.splice(index, 1); } var notify = function notify(deltax, deltay) { for (var i in subscribers) subscribers[i](deltax, deltay); } return { init : init, subscribe : subscribe, unsubscribe : unsubscribe } })(); /* * element class */ var...
Split Navigation - CSS: Cascading Style Sheets
requirements a common navigation pattern is to have one element pushed away from the others.
...this is how centering a block with auto margins works — you have a margin on each side of the block trying to take up all of the space, thus pushing the block into the middle.
... in this case the left auto margin takes up any available space and pushes the item over to the right.
... you could apply the class push to any item in the list.
Function.prototype.apply() - JavaScript
examples using apply to append an array to another you can use push to append an element to an array.
... and, because push accepts a variable number of arguments, you can also push multiple elements at once.
... but, if you pass an array to push, it will actually add that array as a single element, instead of adding the elements individually.
... const array = ['a', 'b']; const elements = [0, 1, 2]; array.push.apply(array, elements); console.info(array); // ["a", "b", 0, 1, 2] using apply and built-in functions clever usage of apply allows you to use built-in functions for some tasks that would probably have otherwise been written by looping over the array values.
Making PWAs work offline with Service workers - Progressive web apps (PWAs)
if you want to experiment first before pushing your code to production, you can always test on a localhost or setup github pages — both support https.
... var gamesimages = []; for(var i=0; i<games.length; i++) { gamesimages.push('data/img/'+games[i].slug+'.jpg'); } var contenttocache = appshellfiles.concat(gamesimages); then we can manage the install event itself: self.addeventlistener('install', (e) => { console.log('[service worker] install'); e.waituntil( caches.open(cachename).then((cache) => { console.log('[service worker] caching all: app shell and content'); return cache.addall(contenttoc...
...the version number in the cache name is key to this: var cachename = 'js13kpwa-v1'; when this updates to v2, we can then add all of our files (including our new files) to a new cache: contenttocache.push('/pwa-examples/js13kpwa/icons/icon-32.png'); // ...
... service workers are also used when dealing with push notifications — this will be explained in a subsequent article.
File I/O - Archive of obsolete content
however, you can enumerate available drives using the following code: components.utils.import("resource://gre/modules/fileutils.jsm"); var root = new fileutils.file("\\\\."); var drivesenum = root.directoryentries, drives = []; while (drivesenum.hasmoreelements()) { drives.push(drivesenum.getnext().
... // file is the given directory (nsifile) var entries = file.directoryentries; var array = []; while(entries.hasmoreelements()) { var entry = entries.getnext(); entry.queryinterface(components.interfaces.nsifile); array.push(entry); } reading from a file read into a stream or a string this will allow you to read a file without locking up the ui thread while reading.
... createinstance(components.interfaces.nsifileinputstream); istream.init(file, 0x01, 0444, 0); istream.queryinterface(components.interfaces.nsilineinputstream); // read lines into array var line = {}, lines = [], hasmore; do { hasmore = istream.readline(line); lines.push(line.value); } while(hasmore); istream.close(); // do something with read data alert(lines); reading a binary file for instance, to get the data in a png file: var ios = components.classes["@mozilla.org/network/io-service;1"].
Chapter 6: Firefox extensions and XUL applications - Archive of obsolete content
listing 1: calc.js (stage 1) function rpncalc() { } rpncalc.prototype = { init: function() { }, push: function(val) { }, plus: function() { }, pop: function() { } } implement the addition operation create test case begin by creating the test case.
... listing 2: content for test_calc.js (first-round test case) var testcase = mozlab.mozunit.testcase; var assert = mozlab.mozunit.assertions; var tc = new testcase('rpn calc testcase'); var module = new modulemanager(); var rpncalc = module.require('package', 'calc'); tc.tests = { '2 1 +': function() { var calc = new rpncalc.rpncalc(); calc.init(); calc.push(2); calc.push(1); calc.plus(); assert.equals(calc.pop(), 3); } } listing 3: additional content for calc.js function rpncalc() { this.stack = new array(); } rpncalc.prototype = { init: function() { this.stack = new array(); }, push: function(val) { this.stack.push(number(val)); }, _letfunc: function(func) { a = this.pop(); b = this.pop(); this.push(...
... listing 4: test_calc.js (adding sample test case) '2 1 -': function() { var calc = new rpncalc.rpncalc(); calc.init(); calc.push(2); calc.push(1); calc.minus(); assert.equals(calc.pop(), 1); }, listing 5: calc.js (implementing subtraction operation) minus: function() { this._letfunc(this._minus); }, _minus: function(a, b) { return a - b; }, listing 6: calc.js (correcting mistake in implementation of subtraction) _letfunc: function(func) { // correct pop order b = this.pop(); a = this.pop(); this.push(func(a...
New in JavaScript 1.3 - Archive of obsolete content
array.prototype.push(): in javascript 1.2, the push method returned the last element added to an array.
... under javascript 1.3, push returns the new length of the array.
... statements label switch do...while export import built-in objects regexp methods of built-in objects tosource() object.prototype.watch() object.prototype.unwatch() function.arity function.prototype.apply() function.prototype.call() array.prototype.concat() array.prototype.pop() array.prototype.push() array.prototype.shift() array.prototype.slice() array.prototype.splice() string.prototype.concat() string.prototype.concat() string.prototype.match() string.prototype.search() string.prototype.slice() string.prototype.substr() ...
Sharp variables in JavaScript - Archive of obsolete content
examples multiple references var a = { foo:#1=[], bar:#1# }; a.foo.push("hello"); a.bar.push("there!"); alert(a.foo[1]); // "there!" you can avoid using sharp variables by breaking the declaration up into multiple lines.
... var a = { foo:[], bar:undefined }; a.bar = a.foo; a.foo.push("hello"); a.bar.push("there!"); alert(a.foo[1]); // "there!" cyclic references sharp variables can be used to create a circularly linked list in one line of code.
... var a = {val:1, next:{val:2, next:undefined} }; a.next.next = a; a.val; // 1 a.next.val; // 2 a.next.next.val; // 1 a.next.next == a; // true multiple sharp variables var a = #1 = { val:#2=[], next:{val:[], next:{val:#02#, next:#1#}} }; // leading 0s don't matter a.val.push(1); a.next.val.push(2); a.val[0]; // 1 a.next.val[0]; // 2 a.next.next.val[0]; // 1 a.next.next.next.val[0]; // 1 a == a.next.next; // false a == a.next.next.next; // true ...
How do I use GitHub Pages? - Learn web development
your screen should look like this: click create repository; this should bring you to the following page: uploading your files to github on the current page, you are interested in the section …or push an existing repository from the command line.
... git add --all git commit -m 'adding my files to my repository' finally, push the code up to github by going to the github web page you're on and entering into the terminal the second of the two commands we saw the …or push an existing repository from the command line section: git push -u origin master now you need to turn github pages on for your repository.
...then, you need to enter the following commands (pressing enter after each one) to push those changes to github: git add --all git commit -m 'another commit' git push you can replace another commit with a more suitable message to describe what change you just made.
Updating NSPR or NSS in mozilla-central
if you check in an individual change by mistake, your change will be lost when the nspr and nss teams push a new hg tag to mozilla-central.
...em-nss use system installed nss], _use_system_nss=1 ) if test -n "$_use_system_nss"; then am_path_nss(3.16.1, [moz_native_nss=1], [ac_msg_error([you don't have nss installed or your version is too old])]) fi commit the update: $ hg commit -a in order to eliminate any problems related to how nss and nspr are built differently in firefox than they are standalone, you should push your commit to try first.
... push the update: $ hg push ...
Bytecodes
for example, in (a + b) + c you would push a, then push b, then add, then push c, then add, which requires a maximum depth of two expression slots.
...there is always a "top of stack" (tos) that corresponds to the latest value pushed onto the expression stack.
...bytecode listing all opcodes are annotated with a [-popcount, +pushcount] to represent the overall stack-effects their execution.
Introduction to the JavaScript shell
for example, if you enter the javascript function below: function test() { var i = 3; print(i+2); } then run the command dis(test);, you get this output: main: 00000: uint16 3 00003: setvar 0 00006: pop 00007: name "print" 00010: pushobj 00011: getvar 0 00014: uint16 2 00017: add 00018: call 1 00021: pop 00022: stop source notes: 0: 0 [ 0] newline 1: 3 [ 3] decl offset 0 2: 7 [ 4] newline 3: 18 [ 11] xdelta 4: 18 [ 0] pcbase offset 11 dissrc([function]) disassembles the javascript bytecode for the entire program, or for the specified function, showing the source lines.
...program includes a function, dostuff(), like this: function dostuff(input) { print("enter a number: "); var n1 = readline(); print("enter another one: "); var n2 = readline(); print("you entered " + n1 + " and " + n2 + "\n"); } calling dissrc(dostuff) function would give this output: ;------------------------- 10: print("enter a number: "); 00000: 10 name "print" 00003: 10 pushobj 00004: 10 string "enter a number: " 00007: 10 call 1 00010: 10 pop ;------------------------- 11: var n1 = readline(); 00011: 11 name "readline" 00014: 11 pushobj 00015: 11 call 0 00018: 11 setvar 0 00021: 11 pop ;------------------------- 12: print("enter another one: "); 00022: 12 name "print" 00025: 12 pushobj 00026: 12 string "enter another one: " 00...
...029: 12 call 1 00032: 12 pop ;------------------------- 13: var n2 = readline(); 00033: 13 name "readline" 00036: 13 pushobj 00037: 13 call 0 00040: 13 setvar 1 00043: 13 pop ;------------------------- 14: ;------------------------- 15: print("you entered " + n1 + " and " + n2 + "\n"); 00044: 15 name "print" 00047: 15 pushobj 00048: 15 string "you entered " 00051: 15 getvar 0 00054: 15 add 00055: 15 string " and " 00058: 15 add 00059: 15 getvar 1 00062: 15 add 00063: 15 string "\\n" 00066: 15 add 00067: 15 call 1 00070: 15 pop 00071: 15 stop dumpheap(([filename[, start[, tofind[, maxdepth[, toignore]]]]]) dump gc information.
Gecko Roles
role_toolbar represents a toolbar, which is a grouping of controls (push buttons or toggle buttons) that provides easy access to frequently used features.
... role_pushbutton represents a push button control.
...a specialized push button that can be checked or unchecked, but does not provide a separate indicator for the current state.
nsIAccessibleRole
role_toolbar 22 represents a toolbar, which is a grouping of controls (push buttons or toggle buttons) that provides easy access to frequently used features.
... role_pushbutton 43 represents a push button control.
...a specialized push button that can be checked or unchecked, but does not provide a separate indicator for the current state.
nsICategoryManager
ymanager = components.classes["@mozilla.org/categorymanager;1"] .getservice(components.interfaces.nsicategorymanager); var enumerator = categorymanager.enumeratecategories(); var categories = []; while (enumerator.hasmoreelements()) { var item = enumerator.getnext(); var category = item.queryinterface(components.interfaces.nsisupportscstring) categories.push(category.tostring()); } categories.sort(); var categoriesstring = categories.join("\n"); dump(categoriesstring + "\n"); print out a list of app-startup entries this example prints out a list of entries of "app-startup" category.
...anager = components.classes["@mozilla.org/categorymanager;1"] .getservice(components.interfaces.nsicategorymanager); var enumerator = categorymanager.enumeratecategory("app-startup"); var entries = []; while (enumerator.hasmoreelements()) { var item = enumerator.getnext(); var entry = item.queryinterface(components.interfaces.nsisupportscstring) entries.push(entry.tostring()); } entries.sort(); var entriesstring = entries.join("\n"); dump(entriesstring + "\n"); disable currently loaded plugins by type this snippet here shows how to disable plugins that are currently loaded for the file type of pdf.
...from loading in future var stringtypes = ''; var types = []; var pref_disabled_plugin_types = 'plugin.disable_full_page_plugin_for_types'; if (services.prefs.prefhasuservalue(pref_disabled_plugin_types)) { stringtypes = services.prefs.getcharpref(pref_disabled_plugin_types); } if (stringtypes !== '') { types = stringtypes.split(','); } if (types.indexof(content_type) === -1) { types.push(content_type); } services.prefs.setcharpref(pref_disabled_plugin_types, types.join(',')); remarks categories have a variety of uses throughout the mozilla platform.
Demo Addon
if (id.email) info.emails.push(id.email); } data.push(info); } first, we use fixiterator() here to get all accounts in your profile.
... to list some messages of the folder we use: for each (let msghdr in fixiterator(inbox.msgdatabase.enumeratemessages(), ci.nsimsgdbhdr)) { if (++i >= 10 && lastmsghdr != null) break; messages.push({ author: msghdr.mime2decodedauthor, subject: msghdr.mime2decodedsubject, date: new date(msghdr.date/1000), }); //...
...ction are purged from the system */ onitemsremoved: function mylistener_onitemsremoved(aitems, acollection) { }, /* called when our database query completes */ onquerycompleted: function mylistener_onquerycompleted(acollection) { let items = acollection.items; let data = { messages: [], }; for (let i in items) { data.messages.push({ subject: items[i].subject, date: items[i].date, author: items[i].from.value, }); // ...
Mozilla
continuous integration when you push a commit to mozilla-central or a related repository, it initiates a large chain of builds and tests across multiple types of infrastructure.
... supported build targets page moved to the in-tree documentation: https://firefox-source-docs.mozilla.org/build/buildsystem/supported-configurations.html task graph after a change to the gecko source code is pushed to version-control, jobs for that change appear on treeherder.
...for example, this popup notification is displayed when a web site requests geolocation information: using raii classes in mozilla raii classes are useful when two operations (e.g., lock/unlock, addref/release, pushstate/popstate) must be paired.
Gecko Plugin API Reference - Plugins
pop-up menus and dialog boxes event handling for windowless plug-ins streams receiving a stream telling the plug-in when a stream is created telling the plug-in when a stream is deleted finding out how much data the plug-in can accept writing the stream to the plug-in sending the stream in random-access mode sending the stream in file mode sending a stream creating a stream pushing data into the stream deleting the stream example of sending a stream urls getting urls getting the url and displaying the page posting urls posting data to an http server uploading files to an ftp server sending mail memory allocating and freeing memory mac os flushing memory (mac os only) version, ui, and status information displayin...
... npn_pushpopupsenabledstate pushes the popups-enabled state.
... npn_write pushes data into a stream produced by the plug-in and consumed by the browser.
Basic animations - Web APIs
tbyid('cw'); c = cn.getcontext('2d'); for (var i = 0; i < 10; i++) { var r = 30; var x = math.random() * (innerwidth - 2 * r) + r; var y = math.random() * (innerheight - 2 * r) + r; var t = new ob(innerwidth / 2,innerheight / 2,5,"red",math.random() * 200 + 20,2); a.push(t); } //cn.style.backgroundcolor = "#700bc8"; c.linewidth = "2"; c.globalalpha = 0.5; resize(); anim() } window.onresize = function() { resize(); } function resize() { cn.height = innerheight; cn.width = ...
....getseconds()); return n + " : " + o } function coll(t, e) { return t.x < e.x + e.w && t.x + t.w > e.x && t.y < e.y + e.h && t.h + t.y > e.y } function snake() { this.w = 15, this.h = 15, this.dx = 1, this.dy = 1, this.xf = 1, this.yf = 1, this.sn = []; for (var t = { x: w / 2, y: h / 2 }, e = 0; e < 5; e++) this.sn.push(object.assign({}, t)), t.x += this.w; this.draw = function () { var t = d && d.search("arrow") > -1, e = -1; if (t) { var i = { ...this.sn[0] }; if ("arrowup" == d && (i.y -= this.h), "arrowdown" == d && (i.y += this.h), "arrowleft" == d && (i.x -= this.w), "arrowright" == d && (i.x...
...{ c.fillstyle = this.color, c.arc(this.x, this.y, this.b - 5, 0, 2 * math.pi), c.fill(), c.beginpath(), c.arc(this.x, this.y, this.b - 5, 0, math.pi), c.strokestyle = "green", c.linewidth = 10, c.stroke(), c.beginpath(), c.linewidth = 1 }) } function init() { cc.height = h, cc.width = w, c.fillrect(0, 0, w, innerheight); for (var t = 0; t < 10; t++) fa.push(new food); s = new snake(w / 2, h / 2, 400, 4, 4), anima() } function anima() { c.fillstyle = "rgba(0,0,0,0.11)", c.fillrect(0, 0, cc.width, cc.height), fa.foreach(t => t.put()), s.draw(), document.getelementbyid("time").innertext = tmz(), settimeout(() => { requestanimationframe(anima) }, fw) } function emit(t) { key.keydown(t) } ...
In depth: Microtasks and the JavaScript runtime environment - Web APIs
when greetuser("mike") is reached, a context is created for the greetuser() function; this execution context is pushed onto the execution context stack.
... when greetuser("teresa") is reached, a context is created for it and pushed onto the stack.
... when greetuser("veronica") is reached, a context is created for it and pushed onto the stack.
Intersection Observer API - Web APIs
let thresholdsets = [ [], [0.5], [0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0], [0, 0.25, 0.5, 0.75, 1.0] ]; for (let i=0; i<=1.0; i+= 0.01) { thresholdsets[0].push(i); } // add each box, creating a new observer for each for (let i=0; i<4; i++) { let template = document.queryselector("#boxtemplate").content.clonenode(true); let boxid = "box" + (i+1); template.queryselector(".samplebox").id = boxid; wrapper.appendchild(document.importnode(template, true)); // set up the observer for this box observeroptions.threshold = thresh...
... building the array of threshold ratios the buildthresholdlist() function, which builds the list of thresholds, looks like this: function buildthresholdlist() { let thresholds = []; let numsteps = 20; for (let i=1.0; i<=numsteps; i++) { let ratio = i/numsteps; thresholds.push(ratio); } thresholds.push(0); return thresholds; } this builds the array of thresholds—each of which is a ratio between 0.0 and 1.0, by pushing the value i/numsteps onto the thresholds array for each integer i between 1 and numsteps.
... it also pushes 0 to include that value.
PopStateEvent - Web APIs
if the history entry being activated was created by a call to history.pushstate() or was affected by a call to history.replacestate(), the popstate event's state property contains a copy of the history entry's state object.
... note: just calling history.pushstate() or history.replacestate() won't trigger a popstate event.
... the popstate event as an example, a page at http://example.com/example.html running the following code will generate alerts as indicated: window.onpopstate = function(event) { alert("location: " + document.location + ", state: " + json.stringify(event.state)); }; history.pushstate({page: 1}, "title 1", "?page=1"); history.pushstate({page: 2}, "title 2", "?page=2"); history.replacestate({page: 3}, "title 3", "?page=3"); history.back(); // alerts "location: http://example.com/example.html?page=1, state: {"page":1}" history.back(); // alerts "location: http://example.com/example.html, state: null history.go(2); // alerts "location: http://example.com/example.html?page=3...
ServiceWorkerRegistration - Web APIs
serviceworkerregistration.pushmanager read only returns a reference to the pushmanager interface for managing push subscriptions including subscribing, getting an active subscription, and accessing push permission status.
... push apithe definition of 'pushmanager' in that specification.
... working draft adds the pushmanager property.
Advanced techniques: Creating and sequencing audio - Web APIs
the best way to get our voices to play on the beat is to create a scheduling system, whereby we look ahead at when the notes are going to play and push them into a queue.
...// add beat length to last beat time // advance the beat number, wrap to zero currentnote++; if (currentnote === 4) { currentnote = 0; } } we want to create a reference queue for the notes that are to be played, and the functionality to play them using the functions we've previously created: const notesinqueue = []; function schedulenote(beatnumber, time) { // push the note on the queue, even if we're not playing.
... notesinqueue.push({ note: beatnumber, time: time }); if (pads[0].queryselectorall('button')[currentnote].getattribute('aria-checked') === 'true') { playsweep() } if (pads[1].queryselectorall('button')[currentnote].getattribute('aria-checked') === 'true') { playpulse() } if (pads[2].queryselectorall('button')[currentnote].getattribute('aria-checked') === 'true') { playnoise() } if (pads[3].queryselectorall('button')[currentnote].getattribute('aria-checked') === 'true') { playsourcenode(audioctx, sample); } } here we look at the current time and compare it to the time for the next note; when the two match it will call the previous two functions.
WindowEventHandlers.onpopstate - Web APIs
if the activated history entry was created by a call to history.pushstate(), or was affected by a call to history.replacestate(), the popstate event's state property contains a copy of the history entry's state object.
... note: calling history.pushstate() or history.replacestate() won't trigger a popstate event.
... examples for example, a page at http://example.com/example.html running the following code will generate alerts as indicated: window.onpopstate = function(event) { alert("location: " + document.location + ", state: " + json.stringify(event.state)); }; history.pushstate({page: 1}, "title 1", "?page=1"); history.pushstate({page: 2}, "title 2", "?page=2"); history.replacestate({page: 3}, "title 3", "?page=3"); history.back(); // alerts "location: http://example.com/example.html?page=1, state: {"page":1}" history.back(); // alerts "location: http://example.com/example.html, state: null history.go(2); // alerts "location: http://example.com/example.html?page=3...
Border-image generator - CSS: Cascading Style Sheets
: 5; }; var getnode = function getnode(topic) { return sliders[topic].node; }; var getprecision = function getprecision(topic) { return sliders[topic].precision; }; var getstep = function getstep(topic) { return sliders[topic].step; }; var subscribe = function subscribe(topic, callback) { if (subscribers[topic] === undefined) subscribers[topic] = []; subscribers[topic].push(callback); }; var unsubscribe = function unsubscribe(topic, callback) { subscribers[topic].indexof(callback); subscribers[topic].splice(index, 1); }; var notify = function notify() { if (subscribers[this.topic] === undefined) return; for (var i = 0; i < subscribers[this.topic].length; i++) subscribers[this.topic][i](this.value); }; var createslider = function createslider(t...
...rn dropdown; }; var setvalue = function setvalue(topic, index) { if (dropdowns[topic] === undefined || index >= dropdowns[topic].dropmenu.children.length) return; dropdowns[topic].setnodevalue(dropdowns[topic].dropmenu.children[index]); }; var subscribe = function subscribe(topic, callback) { if (subscribers[topic] === undefined) subscribers[topic] = []; subscribers[topic].push(callback); }; var unsubscribe = function unsubscribe(topic, callback) { var index = subscribers[topic].indexof(callback); subscribers[topic].splice(index, 1); }; var notify = function notify() { if (subscribers[this.topic] === undefined) return; for (var i in subscribers[this.topic]) { subscribers[this.topic][i](this.value); } }; var init = function init() { var elem, ...
... }; var getnode = function getnode(topic) { return buttons[topic].node; }; var setvalue = function setvalue(topic, value) { var obj = buttons[topic]; if (obj === undefined) return; obj.checkbox.checked = value; notify.call(obj); }; var subscribe = function subscribe(topic, callback) { if (subscribers[topic] === undefined) subscribers[topic] = []; subscribers[topic].push(callback); }; var unsubscribe = function unsubscribe(topic, callback) { subscribers[topic].indexof(callback); subscribers[topic].splice(index, 1); }; var notify = function notify() { if (subscribers[this.topic] === undefined) return; for (var i = 0; i < subscribers[this.topic].length; i++) subscribers[this.topic][i](this.checkbox.checked); }; var init = function init() { ...
Border-radius generator - CSS: Cascading Style Sheets
} var setunit = function setunit(topic, unit) { var slider = sliders[topic]; if (slider === undefined) return; slider.unit = unit; setvalue(topic, slider.value); } var getnode = function getnode(topic) { return sliders[topic].node; } var subscribe = function subscribe(topic, callback) { if (subscribers[topic] === undefined) subscribers[topic] = []; subscribers[topic].push(callback); } var unsubscribe = function unsubscribe(topic, callback) { subscribers[topic].indexof(callback); subscribers[topic].splice(index, 1); } var notify = function notify() { for (var i in subscribers[this.topic]) { subscribers[this.topic][i](this.value); } } var init = function init() { var elem = document.queryselectorall('.ui-input-slider'); var size = elem.length...
...ttons[topic] = this; } var getnode = function getnode(topic) { return buttons[topic].node; } var setvalue = function setvalue(topic, value) { try { buttons[topic].checkbox.checked = value; } catch(error) { console.log(error); } } var subscribe = function subscribe(topic, callback) { if (subscribers[topic] === undefined) subscribers[topic] = []; subscribers[topic].push(callback); } var unsubscribe = function unsubscribe(topic, callback) { subscribers[topic].indexof(callback); subscribers[topic].splice(index, 1); } var notify = function notify() { for (var i = 0; i < subscribers[this.topic].length; i++) subscribers[this.topic][i](this.checkbox.checked); } var init = function init() { var elem = document.queryselectorall('.ui-checkbox'); var...
... var dragend = function dragend(e) { if (e.button !== 0) return; if (active === true) { active = false; document.removeeventlistener('mousemove', mousedrag, false); } } var mousedrag = function mousedrag(e) { notify(e.clientx - lastx, e.clienty - lasty); lastx = e.clientx; lasty = e.clienty; } var subscribe = function subscribe(callback) { subscribers.push(callback); } var unsubscribe = function unsubscribe(callback) { var index = subscribers.indexof(callback); subscribers.splice(index, 1); } var notify = function notify(deltax, deltay) { for (var i in subscribers) subscribers[i](deltax, deltay); } return { init : init, subscribe : subscribe, unsubscribe : unsubscribe } })(); var subject; var units = ['px...
CSS grids, logical values, and writing modes - CSS: Cascading Style Sheets
if we position an item using absolute positioning, we use these physical keywords as offset values to push the item around.
...using an auto margin to push one item away from the others is a common flexbox trick too, however this also ties the layout to the physical space.
... if you use absolute positioning within a grid area, then you will again be using physical offsets to push the item around inside the grid area.
appearance (-moz-appearance, -webkit-appearance) - CSS: Cascading Style Sheets
syntax /* css basic user interface module level 4 values */ appearance: none; appearance: auto; appearance: menulist-button; appearance: textfield; /* "compat-auto" values, which have the same effect as 'auto' */ appearance: button; appearance: searchfield; appearance: textarea; appearance: push-button; appearance: slider-horizontal; appearance: checkbox; appearance: radio; appearance: square-button; appearance: menulist; appearance: listbox; appearance: meter; appearance: progress-bar; /* partial list of available values in gecko */ -moz-appearance: scrollbarbutton-up; -moz-appearance: button-bevel; /* partial list of available values in webkit/blink (as well as gecko and edge) */ -we...
...-webkit-appearance: menulist; } <div>lorem</div> firefox chrome safari edge meter div{ color: black; -webkit-appearance: meter; } <div>lorem</div> chrome safari firefox progress-bar div{ color: black; -webkit-appearance: progress-bar; } <div>lorem</div> chrome safari firefox push-button div{ color: black; -webkit-appearance: push-button; } <div>lorem</div> chrome safari edge radio div { color: black; -moz-appearance: radio; -webkit-appearance: radio; } <div>lorem</div> firefox chrome safari edge the element is drawn like a radio button, including only the actual "radio button" portion.
... formal definition initial valueautoapplies toall elementsinheritednocomputed valueas specifiedanimation typediscrete formal syntax none | auto | button | textfield | menulist-button | <compat-auto>where <compat-auto> = searchfield | textarea | push-button | slider-horizontal | checkbox | radio | square-button | menulist | listbox | meter | progress-bar examples the following would make an element look like a menulist button: .exampleone { appearance: menulist-button; } see also this jsfiddle for an example showing how you might use appearance: none to apply custom styling to radio buttons and checkboxes.
Array.prototype.reduce() - JavaScript
es }, {}) // countednames is: // { 'alice': 2, 'bob': 1, 'tiff': 1, 'bruce': 1 } grouping objects by a property let people = [ { name: 'alice', age: 21 }, { name: 'max', age: 20 }, { name: 'jane', age: 20 } ]; function groupby(objectarray, property) { return objectarray.reduce(function (acc, obj) { let key = obj[property] if (!acc[key]) { acc[key] = [] } acc[key].push(obj) return acc }, {}) } let groupedpeople = groupby(people, 'age') // groupedpeople is: // { // 20: [ // { name: 'max', age: 20 }, // { name: 'jane', age: 20 } // ], // 21: [{ name: 'alice', age: 21 }] // } bonding arrays contained in an array of objects using the spread operator and initialvalue // friends - an array of objects // where object field "books" is a list of ...
... let myarray = ['a', 'b', 'a', 'b', 'c', 'e', 'e', 'c', 'd', 'd', 'd', 'd'] let myorderedarray = myarray.reduce(function (accumulator, currentvalue) { if (accumulator.indexof(currentvalue) === -1) { accumulator.push(currentvalue) } return accumulator }, []) console.log(myorderedarray) replace .filter().map() with .reduce() using array.filter() then array.map() traverses the array twice, but you can achieve the same effect while traversing only once with array.reduce(), thereby being more efficient.
... const numbers = [-5, 6, 2, 0,]; const doubledpositivenumbers = numbers.reduce((accumulator, currentvalue) => { if (currentvalue > 0) { const doubled = currentvalue * 2; accumulator.push(doubled); } return accumulator; }, []); console.log(doubledpositivenumbers); // [12, 4] running promises in sequence /** * runs promises from array of functions that can return promises * in chained manner * * @param {array} arr - promise arr * @return {object} promise object */ function runpromiseinsequence(arr, input) { return arr.reduce( (promisechain, currentfunction) => promisechain.then(currentfunction), promise.resolve(input) ) } // promise function 1 function p1(a) { retur...
Understanding WebAssembly text format - WebAssembly
although the browser compiles it to something more efficient, wasm execution is defined in terms of a stack machine where the basic idea is that every type of instruction pushes and/or pops a certain number of i32/i64/f32/f64 values to/from a stack.
... for example, local.get is defined to push the value of the local it read onto the stack, and i32.add pops two i32 values (it implicitly grabs the previous two values pushed onto the stack), computes their sum (modulo 2^32) and pushes the resulting i32 value.
...for example, the following module contains two functions — one just returns the value 42, the other returns the result of calling the first plus one: (module (func $getanswer (result i32) i32.const 42) (func (export "getanswerplus1") (result i32) call $getanswer i32.const 1 i32.add)) note: i32.const just defines a 32-bit integer and pushes it onto the stack.
Porting the Library Detector - Archive of obsolete content
he user interface, the content script will just run when it's loaded, collect the array of library names, and post it back to main.js: function testlibraries() { var win = unsafewindow; var librarylist = []; for(var i in ld_tests) { var passed = ld_tests[i].test(win); if (passed) { var libraryinfo = { name: i, version: passed.version }; librarylist.push(libraryinfo); } } self.postmessage(librarylist); } testlibraries(); main.js responds to that message by fetching the tab corresponding to that worker using worker.tab, and adding the array of library names to that tab's libraries property: pagemod.pagemod({ include: "*", contentscriptwhen: 'end', contentscriptfile: (data.url('library-detector.js')), onattach: function(worker) ...
...{ worker.on('message', function(librarylist) { if (!worker.tab.libraries) { worker.tab.libraries = []; } librarylist.foreach(function(library) { if (worker.tab.libraries.indexof(library) == -1) { worker.tab.libraries.push(library); } }); if (worker.tab == tabs.activetab) { updatewidgetview(worker.tab); } }); } }); the content script is executed once for every window.onload event, so it will run multiple times when a single page containing multiple iframes is loaded.
page-mod - Archive of obsolete content
for example, if you maintain a list of workers attached to a page-mod: var workers = []; var pagemod = require("sdk/page-mod").pagemod({ include: ['*'], contentscriptwhen: 'ready', contentscriptfile: data.url('pagemod.js'), onattach: function(worker) { workers.push(worker); } }); you can remove workers when they are no longer valid by listening to detach: var workers = []; function detachworker(worker, workerarray) { var index = workerarray.indexof(worker); if(index != -1) { workerarray.splice(index, 1); } } var pagemod = require("sdk/page-mod").pagemod({ include: ['*'], contentscriptwhen: 'ready', contentscriptfile: data.url('pagemod.
...js'), onattach: function(worker) { workers.push(worker); worker.on('detach', function () { detachworker(this, workers); }); } }); cleaning up on add-on removal content scripts receive a detach message when the add-on that attached them is disabled or removed: you can use this in the content script to undo any changes that you've made.
Creating annotations - Archive of obsolete content
updating main.js go back to main.js and add the code to create the selector into the main function: var selector = pagemod.pagemod({ include: ['*'], contentscriptwhen: 'ready', contentscriptfile: [data.url('jquery-1.4.2.min.js'), data.url('selector.js')], onattach: function(worker) { worker.postmessage(annotatorison); selectors.push(worker); worker.port.on('show', function(data) { console.log(data); }); worker.on('detach', function () { detachworker(this, selectors); }); } }); make sure the name you use to load jquery matches the name of the jquery version you downloaded.
...ving the show message we assign the content of the message to the panel using a new property annotationanchor, and show the panel: var selector = pagemod.pagemod({ include: ['*'], contentscriptwhen: 'ready', contentscriptfile: [data.url('jquery-1.4.2.min.js'), data.url('selector.js')], onattach: function(worker) { worker.postmessage(annotatorison); selectors.push(worker); worker.port.on('show', function(data) { annotationeditor.annotationanchor = data; annotationeditor.show(); }); worker.on('detach', function () { detachworker(this, selectors); }); } }); execute cfx run again, activate the annotator, move your mouse over an element and click the element when it is highlighted.
Displaying annotations - Archive of obsolete content
torage.annotations) { worker.postmessage(simplestorage.storage.annotations); } worker.port.on('show', function(data) { annotation.content = data; annotation.show(); }); worker.port.on('hide', function() { annotation.content = null; annotation.hide(); }); worker.on('detach', function () { detachworker(this, matchers); }); matchers.push(worker); } }); when a new page is loaded the function assigned to onattach is called.
...her's workers, and edit handlenewannotation to call this new function when the user enters a new annotation: function updatematchers() { matchers.foreach(function (matcher) { matcher.postmessage(simplestorage.storage.annotations); }); } function handlenewannotation(annotationtext, anchor) { var newannotation = new annotation(annotationtext, anchor); simplestorage.storage.annotations.push(newannotation); updatematchers(); } annotation panel the annotation panel just shows the content of an annotation.
Developing for Firefox Mobile - Archive of obsolete content
then execute jpm-mobile run with some extra options: jpm-mobile run --adb /path/to/adb in the command shell, you should see something like: launching mobile application with intent name org.mozilla.fennec pushing the addon to your device starting: intent { act=android.activity.main cmp=org.mozilla.fennec/.app (has extras) } --------- beginning of /dev/log/main --------- beginning of /dev/log/system could not read chrome manifest 'file:///data/data/org.mozilla.fennec/chrome.manifest'.
...the easiest way is probably to copy the signed xpi somewhere on the device: adb push my-addon.xpi /mnt/sdcard/ then open firefox mobile and type this into the address bar: file:///mnt/sdcard/my-addon.xpi the browser should open the xpi and ask if you want to install it.
Delayed Execution - Archive of obsolete content
let idx = delay.timers.push(timer) - 1; return idx; } delay.timers = []; function repeat(timeout, func) { let timer = new timer(function () { func(); }, timeout, ci.nsitimer.type_repeating_slack); // store a reference to the timer so that it's not reaped before it fires.
... let idx = delay.timers.push(timer) - 1; return idx; } repeat.timers = []; // repeat a task every 1200ms repeat(1200, doathing); // do something 320ms from now delay(320, dosomething); ...
Useful Mozilla Community Sites - Archive of obsolete content
you just need to upload a new version of your extension, and once it's approved it will be pushed as an update to all your users.
... if you decide to host your own extension, you'll have to learn about the update system in order to push your own updates.
Index - Archive of obsolete content
on windows and unix, pressing alt+a is a convenient way to push that button.
... 3674 npn_write api, gecko, npapi, plugins, reference pushes data into a stream produced by the plug-in and consumed by the browser.
Block and Line Layout Cheat Sheet - Archive of obsolete content
mlastframe may also be directly manipulated if a line is split, or if frames are pushed from one line to the next.
...mframe is initialized to the containing inline frame's perframedata when a new perspandata is pushed in nslinelayout::beginspan.
Tabs - Archive of obsolete content
ArchiveMozillaJetpackUITabs
blah(lengthstringfocusedstringtostringstringpopstringpushstringreversestringshiftstringsortstringsplicestringunshiftstring)this is some default text lengththe number of open tabsstring focusedthe current tab in your browserstring tostringstuffstring popstuffstring pushstuffstring reversestuffstring shiftstuffstring sortstuffstring splicestuffstring unshiftstuffstring onready()when the inherited document is fully loaded.
... urlurl to be openedstring jetpack.tabs.open("http://www.example.com/"); blah(lengthstringfocusedstringtostringstringpopstringpushstringreversestringshiftstringsortstringsplicestringunshiftstring)this is some default text lengththe number of open tabsstring focusedthe current tab in your browserstring tostringstuffstring popstuffstring pushstuffstring reversestuffstring shiftstuffstring sortstuffstring splicestuffstring unshiftstuffstring onready()when the inherited document is fully loaded.
Merging TraceMonkey Repo - Archive of obsolete content
if the sheriff gives you permission to land, hg push -r default ssh://hg.mozilla.org/tracemonkey and hg push ssh://hg.mozilla.org/mozilla-central if you can't push to mozilla-central because somebody ignored the "ask the sheriff" rule and pushed there anyway, that's typical, and it just means you have to repeat the above process.
... once you've pushed to mozilla-central, do a bugzilla search for bugs that are not marked as resolved but have fixed-in-tracemonkey in the whiteboard.
Abc Assembler Tests - Archive of obsolete content
* * ***** end license block ***** */ function main() { getlocal0 pushscope findproperty start pushstring "instructions that start with the letter l" callpropvoid start 1 newfunction .function_id(runtest) getlocal0 call 0 findproperty end callpropvoid end 0 returnvoid } function runtest() { // test null <= null == true findproperty compare_stricteq pushstring "null lessequals null" // testname pushtrue // expected...
... pushnull pushnull lessequals // actual callpropvoid compare_stricteq 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_typeer...
Tamarin build documentation - Archive of obsolete content
tamarin buildbot tryserver the tryserver/sandbox is setup to allow users to push any code changes that they would like to have tested in the automated build/test process prior to actually pushing the changes.
...push any changes that you want to test into this repository.
appendNotification - Archive of obsolete content
popup: null }; buttons.push(button1); let button2 = { isdefault: true, accesskey: "2", label: "button 2", callback: testnotificationbutton2callback, type: "", // if a popup, then must be: "menu-button" or "menu".
... popup: null }; buttons.push(button2); //appendnotification( label , value , image (url) , priority , buttons, eventcallback ) notifybox.appendnotification("my notification text", "test notification unique id", "chrome://browser/content/aboutrobots-icon.png", notifybox.priority_info_high, buttons, testnotificationcallback); } ...
Sorting and filtering a custom tree view - Archive of obsolete content
this way, we don't have to deal with //mapping between the two data.push({name: "leonardo", description: "leader", weapon: "dual katanas"}); data.push({name: "michaelangelo", description: "party dude", weapon: "nunchaku"}); data.push({name: "donatello", description: "does machines", weapon: "bo"}); data.push({name: "raphael", description: "cool, but rude", weapon: "sai"}); data.push({name: "splinter", description: "rat", weapon: "walking stick"}); data.push(...
...{name: "shredder", description: "armored man", weapon: "blades"}); data.push({name: "casey jones", description: "goalie masked man", weapon: "hockey stick"}); data.push({name: "april o'neil", description: "journalist", weapon: "none"}); } if (filtertext == "") { //show all of them table = data; } else { //filter out the ones we want to display table = []; data.foreach(function(element) { //we'll match on every property for (var i in element) { if (prepareforcomparison(element[i]).indexof(filtertext) != -1) { table.push(element); break; } } }); } sort(); //restore scroll position if (topvisiblerow) { settopvisiblerow(topvisiblerow); } } //generic custom tree view stuff function treeview(table) { this.rowcount = table.length; this.getcel...
NPN_SetValue - Archive of obsolete content
variable values the function can set: nppvpluginwindowbool: sets windowed/windowless mode for plugin display; true=windowed, false=windowless nppvplugintransparentbool: sets transparent mode for display of a plugin; true=transparent, false=opaque nppvjavaclass nppvpluginwindowsize nppvplugintimerinterval nppvpluginscriptableinstance nppvpluginscriptableiid nppvjavascriptpushcallerbool: specifies whether you are pushing or popping the jscontext off the stack nppvpluginkeeplibraryinmemory: tells browser that the plugin dll should live longer than usual nppvpluginneedsxembed nppvpluginscriptablenpobject nppvformvalue nppvplugindrawingmodel value the value of the specified variable to be set.
... nppvjavascriptpushcallerbool sets whether you are pushing or popping the appropriate jscontext off the stack (see the two-way scriptability article on the mozilla plugins project page for more details).
Tamarin Tracing Build Documentation - Archive of obsolete content
tamarin buildbot tryserver the tryserver/sandbox is setup to allow users to push any code changes that they would like to have tested in the automated build/test process prior to actually pushing the changes.
...push any changes that you want to test into this repository.
Array.unobserve() - Archive of obsolete content
examples unobserving an array var arr = [1, 2, 3]; var observer = function(changes) { console.log(changes); } array.observe(arr, observer); ​ arr.push(4); // [{type: "splice", object: <arr>, index: 3, removed:[], addedcount: 1}] array.unobserve(arr, observer); arr.pop(); // the callback wasn't called using an anonymous function var persons = ['khalid', 'ahmed', 'mohammed']; array.observe(persons, function (changes) { console.log(changes); }); persons.shift(); // [{type: "splice", object: <arr>, index: 0, removed: [ "khalid" ], addedcoun...
...t: 0 }] array.unobserve(persons, function (changes) { console.log(changes); }); persons.push('abdullah'); // [{type: "splice", object: <arr>, index: 2, removed: [], addedcount: 1 }] // the callback will always be called ...
Styling the Amazing Netscape Fish Cam Page - Archive of obsolete content
rather than try to fight it or push the image below the h3's element box, i let the image mostly overlap the h3, but with a slight offset.
... div.card {float: left; width: 45%; margin: 1em 2% 0 2%;} div.card img {float: left; position: relative; z-index: 10; margin: 4px 0 0 0; border: 1px solid #339;} div.card h3 {margin: 0 0 0 4px; padding: 0.2em 0 1px 150px; border: 1px solid #339; border-left: 5px double #339; background: #eec url(body-bg-tan.jpg) bottom left no-repeat fixed; color: #339;} note how the image is pushed downward four pixels, while the h3 is pushed rightward four pixels.
Common causes of memory leaks in extensions - Extensions
for example, in xul overlay code: var contentwindows = []; function inbrowserxuloverlay(contentwindow) { // forgetting or failing to pop the content window thing again contentwindows.push(contentwindow); } this will keep the content window compartments alive until the browser window is closed.
... for example: var windows = []; function injavascriptcodemodule(window) { // forgetting or failing to pop the window again windows.push(window); } both of these cases can happen if you forget to declare local variables with var or let, which means they end up belonging to the global scope.
Game promotion - Game development
honesty is key and you should be authentic, because nobody likes boring press releases or pushy advertisements.
...remember to not be too pushy on telling everyone about your games — you're not a walking advertisement.
Desktop gamepad controls - Game development
to update the state of the gamepad's currently pressed buttons we will need a function that will do exactly that on every frame: function gamepadupdatehandler() { buttonspressed = []; if(controller.buttons) { for(var b=0; b<controller.buttons.length; b++) { if(controller.buttons[b].pressed) { buttonspressed.push(b); } } } } we first reset the buttonspressed array to get it ready to store the latest info we'll write to it from the current frame.
...d buttons: update: function() { gamepadapi.buttons.cache = []; for(var k=0; k<gamepadapi.buttons.status.length; k++) { gamepadapi.buttons.cache[k] = gamepadapi.buttons.status[k]; } gamepadapi.buttons.status = []; var c = gamepadapi.controller || {}; var pressed = []; if(c.buttons) { for(var b=0,t=c.buttons.length; b<t; b++) { if(c.buttons[b].pressed) { pressed.push(gamepadapi.buttons.layout[b]); } } } var axes = []; if(c.axes) { for(var a=0,x=c.axes.length; a<x; a++) { axes.push(c.axes[a].tofixed(2)); } } gamepadapi.axes.status = axes; gamepadapi.buttons.status = pressed; return pressed; }, the function above clears the buttons cache, and copies their status from the previous frame to the cache.
Plug-in Development Overview - Gecko Plugin API Reference
in the browser's normal-mode streams, the browser calls the plug-in to inform it that the stream was created and to push more data.
... in streams produced by the plug-in, by contrast, the plug-in calls netscape functions to create a stream, push data into it, and delete it.
Introduction to CSS layout - Learn web development
in the example below we float a <div> left, and give it a margin on the right to push the text away from the element.
...these serve to move the affected element down and to the right — this might seem like the opposite of what you were expecting, but you need to think of it as the element being pushed on its left and top sides, which result in it moving right and down.
Legacy layout methods - Learn web development
they work by giving items a size, and pushing them around to line them up in a way that looks like a grid.
...if we wanted to leave an empty column space before the first container — or between containers — we would need to create an offset class to add a left margin to our site to push it across the grid visually.
Positioning - Learn web development
illogical as it may initially sound, this is just the way that relative positioning works — you need to think of an invisible force that pushes the specified side of the positioned box, moving it in the opposite direction.
... so for example, if you specify top: 30px;, a force pushes the top of the box, causing it to move downwards by 30px.
Sending forms through JavaScript - Learn web development
for( name in data ) { urlencodeddatapairs.push( encodeuricomponent( name ) + '=' + encodeuricomponent( data[name] ) ); } // combine the pairs into a single string and replace all %-encoded spaces to // the '+' character; matches the behaviour of browser form submissions.
...now for the javascript: const btn = document.queryselector('button'); function senddata( data ) { const xhr = new xmlhttprequest(), fd = new formdata(); // push our data into our formdata object for( name in data ) { fd.append( name, data[ name ] ); } // define what happens on successful data submission xhr.addeventlistener( 'load', function( event ) { alert( 'yeah!
Adding a new todo form: Vue events, methods, and models - Learn web development
this can be done by pushing a new to-do item object to the array containing our new data.
... update your addtodo() method like so: addtodo(todolabel) { this.todoitems.push({id:uniqueid('todo-'), label: todolabel, done: false}); } try testing your form again, and you should see new to-do items get appended to the end of the list.
Introduction to automated testing - Learn web development
with the in-built image editor, highlight your screenshot before you push it to your colleagues.
... using the mark as bug button you can push bugs to numerous third-party tools such as jira, asana, trello, and more.
Introducing a complete toolchain - Learn web development
in the next chapter we will push to a github code repository, which will cause a cascade effect that (should) deploy all the software to a home on the web.
... you can interact with git in a number of different ways, from using the command line to issue commands, to using a git gui app to issue the same commands by pushing buttons, or even from directly inside your code editor, as seen in the visual studio code example below: anyway, installing git is all we need to do for now.
Examples
ecoder, textencoder, os} = cu.import("resource://gre/modules/osfile.jsm", {}); /* files: an array of file paths */ function readtextfiles(files) { let promises = [], decoder = new textdecoder(); for (let i = 0; i < files.length; i++) { let promise = os.file.read(files[i]) promise = promise.then(function onsuccess(array) { return decoder.decode(array); }); promises.push(promise); } return promise.all(promises); } let folder = "/path/to/folder"; let promise = readtextfiles([ os.path.join(folder, "read.me"), os.path.join(folder, "home.html") ]); promise.then( function onsuccess(filescontent) { // filescontent is an array of strings; each string is the content of one file.
...reason) + '"'); } ); function myuserdefinedpromise() { try { var mysubpromises = []; var imagepaths = ['http://www.mozilla.org/media/img/firefox/favicon.png', 'https://developer.cdn.mozilla.net/media/redesign/img/favicon32.png']; [].foreach.call(imagepaths, function(path) { let myimage = new image(); let loadthisimagepromise = promise.defer(); mysubpromises.push(loadthisimagepromise.promise); myimage.onload = function() { loadthisimagepromise.resolve('succesfully loaded image at path = "' + path + '" the width of this image is = "' + this.naturalwidth + '".'); if (!this.naturalwidth) { loadthisimagepromise.reject('image loaded but it has 0 width at path = "' + path + '" the naturalwidth was 0'); } } myi...
Index
mercurial allows localizers to work locally (on their machines) and then push (an hg term) changes to a remote repository, which usually is hosted on the mozilla servers (hg.mozilla.org).
...here you'll learn the process of using svn to obtain mozilla website source files from the mozilla servers and pushing your localizations right back to them.
Localization sign-off reviews
once you have made the formal request in bugzilla and you have pushed your work into your l10n repo, refer to the dashboards to follow your review's progress.
...once they are fixed, push your fix to your repo, attach it to the corresponding bug using the same mercurial revision number as before, and then request another review.
Localization technical reviews
here is a detailed overview of what a technical review is and who it's meant for: a technical review: is performed as a qa measure on a revision pushed to a new locale's l10n aurora repo in mercurial.
...once they are fixed, push your fix to your repo, attach it to the corresponding bug using the same mercurial revision number as before, and then request another review.
What every Mozilla translator should know
when you create a bug, if you want the person in charge of the l10n to follow up your bug you should cc: l10n@mozilla.com if you choose to make changes to your localization, you should make the changes local to your disk, push them to your hg repository on merucial, test the changes on a nightly/tinderbox build, fix any errors if some are found and test again, and send the new changeset id as your "opt-in" revisions to the l10-drivers.
...search plugins, protocol handlers, rss/live bookmarks), you will need to upload a patch with the suggested changes to bugzilla and get approval before pushing those changes to your hg repository.
I/O Functions
a layer can be pushed onto or popped from an existing stack of layers.
...for example, the following lines of code are equivalent: rv = pr_pushiolayer(stack, pr_top_io_layer, my_layer); rv = pr_pushiolayer(stack, pr_getlayersidentity(stack), my_layer); pr_getuniqueidentity pr_getnameforidentity pr_getlayersidentity pr_getidentitieslayer pr_getdefaultiomethods pr_createiolayerstub pr_pushiolayer pr_popiolayer ...
Creating JavaScript tests
checking in completed tests tests are usually reviewed and pushed just like any other code change.
... it is ok under certain circumstances to push new tests to certain repositories without a code review.
Index
425 js_poparguments jsapi_reference, obsolete, spidermonkey js_poparguments frees the stack frame pointer previously allocated by js_pusharguments and unroots the jsvals which have been associated with it (those returned by js_pusharguments as well).
... 428 js_pusharguments jsapi reference, obsolete, spidermonkey js_pusharguments provides a convenient way to translate a series of native c/c++ values to jsvals with a single function call.
JIT Optimization Strategies
call call_inline a function call f(x) usually pushes a frame onto the call stack.
... inlining a call site conceptually copies the body of the callee function and pastes it in place of the call site and avoids pushing a new execution frame.
Running Automated JavaScript Tests
ing command: ./mach jstestbrowser to run specific test, you can use --filter=pattern command-line argument, where pattern is a regexp pattern that is tested against file:///{path_to_obj_dir}/dist/test-stage/jsreftest/tests/jsreftest.html?test={relative_path_to_test_from_js/src/tests} string: ./mach jstestbrowser --filter=pattern running jstests on treeherder when viewing treeherder after a push to the mozilla repositories, jstests run in the browser are shown as r(j) meaning "javascript reftests".
... running jit-tests on treeherder when viewing treeherder after a push to the mozilla repositories, jit-tests are run by calling make check, and appear under b.
Introduction to XPCOM for the DOM
pushing this concept to its maximum, a class can be "purely virtual" if it declares methods without implementing any of them.
...xpcom pushes this concept to the extreme.
nsIDocShell
load_cmd_pushstate 0x8 returned by the loadtype attribute when the page has used history.pushstate() character set source constants these constants are not exposed to script.
... addstate() do either a history.pushstate() or history.replacestate() operation, depending on the value of areplace.
nsISHEntry
in practice, two entries a and b will have the same docidentifier if we arrived at b by clicking an anchor link in a or if b was created by a's calling history.pushstate().
... statedata nsistructuredclonecontainer get/set data associated with this history state via a pushstate() call, serialized using structured clone.
nsIThreadEventFilter
the nsithreadeventfilter interface may be implemented to determine whether or not an event may be accepted by a nested event queue; see nsithreadinternal.pusheventqueue() for more information.
...(see nsithreadinternal.pusheventqueue()) warning: this method must not make any calls on the thread object.
Adding items to the Folder Pane
first, our "numbers" container looks like this: let containerrow = { _numbers: 3, id: "numbers-main-container", text: "numbers", level: 0, open: false, _children: null, get children() { if (!this._children) { this._children = []; for (var i = 1; i <= this._numbers; i++) this._children.push(new numberrow(i)); } return this._children; }, getproperties: function gne_getprops() { // put your css attributes here }, command: function gne_command() { // just going to alert, to do something here components.classes["@mozilla.org/embedcomp/prompt-service;1"] .getservice(components.interfaces.nsipromptservice) ...
...thus, our _insert function becomes _insert: function gne__insert() { // only insert our nodes into the "all" mode if (gfoldertreeview.mode != "all") return; gfoldertreeview._rowmap.push(containerrow); }, right now, clicking on these additional items has no effect.
Browser Side Plug-in API - Plugins
npn_pushpopupsenabledstate pushes the popups-enabled state.
... npn_write pushes data into a stream produced by the plug-in and consumed by the browser.
Plug-in Development Overview - Plugins
in the browser's normal-mode streams, the browser calls the plug-in to inform it that the stream was created and to push more data.
... in streams produced by the plug-in, by contrast, the plug-in calls netscape functions to create a stream, push data into it, and delete it.
Accessibility Inspector - Firefox Developer Tools
each item has two properties listed: role — the role this item has on the page (e.g., pushbutton, or footer).
... actions — a list of actions that can be performed on the item, for example, a pushbutton would have "press" listed, while a link would have "jump" listed.
Monster example - Firefox Developer Tools
j = 0; j &lt; namelength; j++) { name += chars[randomint(0, chars.length-1)]; } return name; } this.name = randomname(); this.eyecount = randomint(0, 25); this.tentaclecount = randomint(0, 250); } function makemonsters() { var monsters = { "friendly": [], "fierce": [], "undecided": [] }; for (var i = 0; i &lt; monster_count; i++) { monsters.friendly.push(new monster()); } for (var i = 0; i &lt; monster_count; i++) { monsters.fierce.push(new monster()); } for (var i = 0; i &lt; monster_count; i++) { monsters.undecided.push(new monster()); } console.log(monsters); } var makemonstersbutton = document.getelementbyid("make-monsters"); makemonstersbutton.addeventlistener("click", makemonsters); the page contains a button: when ...
...you push the button, the code creates some monsters.
Waterfall - Firefox Developer Tools
tion calculateprimes() { console.time("calculating..."); var primes = []; for (var i = 0; i < iterations; i++) { var candidate = i * (multiplier * math.random()); var isprime = true; for (var c = 2; c <= math.sqrt(candidate); ++c) { if (candidate % c === 0) { // not prime isprime = false; break; } } if (isprime) { primes.push(candidate); } } console.timeend("calculating..."); return primes; } the waterfall's output will look something like this: the marker is labeled with the argument you passed to console.time(), and when you select the marker, you can see the program stack in the right-hand sidebar.
...mes = []; for (var i = 0; i < iterations; i++) { if (i % 10 == 0) { console.timestamp(i.tostring()); } var candidate = i * (multiplier * math.random()); var isprime = true; for (var c = 2; c <= math.sqrt(candidate); ++c) { if (candidate % c === 0) { // not prime isprime = false; break; } } if (isprime) { primes.push(candidate); } } console.timeend("calculating..."); return primes; } in the waterfall you'll now see something like this: ...
AudioContext.createMediaStreamDestination() - Web APIs
stopping the mediarecorder causes the dataavailable event to fire, and the event data is pushed into the chunks array.
... b.addeventlistener("click", function(e) { if (!clicked) { mediarecorder.start(); osc.start(0); e.target.innerhtml = "stop recording"; clicked = true; } else { mediarecorder.stop(); osc.stop(0); e.target.disabled = true; } }); mediarecorder.ondataavailable = function(evt) { // push each chunk (blobs) in an array chunks.push(evt.data); }; mediarecorder.onstop = function(evt) { // make blob out of our blobs, and open it.
Background Tasks API - Web APIs
that function, enqueuetask(), looks like this: function enqueuetask(taskhandler, taskdata) { tasklist.push({ handler: taskhandler, data: taskdata }); totaltaskcount++; if (!taskhandle) { taskhandle = requestidlecallback(runtaskqueue, { timeout: 1000 }); } schedulestatusrefresh(); } enqueuetask() accepts as input two parameters: taskhandler is a function which will be called to handle the task.
... to enqueue the task, we push an object onto the tasklist array; the object contains the taskhandler and taskdata values under the names handler and data, respectively, then increment totaltaskcount, which reflects the total number of tasks which have ever been enqueued (we don't decrement it when tasks are removed from the queue).
Document.createTreeWalker() - Web APIs
example the following example goes through all nodes in the body, reduces the set of nodes to elements, simply passes through as acceptable each node (it could reduce the set in the acceptnode() method instead), and then makes use of tree walker iterator that is created to advance through the nodes (now all elements) and push them into an array.
... var treewalker = document.createtreewalker( document.body, nodefilter.show_element, { acceptnode: function(node) { return nodefilter.filter_accept; } }, false ); var nodelist = []; var currentnode = treewalker.currentnode; while(currentnode) { nodelist.push(currentnode); currentnode = treewalker.nextnode(); } specifications specification status comment domthe definition of 'document.createtreewalker' in that specification.
ExtendableMessageEvent.data - Web APIs
examples when the following code is used inside a service worker to respond to a push messages by sending the data received via pushmessagedata to the main context via a channel message, the event object of onmessage will be a extendablemessageevent.
... var port; self.addeventlistener('push', function(e) { var obj = e.data.json(); if(obj.action === 'subscribe' || obj.action === 'unsubscribe') { port.postmessage(obj); } else if(obj.action === 'init' || obj.action === 'chatmsg') { port.postmessage(obj); } }); self.onmessage = function(e) { console.log(e.data); port = e.ports[0]; } specifications specification status comment service workersthe definition of 'extendablemessageevent.data' in that specification.
ExtendableMessageEvent.lastEventId - Web APIs
examples when the following code is used inside a service worker to respond to a push messages by sending the data received via pushmessagedata to the main context via a channel message, the event object of onmessage will be a extendablemessageevent.
... var port; self.addeventlistener('push', function(e) { var obj = e.data.json(); if(obj.action === 'subscribe' || obj.action === 'unsubscribe') { port.postmessage(obj); } else if(obj.action === 'init' || obj.action === 'chatmsg') { port.postmessage(obj); } }); self.onmessage = function(e) { console.log(e.lasteventid); port = e.ports[0]; } specifications specification status comment service workersthe definition of 'extendablemessageevent.lasteventid' in that specification.
ExtendableMessageEvent.origin - Web APIs
examples when the following code is used inside a service worker to respond to a push messages by sending the data received via pushmessagedata to the main context via a channel message, the event object of onmessage will be a extendablemessageevent.
... var port; self.addeventlistener('push', function(e) { var obj = e.data.json(); if(obj.action === 'subscribe' || obj.action === 'unsubscribe') { port.postmessage(obj); } else if(obj.action === 'init' || obj.action === 'chatmsg') { port.postmessage(obj); } }); self.onmessage = function(e) { console.log(e.origin); port = e.ports[0]; } specifications specification status comment service workersthe definition of 'extendablemessageevent.origin' in that specification.
ExtendableMessageEvent.ports - Web APIs
examples when the following code is used inside a service worker to respond to a push messages by sending the data received via pushmessagedata to the main context via a channel message, the event object of onmessage will be a extendablemessageevent.
... var port; self.addeventlistener('push', function(e) { var obj = e.data.json(); if(obj.action === 'subscribe' || obj.action === 'unsubscribe') { port.postmessage(obj); } else if(obj.action === 'init' || obj.action === 'chatmsg') { port.postmessage(obj); } }); self.onmessage = function(e) { port = e.ports[0]; } specifications specification status comment service workersthe definition of 'extendablemessageevent.ports' in that specification.
ExtendableMessageEvent.source - Web APIs
examples when the following code is used inside a service worker to respond to a push messages by sending the data received via pushmessagedata to the main context via a channel message, the event object of onmessage will be a extendablemessageevent.
... var port; self.addeventlistener('push', function(e) { var obj = e.data.json(); if(obj.action === 'subscribe' || obj.action === 'unsubscribe') { port.postmessage(obj); } else if(obj.action === 'init' || obj.action === 'chatmsg') { port.postmessage(obj); } }); self.onmessage = function(e) { console.log(e.source); port = e.ports[0]; } specifications specification status comment service workersthe definition of 'extendablemessageevent.source' in that specification.
Using microtasks in JavaScript with queueMicrotask() - Web APIs
const messagequeue = []; let sendmessage = message => { messagequeue.push(message); if (messagequeue.length === 1) { queuemicrotask(() => { const json = json.stringify(messagequeue); messagequeue.length = 0; fetch("url-of-receiver", json); }); } }; when sendmessage() gets called, the specified message is first pushed onto the message queue array.
...that means that any further calls to sendmessage() made in the interim will push their messages onto the message queue, but because of the array length check before adding a microtask, no new microtask is enqueued.
Ajax navigation example - Web APIs
t("unknown error."); } function ajaxload () { var vmsg, nstatus = this.status; switch (nstatus) { case 200: vmsg = json.parse(this.responsetext); document.title = opageinfo.title = vmsg.page; document.getelementbyid(stargetid).innerhtml = vmsg.content; if (bupdateurl) { history.pushstate(opageinfo, opageinfo.title, opageinfo.url); bupdateurl = false; } break; default: vmsg = nstatus + ": " + (ohttpstatus[nstatus] || "unknown"); switch (math.floor(nstatus / 100)) { /* case 1: // informational 1xx ...
...new xmlhttprequest(); bisloading = true; oreq.onload = ajaxload; oreq.onerror = ajaxerror; if (spage) { opageinfo.url = filterurl(spage, null); } oreq.open("get", filterurl(opageinfo.url, "json"), true); oreq.send(); oloadingbox.parentnode || document.body.appendchild(oloadingbox); } function requestpage (surl) { if (history.pushstate) { bupdateurl = true; getpage(surl); } else { /* ajax navigation is not supported */ location.assign(surl); } } function processlink () { if (this.classname === sajaxclass) { requestpage(this.href); return false; } return true; } function init () { opagein...
Timing element visibility with the Intersection Observer API - Web APIs
function handlerefreshinterval() { let redrawlist = []; visibleads.foreach(function(adbox) { let previoustime = adbox.dataset.totalviewtime; updateadtimer(adbox); if (previoustime != adbox.dataset.totalviewtime) { redrawlist.push(adbox); } }); if (redrawlist.length) { window.requestanimationframe(function(time) { redrawlist.foreach(function(adbox) { drawadtimer(adbox); }); }); } } the array redrawlist will be used to keep a list of all the ads which need to be redrawn during this refresh cycle, since it may not be exactly the same as the elapsed time due to system activity or becaus...
...if it's changed, then we push the ad onto the redrawlist so we know it needs to be updated during the next animation frame.
MediaRecorder: dataavailable event - Web APIs
> { console.log("data available after mediarecorder.stop() called."); var audio = document.createelement('audio'); audio.controls = true; var blob = new blob(chunks, { 'type' : 'audio/ogg; codecs=opus' }); var audiourl = window.url.createobjecturl(blob); audio.src = audiourl; console.log("recorder stopped"); }); mediarecorder.addeventlistener('dataavailable', (event) => { chunks.push(event.data); }); ...
...stop = function(e) { console.log("data available after mediarecorder.stop() called."); var audio = document.createelement('audio'); audio.controls = true; var blob = new blob(chunks, { 'type' : 'audio/ogg; codecs=opus' }); var audiourl = window.url.createobjecturl(blob); audio.src = audiourl; console.log("recorder stopped"); } mediarecorder.ondataavailable = function(e) { chunks.push(e.data); } ...
Recording a media element - Web APIs
starting media recording the startrecording() function handles starting the recording process: function startrecording(stream, lengthinms) { let recorder = new mediarecorder(stream); let data = []; recorder.ondataavailable = event => data.push(event.data); recorder.start(); log(recorder.state + " for " + (lengthinms/1000) + " seconds..."); let stopped = new promise((resolve, reject) => { recorder.onstop = resolve; recorder.onerror = event => reject(event.name); }); let recorded = wait(lengthinms).then( () => recorder.state == "recording" && recorder.stop() ); return promise.all([ stopped, recorded ...
...the event handler simply pushes the blob onto the data array.
Node - Web APIs
WebAPINode
*/ removeallchildren(document.body) recurse through child nodes the following function recursively calls a callback function for each node contained by a root node (including the root itself): function eachnode(rootnode, callback) { if (!callback) { const nodes = [] eachnode(rootnode, function(node) { nodes.push(node) }) return nodes } if (false === callback(rootnode)) { return false } if (rootnode.haschildnodes()) { const nodes = rootnode.childnodes for (let i = 0, l = nodes.length; i < l; ++i) { if (false === eachnode(nodes[i], callback)) { return } } } } syntax eachnode(rootnode, callback) description recursively calls a function for each descendant ...
... grep to do the searching: function grep(parentnode, pattern) { const matches = [] let endscan = false eachnode(parentnode, function(node){ if (endscan) { return false } // ignore anything which isn't a text node if (node.nodetype !== node.text_node) { return } if (typeof pattern === "string") { if (-1 !== node.textcontent.indexof(pattern)) { matches.push(node) } } else if (pattern.test(node.textcontent)) { if (!pattern.global) { endscan = true matches = node } else { matches.push(node) } } }) return matches } for example, to find text nodes that contain typos: const typos = ["teh", "adn", "btu", "adress", "youre", "msitakes"] const pattern = new regexp("\\b(" + typos.join("|") +...
Notifications API - Web APIs
note: as of firefox 44, the permissions for notifications and push have been merged.
... if permission is granted for notifications, push will also be enabled.
Using the Permissions API - Web APIs
the only two apis currently recognized by the permissions api in chrome are geolocation and notification, with firefox also recognizing push and webmidi.
...for example, the pushpermissiondescriptor should also contain a boolean that specifies if uservisibleonly is true or false.
Multi-touch interaction - Web APIs
// save this event for later processing (this could be part of a // multi-touch interaction) and update the background color push_event(ev); if (logevents) log("pointerdown: name = " + ev.target.id, ev); update_background(ev); } pointer move the pointermove handler is called when the pointer moves.
... function get_cache(ev) { // return the cache for this event's target element switch(ev.target.id) { case "target1": return evcache1; case "target2": return evcache2; case "target3": return evcache3; default: log("error with cache handling",ev); } } function push_event(ev) { // save this event in the target's cache var cache = get_cache(ev); cache.push(ev); } function remove_event(ev) { // remove this event from the target's cache var cache = get_cache(ev); for (var i = 0; i < cache.length; i++) { if (cache[i].pointerid == ev.pointerid) { cache.splice(i, 1); break; } } } update background color the background color of the touch ...
ReadableStream - Web APIs
fetch("https://www.example.org/").then((response) => { const reader = response.body.getreader(); const stream = new readablestream({ start(controller) { // the following function handles each data chunk function push() { // "done" is a boolean and value a "uint8array" reader.read().then(({ done, value }) => { // is there no more data to read?
... if (done) { // tell the browser that we have finished sending data controller.close(); return; } // get the data and send it to the browser via the controller controller.enqueue(value); push(); }); }; push(); } }); return new response(stream, { headers: { "content-type": "text/html" } }); }); specifications specification status comment streamsthe definition of 'readablestream' in that specification.
ReadableStreamDefaultReader - Web APIs
fetch("https://www.example.org/").then((response) => { const reader = response.body.getreader(); const stream = new readablestream({ start(controller) { // the following function handles each data chunk function push() { // "done" is a boolean and value a "uint8array" return reader.read().then(({ done, value }) => { // is there no more data to read?
... if (done) { // tell the browser that we have finished sending data controller.close(); return; } // get the data and send it to the browser via the controller controller.enqueue(value); push(); }); }; push(); } }); return new response(stream, { headers: { "content-type": "text/html" } }); }); specifications specification status comment streamsthe definition of 'readablestreamdefaultreader' in that specification.
Service Worker API - Web APIs
they will also allow access to push notifications and background sync apis.
... reacting to push messages: start up a service worker to send users a message to tell them new content is available.
Touch events - Web APIs
function handlestart(evt) { evt.preventdefault(); console.log("touchstart."); var el = document.getelementbyid("canvas"); var ctx = el.getcontext("2d"); var touches = evt.changedtouches; for (var i = 0; i < touches.length; i++) { console.log("touchstart:" + i + "..."); ongoingtouches.push(copytouch(touches[i])); var color = colorfortouch(touches[i]); ctx.beginpath(); ctx.arc(touches[i].pagex, touches[i].pagey, 4, 0, 2 * math.pi, false); // a circle at the start ctx.fillstyle = color; ctx.fill(); console.log("touchstart:" + i + "."); } } this calls event.preventdefault() to keep the browser from continuing to process the touch event (this also prevents ...
... after that, we iterate over all the touch objects in the list, pushing them onto an array of active touchpoints and drawing the start point for the draw as a small circle; we're using a 4-pixel wide line, so a 4-pixel radius circle will show up neatly.
WebGLRenderingContext.commit() - Web APIs
the webglrenderingcontext.commit() method pushes frames back to the original htmlcanvaselement, if the context is not directly fixed to a specific canvas.
... // push frames back to the original htmlcanvaselement gl.commit(); specifications specification status comment html living standardthe definition of 'the commit() method of the offscreencanvas object's rendering context' in that specification.
Using Web Workers - Web APIs
var results = []; function resultreceiver(event) { results.push(parseint(event.data)); if (results.length == 2) { postmessage(results[0] + results[1]); } } function errorreceiver(event) { throw event.data; } onmessage = function(event) { var n = parseint(event.data); if (n == 0 || n == 1) { postmessage(n); return; } for (var i = 1; i <= 2; i++) { var worker = new worker('fibonacci.js'); worker.onmessage = resultreceiver; ...
...they will also allow access to push notifications and background sync apis.
WindowOrWorkerGlobalScope.setInterval() - Web APIs
<script> function typewriter (sselector, nrate) { function clean () { clearinterval(nintervid); btyping = false; bstart = true; ocurrent = null; asheets.length = nidx = 0; } function scroll (osheet, npos, beraseandstop) { if (!osheet.hasownproperty('parts') || amap.length < npos) { return true; } var orel, bexit = false; if (amap.length === npos) { amap.push(0); } while (amap[npos] < osheet.parts.length) { orel = osheet.parts[amap[npos]]; scroll(orel, npos + 1, beraseandstop) ?
...ar nintervid, ocurrent = null, btyping = false, bstart = true, nidx = 0, spart = "", asheets = [], amap = []; this.rate = nrate || 100; this.play = function () { if (btyping) { return; } if (bstart) { var aitems = document.queryselectorall(sselector); if (aitems.length === 0) { return; } for (var nitem = 0; nitem < aitems.length; nitem++) { asheets.push(new sheet(aitems[nitem])); /* uncomment the following line if you have previously hidden your elements via css: */ // aitems[nitem].style.visibility = "visible"; } bstart = false; } nintervid = setinterval(typewrite, this.rate); btyping = true; }; this.pause = function () { clearinterval(nintervid); btyping = false; }; this.terminate = f...
Web APIs
WebAPI
apihigh resolution timehistory apiiimage capture apiindexeddbintersection observer apillong tasks api mmedia capabilities api media capture and streamsmedia session apimedia source extensions mediastream recordingnnavigation timingnetwork information api ppage visibility apipayment request apiperformance apiperformance timeline apipermissions apipointer eventspointer lock apiproximity events push api rresize observer apiresource timing apisserver sent eventsservice workers apistoragestorage access apistreams ttouch eventsuurl apivvibration apivisual viewport wweb animationsweb audio apiweb authentication apiweb crypto apiweb notificationsweb storage apiweb workers apiwebglwebrtcwebvttwebxr device apiwebsockets api interfaces this is a list of all the interfaces (that is, types of ob...
...anceobserverentrylist performancepainttiming performanceresourcetiming performanceservertiming performancetiming periodicwave permissionstatus permissions photocapabilities plugin pluginarray point pointerevent popstateevent positionoptions processinginstruction progressevent promiserejectionevent publickeycredential publickeycredentialcreationoptions publickeycredentialrequestoptions pushevent pushmanager pushmessagedata pushregistrationmanager pushsubscription r rtcansweroptions rtccertificate rtcconfiguration rtcdtmfsender rtcdtmftonechangeevent rtcdatachannel rtcdatachannelevent rtcdtlstransport rtcerror rtcerrorevent rtcicecandidate rtcicecandidateinit rtcicecandidatepair rtcicecandidatepairstats rtcicecandidatestats rtcicecandidatetype rtcicecomponent rtcicec...
HTML To MSAA - Accessibility
notes a role_system_ link n/a value of @href attribute state_system_ selectable if @name attribute is presented state_system_ linked if @href attribute is presented or click event listener is registered state_system_ traversed if link is traversed n/a "jump" if @href is valid n/a br role_system_ whitespace '\n' (new line char) state_system_ readonly n/a n/a n/a button role_system_ pushbutton from child nodes n/a state_system_ focusable state_system_ default if @type attribute has value "submit" n/a "press" n/a caption bstr role n/a n/a n/a description_for (0x100f), points to table element div bstr role n/a n/a n/a n/a n/a n/a fieldset role_system_ grouping text equivalent from child legend element n/a n/a labelled_by (1003), points to legend element n/a n/a ...
...a n/a n/a n/a n/a n/a img, input @type=image role_system_ graphic from @alt attribute, empty @alt attribute means name can't be calculated at all n/a state_system_ animated if image has more than one frame n/a "showlongdesc" if @longdesc attribute is presented n/a if @usemap attribute is used then image accessible has children for each map item input @type=button, submit, reset role_system_ pushbutton from @value attribute, @alt attribute, default label, @src attribute, @data attribute n/a state_system_ default if @type attribute has value "submit" n/a "press" n/a input @type=text, textarea role_system_ text n/a value property of input dom element state_system_ readonly if @readonly attribute is used n/a "activate" n/a input @type=password role_system_ text n/a n/a state_system...
Aligning Items in a Flex Container - CSS: Cascading Style Sheets
each side tries to take as much space as it can, and so the block is pushed into the middle.
... in this live example, i have flex items arranged simply into a row with the basic flex values, and the class push has margin-left: auto.
Typical use cases of Flexbox - CSS: Cascading Style Sheets
card layout pushing footer down whether you use flexbox or css grid to lay out a list of card components, these layout methods only work on direct children of the flex or grid component.
...as this is the only item that can grow, it takes up all available space in the flex container and pushes the footer to the bottom.
In Flow and Out of Flow - CSS: Cascading Style Sheets
this is why, to make space around a floated item, you must add a margin to the item, in order to push the line boxes away from it.
... relative positioning and flow if you give an item relative positioning with position: relative it remains in flow, however you are then able to use the offset values to push it around.
Introduction to formatting contexts - CSS: Cascading Style Sheets
in a horizontal writing mode line, horizontal padding, borders and margin will be applied to the element and push the text away left and right.
...vertical padding and borders will be applied but may overlap content above and below as, in the inline formatting context, the line boxes will not be pushed apart by padding and borders.
Box alignment in CSS Grid Layout - CSS: Cascading Style Sheets
by setting the margin to auto on both sides, it pushes the block into the middle as both margins attempt to take all of the space.
...you can see how the content is now pushed over to the right side of the area, as the auto margin takes up remaining space, after room for the content of that item has been assigned: * {box-sizing: border-box;} .wrapper { border: 2px solid #f76707; border-radius: 5px; background-color: #fff4e6; } .wrapper > div { border: 2px solid #ffa94d; border-radius: 5px; background-color: #ffd8a8; padding: 1em; color: #d9480f; } .wrapper { display: grid; grid-template-columns: repeat(3, 100px); grid-template-rows: repeat(3, 100px); height: 500px; width: 500px; grid-gap: 10px; grid-template-areas: "a a b" "a a b" "c d d"; } .item1 { grid-area: a; margin-left: auto; } .item...
Realizing common layouts using CSS Grid Layout - CSS: Cascading Style Sheets
we also don’t need special classes to pull or push things, to indent them into the grid.
...i can then use an auto margin on the .cta to push this bar down to the bottom of the box.
Overview of CSS Shapes - CSS: Cascading Style Sheets
this will further shorten the line boxes of any content wrapping the shape, pushing it away from the shape itself.
...change the margin to push the text further away from the path the shape would take by default.
Event reference
push pushevent push api a service worker has received a push message.
... pushsubscriptionchange pushevent push api a pushsubscription has expired.
Evolution of HTTP - HTTP
since 2005, the set of apis available to web pages greatly increased and several of these apis created extensions, mostly new specific http headers, to the http protocol for specific purposes: server-sent events, where the server can push occasional messages to the browser.
... it allows a server to populate data in a client cache, in advance of it being required, through a mechanism called the server push.
HTTP conditional requests - HTTP
the client first reads the original files, modifies them, and finally pushes them to the server: unfortunately, things get a little inaccurate as soon as we take into account concurrency.
...what happens next is very unfortunate: when they commit back to the server, the modifications from the first client are discarded by the next client push, as this second client is unaware of the first client's changes to the resource.
HTTP headers - HTTP
WebHTTPHeaders
other accept-push-policy a client can express the desired push policy for a request by sending an accept-push-policy header field in the request.
... push-policy a push-policy defines the server behaviour regarding push when processing a request.
A re-introduction to JavaScript (JS tutorial) - JavaScript
another way of iterating over an array that was added with ecmascript 5 is foreach(): ['dog', 'cat', 'hen'].foreach(function(currentvalue, index, array) { // do something with currentvalue or array[index] }); if you want to append an item to an array simply do it like this: a.push(item); arrays come with a number of methods.
... a.push(item1, ..., itemn) appends items to the end of the array.
Concurrency model and the event loop - JavaScript
when bar calls foo, a second frame is created and pushed on top of the first one containing foo's arguments and local variables.
...the time value represents the (minimum) delay after which the message will actually be pushed into the queue.
Indexed collections - JavaScript
let myarray = new array('wind', 'rain', 'fire') let list = myarray.join(' - ') // list is "wind - rain - fire" push() adds one or more elements to the end of an array and returns the resulting length of the array.
... let myarray = new array('1', '2') myarray.push('3') // myarray is now ["1", "2", "3"] pop() removes the last element from an array and returns that element.
Array.prototype.filter() - JavaScript
this algorithm is exactly equivalent to the one specified in ecma-262, 5th edition, assuming that fn.call evaluates to the original value of function.prototype.bind(), and that array.prototype.push() has its original value.
...ords = words.filter( (word, index, arr) => { arr[index+1] +=' extra' return word.length < 6 }) console.log(modifiedwords) // notice there are three words below length 6, but since they've been modified one is returned // ["spray"] // appending new words words = ['spray', 'limit', 'exuberant', 'destruction','elite', 'present'] const appendedwords = words.filter( (word, index, arr) => { arr.push('new') return word.length < 6 }) console.log(appendedwords) // only three fits the condition even though the `words` itself now has a lot more words with character length less than 6 // ["spray" ,"limit" ,"elite"] // deleting words words = ['spray', 'limit', 'exuberant', 'destruction', 'elite', 'present'] const deletewords = words.filter( (word, index, arr) => { arr.pop() return word.leng...
Array.prototype.forEach() - JavaScript
converting a for loop to foreach const items = ['item1', 'item2', 'item3'] const copyitems = [] // before for (let i = 0; i < items.length; i++) { copyitems.push(items[i]) } // after items.foreach(function(item){ copyitems.push(item) }) printing the contents of an array note: in order to display the content of an array in the console, you can use console.table(), which prints a formatted version of the array.
... function flatten(arr) { const result = [] arr.foreach((i) => { if (array.isarray(i)) { result.push(...flatten(i)) } else { result.push(i) } }) return result } // usage const nested = [1, 2, 3, [4, 5, [6, 7], 8, 9]] flatten(nested) // [1, 2, 3, 4, 5, 6, 7, 8, 9] specifications specification ecmascript (ecma-262)the definition of 'array.prototype.foreach' in that specification.
Array.prototype.lastIndexOf() - JavaScript
var numbers = [2, 5, 9, 2]; numbers.lastindexof(2); // 3 numbers.lastindexof(7); // -1 numbers.lastindexof(2, 3); // 3 numbers.lastindexof(2, 2); // 0 numbers.lastindexof(2, -2); // 0 numbers.lastindexof(2, -1); // 3 finding all the occurrences of an element the following example uses lastindexof to find all the indices of an element in a given array, using push to add them to another array as they are found.
... var indices = []; var array = ['a', 'b', 'a', 'c', 'a', 'd']; var element = 'a'; var idx = array.lastindexof(element); while (idx != -1) { indices.push(idx); idx = (idx > 0 ?
Proxy - JavaScript
proxy({ browsers: ['internet explorer', 'netscape'] }, { get: function(obj, prop) { // an extra property if (prop === 'latestbrowser') { return obj.browsers[obj.browsers.length - 1]; } // the default behavior to return the value return obj[prop]; }, set: function(obj, prop, value) { // an extra property if (prop === 'latestbrowser') { obj.browsers.push(value); return true; } // convert the value if it is not an array if (typeof value === 'string') { value = [value]; } // the default behavior to store the value obj[prop] = value; // indicate success return true; } }); console.log(products.browsers); // ['internet explorer', 'netscape'] products.browsers = 'firefox'; // pass a string (by mistak...
...lue; prop is usually an integer if (prop in obj) { return obj[prop]; } // get the number of products; an alias of products.length if (prop === 'number') { return obj.length; } let result, types = {}; for (let product of obj) { if (product.name === prop) { result = product; } if (types[product.type]) { types[product.type].push(product); } else { types[product.type] = [product]; } } // get a product by name if (result) { return result; } // get products by type if (prop in types) { return types[prop]; } // get product types if (prop === 'types') { return object.keys(types); } return undefined; } }); console.log(products[0]); ...
Spread syntax (...) - JavaScript
onstructor): ["hi", "how", "are", "you", "mr", null] // (log of "new myconstructorwitharguments"): {prop1: "val1", prop2: "val2"} spread in array literals a more powerful array literal without spread syntax, to create a new array using an existing array as one part of it, the array literal syntax is no longer sufficient and imperative code must be used instead using a combination of push(), splice(), concat(), etc.
... copy an array const arr = [1, 2, 3]; const arr2 = [...arr]; // like arr.slice() arr2.push(4); // arr2 becomes [1, 2, 3, 4] // arr remains unaffected note: spread syntax effectively goes one level deep while copying an array.
Progressive web app structure - Progressive web apps (PWAs)
in addition to the basic shell, you can add other features such as add to home screen or push notifications, safe in the knowledge that the app will still work ok if they are not supported by the user's browser — this is the beauty of progressive enhancement.
... '/pwa-examples/js13kpwa/icons/icon-64.png', '/pwa-examples/js13kpwa/icons/icon-96.png', '/pwa-examples/js13kpwa/icons/icon-128.png', '/pwa-examples/js13kpwa/icons/icon-168.png', '/pwa-examples/js13kpwa/icons/icon-192.png', '/pwa-examples/js13kpwa/icons/icon-256.png', '/pwa-examples/js13kpwa/icons/icon-512.png' ]; var gamesimages = []; for(var i=0; i<games.length; i++) { gamesimages.push('data/img/'+games[i].slug+'.jpg'); } var contenttocache = appshellfiles.concat(gamesimages); the next block installs the service worker, which then actually caches all the files contained in the above list: self.addeventlistener('install', function(e) { console.log('[service worker] install'); e.waituntil( caches.open(cachename).then(function(cache) { console.log('[service worker]...
Progressive loading - Progressive web apps (PWAs)
previous overview: progressive web apps in previous articles we covered apis that help us make our js13kpwa example a progressive web app: service workers, web manifests, notifications and push.
...we also explained push with help from the service worker cookbook.
Structural overview of progressive web apps - Progressive web apps (PWAs)
in addition to the basic shell, you can add other features such as add to home screen or push notifications, safe in the knowledge that the app will still work ok if they are not supported by the user's browser — this is the beauty of progressive enhancement.
... '/pwa-examples/js13kpwa/icons/icon-64.png', '/pwa-examples/js13kpwa/icons/icon-96.png', '/pwa-examples/js13kpwa/icons/icon-128.png', '/pwa-examples/js13kpwa/icons/icon-168.png', '/pwa-examples/js13kpwa/icons/icon-192.png', '/pwa-examples/js13kpwa/icons/icon-256.png', '/pwa-examples/js13kpwa/icons/icon-512.png' ]; var gamesimages = []; for(var i=0; i<games.length; i++) { gamesimages.push('data/img/'+games[i].slug+'.jpg'); } var contenttocache = appshellfiles.concat(gamesimages); with the file list prepared, it's time to install the service worker itself.
2015 MDN Fellowship Program - Archive of obsolete content
they enable the creation of effective offline experiences and wiill also allow access to push notifications and background sync apis.
Interacting with page scripts - Archive of obsolete content
note that the function's closure will be exported, too: // content-script.js var salutation = "hello, "; function greetme(user) { return salutation + user; } exportfunction(greetme, unsafewindow, {defineas: "greetme"}); finally, the "page.html" file adds a button and a page script that calls the exported function when the user pushes the button: <html> <head> </head> <body> <input id="test" type="button" value="click me"/> <script> var test = document.getelementbyid("test"); test.addeventlistener("click", function() { alert(window.greetme("page script")); }, false); </script> </body> </html> exportfunction() works by structured cloning the arguments and return value of the fun...
context-menu - Archive of obsolete content
' var pagehasimgs = !!document.queryselector("img");' + ' return pagehasimgs;' + '});' + 'self.on("click", function (node, data) {' + ' var imgs = document.queryselectorall("img");' + ' var imgsrcs = [];' + ' for (var i = 0 ; i < imgs.length; i++)' + ' imgsrcs.push(imgs[i].src);' + ' self.postmessage(imgsrcs);' + '});', onmessage: function (imgsrcs) { openimageeditor(imgsrcs); } }); show a "search with" menu when the user right-clicks an anchor that searches google or wikipedia with the text contained in the anchor: var cm = require("sdk/context-menu"); var googleitem = cm.item({ label: "google", data: "http:...
indexed-db - Archive of obsolete content
var trans = db.transaction(["items"], "readwrite"); var store = trans.objectstore("items"); var items = new array(); trans.oncomplete = function() { cb(items); } var keyrange = idbkeyrange.lowerbound(0); var cursorrequest = store.opencursor(keyrange); cursorrequest.onsuccess = function(e) { var result = e.target.result; if(!!result == false) return; items.push(result.value.name); result.continue(); }; cursorrequest.onerror = database.onerror; }; function listitems(itemlist) { console.log(itemlist); } open("1"); var add = require("sdk/ui/button/action").actionbutton({ id: "add", label: "add", icon: "./add.png", onclick: function() { additem(require("sdk/tabs").activetab.title); } }); var list = require("sdk/ui/button/action"...
private-browsing - Archive of obsolete content
f tabs the user loads, and uses isprivate() to exclude the titles of tabs that were loaded into private windows: var simplestorage = require("simple-storage"); if (!simplestorage.storage.titles) simplestorage.storage.titles = []; require("tabs").on("ready", function(tab) { if (!require("sdk/private-browsing").isprivate(tab)) { console.log("storing..."); simplestorage.storage.titles.push(tab.title); } else { console.log("not storing, private data"); } }); here's an add-on that uses a page-mod to log the content of pages loaded by the user, unless the page is private.
simple-storage - Archive of obsolete content
for example, this add-on tries to store the urls of pages the user visits: var ss = require("sdk/simple-storage"); ss.storage.pages = []; require("sdk/tabs").on("ready", function(tab) { ss.storage.pages.push(tab.url); }); require("sdk/ui/button/action").actionbutton({ id: "read", label: "read", icon: "./read.png", onclick: function() { console.log(ss.storage.pages); } }); but this isn't going to work, because it empties the array each time the add-on runs (for example, each time firefox is started).
tabs - Archive of obsolete content
tabs.on('open', function onopen(tab) { myopentabs.push(tab); }); // listen for tab content loads.
windows - Archive of obsolete content
var windows = require("sdk/windows").browserwindows; // add a listener to the 'open' event windows.on('open', function(window) { myopenwindows.push(window); }); // add a listener to the 'close' event windows.on('close', function(window) { console.log("a window was closed."); }); // add a listener to the 'activate' event windows.on('activate', function(window) { console.log("a window was activated."); }); // add a listener to the 'deactivate' event windows.on('deactivate', function(window) { console.log("a window was deactivated."); ...
places/bookmarks - Archive of obsolete content
all of the items passed in are pushed to the platform and are either created, updated or deleted.
ui/sidebar - Archive of obsolete content
here's an add-on that adds each worker to an array in the attach handler, and makes sure that its references are cleaned up by listening to detach and removing workers as they are detached: var workerarray = []; function attachworker(worker) { workerarray.push(worker); } function detachworker(worker) { var index = workerarray.indexof(worker); if(index != -1) { workerarray.splice(index, 1); } } var sidebar = require("sdk/ui/sidebar").sidebar({ id: 'my-sidebar', title: 'my sidebar', url: require("sdk/self").data.url("sidebar.html"), onattach: attachworker, ondetach: detachworker }); show this event is emitted when the sidebar is s...
Storing annotations - Archive of obsolete content
the annotation is composed of the text the user entered and the "annotation anchor", which consists of the url, element id and element content: function handlenewannotation(annotationtext, anchor) { var newannotation = new annotation(annotationtext, anchor); simplestorage.storage.annotations.push(newannotation); } this function calls a constructor for an annotation object, which we also need to supply: function annotation(annotationtext, anchor) { this.annotationtext = annotationtext; this.url = anchor[0]; this.ancestorid = anchor[1]; this.anchortext = anchor[2]; } now we need to link this code to the annotation editor, so that when the user presses the return key in the editor...
Drag & Drop - Archive of obsolete content
alue.queryinterface(components.interfaces.nsisupportsstring); } catch(ex) { } if (str) { uri = _ios.newuri(str.data.split("\n")[0], null, null); } else { var file = data.value.queryinterface(components.interfaces.nsifile); if (file) uri = _ios.newfileuri(file); } } if (uri) uris.push(uri); } // use the array of file uris } the _dragover function checks the drag data to see if a simple text file or general purpose file types are available.
Forms related code snippets - Archive of obsolete content
ion () { if (otable.parentnode) { otable.parentnode.removechild(otable); return; } otable.style.zindex = nzindex++; otable.style.position = "absolute"; otable.style.left = otarget.offsetleft + "px"; otable.style.top = (otarget.offsettop + otarget.offsetheight) + "px"; otarget.parentnode.insertbefore(otable, otarget); }; ainstances.push(this); } datepicker.prototype.writedays = function () { const nendblanks = (this.current.getday() + bzeroismonday * 6) % 7, nend = amonthlengths[this.current.getmonth()] + nendblanks, ntotal = nend + ((7 - nend % 7) % 7); var otd, otr; if (this.otbody) { this.container.removechild(this.otbody); } this.otbody = document.createelement("tbody"); ...
Tree - Archive of obsolete content
var celltext = tree.view.getcelltext(row.value, col.value); alert(celltext); } getting the selected indices of a multiselect tree var start = {}, end = {}, numranges = tree.view.selection.getrangecount(), selectedindices = []; for (var t = 0; t < numranges; t++){ tree.view.selection.getrangeat(t, start, end); for (var v = start.value; v <= end.value; v++) selectedindices.push(v); } other resources xul: tree documentation xul tutorial: tree selection ...
XPath - Archive of obsolete content
avascript which return responsexml object to parsexml function function parsexml(obj)//obj is the returnxml object now { if(!obj.documentelement) { alert("your browser does't support this script!"); return; } var fields = [];//store the results if(window.activexobject) { var tobj = obj.documentelement.selectnodes("/root/field/item"); for(var i=0;i<tobj.length; i++) { fields.push(tobj[i].text); } } else { var tobj = obj.evaluate("/root/field/item",obj.documentelement,null, xpathresult.any_type, null); var tmp = tobj.iteratenext(); while(tmp) { fields.push(tmp.textcontent); tmp = tobj.iteratenext(); } } alert(fields); } //here is the demo xml file for xpath <?xml version="1.0"?> <root> <field> <item>art_id</item> <item>psection</item> <i...
Chapter 4: Using XPCOM—Implementing advanced processes - Archive of obsolete content
listing 9: listing the contents of a specific directory file.initwithpath('c:\\'); var children = file.directoryentries; var child; var list = []; while (children.hasmoreelements()) { child = children.getnext().queryinterface(components.interfaces.nsilocalfile); list.push(child.leafname + (child.isdirectory() ?
Appendix F: Monitoring DOM changes - Archive of obsolete content
hashchange and popstate events most ajax-heavy sites update the url when they significantly change their content, either via a change to the fragment identifier (hash) or more recently via the history.pushstate method.
User Notifications and Alerts - Archive of obsolete content
below is preferrable because it only cuts the bottom part of the current page, as opposed to pushing down all tabs and content.
Promises - Archive of obsolete content
let iter = new os.file.directoryiterator(dir); yield iter.foreach(entry => { if (!entry.isdir) files.push(entry.path); }); iter.close(); } // read the files as binary blobs and process them.
An Interview With Douglas Bowman of Wired News - Archive of obsolete content
resizing the browser window often resulted in one column getting pushed to the bottom of another.
Drag and Drop JavaScript Wrapper - Archive of obsolete content
if you want to send more then one data object, (for example multiple files) you must use an transferdataset as follows: var textobserver = { ondragstart: function (event) { var txt1 = 'hello'; var txt2 = 'there'; transferdata.data = new transferdataset(); var tmp = new transferdata(); tmp.adddataforflavour("text/unicode",txt1); transferdata.data.push(tmp); new transferdata(); tmp.adddataforflavour("text/unicode",txt2); transferdata.data.push(tmp); } } you will need to add an observer to each element that can either start a drag action or can accept dropped objects.
Introducing the Audio API extension - Archive of obsolete content
a2.mozsetup(a1.mozchannels, a1.mozsamplerate); } function audioavailable(event) { // write the current framebuffer var framebuffer = event.framebuffer; writeaudio(framebuffer); } a1.addeventlistener('mozaudioavailable', audioavailable, false); a1.addeventlistener('loadedmetadata', loadedmetadata, false); function writeaudio(audio) { buffers.push(audio); // if there's buffered data, write that while(buffers.length > 0) { var buffer = buffers.shift(); var written = a2.mozwriteaudio(buffer); // // if all data wasn't written, keep it in the buffers: if(written < buffer.length) { buffers.unshift(buffer.slice(written)); return; } } } </script> ...
Basics - Archive of obsolete content
blah(lengthstringfocusedstringtostringstringpopstringpushstringreversestringshiftstringsortstringsplicestringunshiftstring)this is some default text lengththe number of open tabsstring focusedthe current tab in your browserstring tostringstuffstring popstuffstring pushstuffstring reversestuffstring shiftstuffstring sortstuffstring splicestuffstring unshiftstuffstring onready()when the inherited document is fully loaded.
Metro browser chrome tests - Archive of obsolete content
a simple test looks like this: gtests.push({ desc: "test loading about:blank", setup: function () { }, teardown: function () { }, run: function () { yield addtab("about:blank"); is(tab.browser.currenturi.spec, "about:blank", "about:blank is loaded"); } }); function test() { runtests(); } gtests contains individual tests that make up the library of tests your test file will contain.
Static Analysis for Windows Code under Linux - Archive of obsolete content
hg clone http://hg.mozilla.org/users/tglek_mo...-moz-plugin-mq .hg/patches # apply gty.diff and plugin.diff # if you have mq setup, do hg qpush -a (for file in `cat .hg/patches/series`; do cat .hg/patches/$file; done) |patch -p1 cd ..
Running Tamarin acceptance tests - Archive of obsolete content
the shell can be named variously in the build but on the phone the executable must be 'avmshell' $ adb shell 'mkdir /data/local/tamarin' $ adb push avmshell /data/local/tamarin/avmshell $ adb shell 'chmod 777 /data/local/tamarin/avmshell' copy android_runner.sh, if it doesn't already exist on the phone in /data/local/tamarin $ adb push tamarin-redux/platform/android/android_runner.sh /data/local/tamarin/android_runner.sh $ adb shell 'chmod 777 /data/loca/android_runner.sh' test it out with a simple .abc or no args for usage (should return e...
Running Tamarin performance tests - Archive of obsolete content
the shell can be named variously in the build but on the phone the executable must be 'avmshell' $ adb push avmshell /data/app/avmshell $ adb shell chmod 777 /data/app/avmshell copy android_runner.sh, if it doesn't already exist on the phone in /data/app $ adb push tamarin-redux/platform/android/android_runner.sh /data/app/android_runner.s $ adb shell chmod 777 /data/app/android_runner.sh test it out with a simple .abc or no args for usage (should return exitcode=0) $ tamarin-redux/platform/android/an...
Tamarin Build System Documentation - Archive of obsolete content
checkins (hg push) to http://hg.mozilla.org/tamarin-redux and sandbox requests will trigger a buildbot build when all build slaves are idle the next build begins before the build begins buildbot waits for 2 minutes of no checkin activity the build system prioritizes tamarin-redux checkins over sandbox builds when several tamarin-redux checkins occur the newest change is built including all checkins since the last ...
Working With Directories - Archive of obsolete content
the following example returns an array of all of a directory's subdirectories: function getsubdirs() { var arr = []; var items = io.getfile("home", "").directoryentries; while (items.hasmoreelements()) { var item = items.getnext(); if (item.isdirectory()) arr.push(item); } return arr; } ...
Reading from Files - Archive of obsolete content
var lines = []; while(stream.available()) lines.push(stream.readline()); in this example, each line from a stream is read and added to an array.
Index - Archive of obsolete content
ArchiveMozillaXULIndex
on windows and unix, pressing alt+a is a convenient way to push that button.
Box Model Details - Archive of obsolete content
centering buttons example 4 : source view <hbox pack="center" align="center" flex="1"> <button label="look at me!"/> <button label="push me!"/> </hbox> this example contains a horizontal box with two buttons in it, contained inside a flexible box.
Element Positioning - Archive of obsolete content
the following shows this attribute in use: example 6: source view <button label="push me please!" crop="right" flex="1"/> notice how the text on the button has had the right side of it cropped after the window is made smaller.
Skinning XUL Files by Hand - Archive of obsolete content
for example, when a button is defined as follows: <button class="plain" label="push me" /> then the following very simple style definition applies to that button.
Splitters - Archive of obsolete content
the resizeafter attribute has been set to grow so that the elements after the splitter push themselves down when the splitter is dragged down.
Tree View Details - Archive of obsolete content
the tree will use this information and add space for the appropriate number of rows and push the rows afterwards down.
Using Spacers - Archive of obsolete content
the buttons have been pushed over.
XUL Accesskey FAQ and Policies - Archive of obsolete content
on windows and unix, pressing alt+a is a convenient way to push that button.
tree - Archive of obsolete content
ArchiveMozillaXULtree
lor: #000000; } if using a content tree view, use the following to get the value of the id attribute for each of the selected rows of a tree: var idlist = []; var rangecount = tree.view.selection.getrangecount(); for (var i = 0; i < rangecount; i++) { var start = {}; var end = {}; tree.view.selection.getrangeat(i, start, end); for (var c = start.value; c <= end.value; c++) { idlist.push(tree.view.getitematindex(c).firstchild.id); } } the following returns a array of the indicies of the rows where the value is checked in a checkbox type column: function getcellchecked(tree, columnid) { var arr = []; var column = tree.columns.getnamedcolumn(columnid); for (var i = 0; i < tree.view.rowcount; i++) { if (tree.view.getcellvalue(i, column) == 'true') arr.push(i); ...
2006-10-06 - Archive of obsolete content
extension compatibility for firefox 2 chris hofmann reminds about the push to have extensions work with ff2.
NPAPI plugin developer guide - Archive of obsolete content
pop-up menus and dialog boxes event handling for windowless plug-ins streams receiving a stream telling the plug-in when a stream is created telling the plug-in when a stream is deleted finding out how much data the plug-in can accept writing the stream to the plug-in sending the stream in random-access mode sending the stream in file mode sending a stream creating a stream pushing data into the stream deleting the stream example of sending a stream urls getting urls getting the url and displaying the page posting urls posting data to an http server uploading files to an ftp server sending mail memory allocating and freeing memory mac os flushing memory (mac os only) version, ui, and status information displayin...
Browser-side plug-in API - Archive of obsolete content
npn_destroystream npn_forceredraw npn_getauthenticationinfo npn_geturl npn_geturlnotify npn_getvalue npn_getvalueforurl npn_invalidaterect npn_invalidateregion npn_memalloc npn_memflush npn_memfree npn_newstream npn_pluginthreadasynccall npn_poppopupsenabledstate npn_posturl npn_posturlnotify npn_pushpopupsenabledstate npn_reloadplugins npn_requestread npn_setvalue npn_setvalueforurl npn_status npn_useragent npn_version npn_write ...
NPAPI plugin reference - Archive of obsolete content
npn_write pushes data into a stream produced by the plug-in and consumed by the browser.
Writing a plugin for Mac OS X - Archive of obsolete content
if you want to implement your plugin in c++ or objective-c++, you need to tell the compiler to export them in c format by using extern "c" in the header, like this: #pragma gcc visibility push(default) extern "c" { nperror np_initialize(npnetscapefuncs *browserfuncs); nperror np_getentrypoints(nppluginfuncs *pluginfuncs); void np_shutdown(void); } #pragma gcc visibility pop you can check to be sure your symbols are visible and in standard c format by using the nm utility provided among the mac os x developer tools: [user@foo mymac] nm basicplugin ...
SAX - Archive of obsolete content
d content handler: function print(s) { dump(s + "\n"); } xmlreader.contenthandler = { // nsisaxcontenthandler startdocument: function() { print("startdocument"); }, enddocument: function() { print("enddocument"); }, startelement: function(uri, localname, qname, /*nsisaxattributes*/ attributes) { var attrs = []; for(var i=0; i<attributes.length; i++) { attrs.push(attributes.getqname(i) + "='" + attributes.getvalue(i) + "'"); } print("startelement: namespace='" + uri + "', localname='" + localname + "', qname='" + qname + "', attributes={" + attrs.join(",") + "}"); }, endelement: function(uri, localname, qname) { print("endelement: namespace='" + uri + "', localname='" + localname + "', qname...
Common Firefox theme issues and solutions - Archive of obsolete content
this guide will help you thoroughly test your theme to find and fix issues before you push updates to amo.
E4X for templating - Archive of obsolete content
ction (k, elem, iter) <> <row>{k}: {elem.text()} {elem.somechild}</row> <row><image src="chrome://myext/skin/images/fillerrow.jpg" /></row> </>)} sorting /* @param {xmllist} xmllist the xmllist to sort @param {function} h the sorting handler */ function sort (xmllist, h) { var k, arr=[], ret = <></>; for (k in xmllist) { if (xmllist.hasownproperty(k)) { arr.push(xmllist[k]); } } arr.sort(h).foreach(function (item) { if (typeof item === 'xml') { ret += item; } else if (typeof item === 'string') { ret += new xml(item); } else { var ser = (new xmlserializer()).serializetostring(item); ret += new xml(ser); } }); return ret; } example: var...
Object.prototype.__noSuchMethod__ - Archive of obsolete content
return parents[i][name].apply(this, args); } } // if we get here, the method hasn't been found throw new typeerror; } // used to add a parent for multiple inheritance function addparent(obj, parent) { // if the object isn't initialized, initialize it if (!obj.__parents_) { obj.__parents_ = []; obj.__nosuchmethod__ = nomethod; } // add the parent obj.__parents_.push(parent); } an example of using this idea is shown below.
MSX Emulator (jsMSX) - Archive of obsolete content
they present an interesting testbed for pushing the current javascript implementations to their limits and for comparing their relative speed.
Old Proxy API - Archive of obsolete content
urn name in obj; }, hasown: function(name) { return object.prototype.hasownproperty.call(obj, name); }, get: function(receiver, name) { return obj[name]; }, set: function(receiver, name, val) { obj[name] = val; return true; }, // bad behavior when set fails in non-strict mode enumerate: function() { var result = []; for (name in obj) { result.push(name); }; return result; }, keys: function() { return object.keys(obj) } }; } // ...
Back to the Server: Server-Side JavaScript On The Rise - Archive of obsolete content
this gives you added control to interrogate and manage the document structure before it's pushed to the client.
Audio for Web games - Game development
see also web audio api on mdn <audio> on mdn developing game audio with the web audio api (html5rocks) mixing positional audio and webgl (html5rocks) songs of diridum: pushing the web audio api to its limits making html5 audio actually work on mobile audio sprites (and fixes for ios) ...
Desktop mouse and keyboard controls - Game development
it's also easier to test control-independent features like gameplay on desktop if you develop it there, so you don't have to push the files to a mobile device every time you make a change in the source code.
Unconventional controls - Game development
connecting the boards and using them may look like this: var cylon = require('cylon'); cylon.robot({ connections: { arduino: { adaptor: 'firmata', port: '/dev/ttyacm0' } }, devices: { makey: { driver: 'makey-button', pin: 2 } }, work: function(my) { my.makey.on('push', function() { console.log("button pushed!"); }); } }).start(); as the description says: this gpio driver allows you to connect a 10 mohm resistor to a digital pin on your arduino or raspberry pi to control your robots with bananas, clay, or drawable circuitry.
Implementing controls using the Gamepad API - Game development
the buttons cache gamepadapi.buttonscache = []; // move the buttons status from the previous frame to the cache for(var k=0; k<gamepadapi.buttonsstatus.length; k++) { gamepadapi.buttonscache[k] = gamepadapi.buttonsstatus[k]; } // clear the buttons status gamepadapi.buttonsstatus = []; // get the gamepad object var c = gamepadapi.controller || {}; // loop through buttons and push the pressed ones to the array var pressed = []; if(c.buttons) { for(var b=0,t=c.buttons.length; b<t; b++) { if(c.buttons[b].pressed) { pressed.push(gamepadapi.buttons[b]); } } } // loop through axes and push their values to the array var axes = []; if(c.axes) { for(var a=0,x=c.axes.length; a<x; a++) { axes.push(c.axes[a].tofixed(2)); } } /...
asm.js - Game development
it pushes js engines to optimize this kind of code, and gives compilers like emscripten a clear definition of what kind of code to generate.
2D maze game with device orientation - Game development
; i<this.maxlevels; i++) { var newlevel = this.add.group(); newlevel.enablebody = true; newlevel.physicsbodytype = phaser.physics.arcade; for(var e=0; e<this.leveldata[i].length; e++) { var item = this.leveldata[i][e]; newlevel.create(item.x, item.y, 'element-'+item.t); } newlevel.setall('body.immovable', true); newlevel.visible = false; this.levels.push(newlevel); } first, add.group() is used to create a new group of items.
Google Chrome - MDN Web Docs Glossary: Definitions of Web-related terms
google pushes updates frequently and has designed the distributions to run side-by-side with the stable version.
HTTP/2 - MDN Web Docs Glossary: Definitions of Web-related terms
the primary goals for http/2 are to reduce latency by enabling full request and response multiplexing, minimize protocol overhead via efficient compression of http header fields, and add support for request prioritization and server push.
Index - MDN Web Docs Glossary: Definitions of Web-related terms
this involves taking standard web sites/apps that enjoy all the best parts of the web — such as discoverability via search engines, being linkable via urls, and working across multiple form factors — and supercharging them with modern apis (such as service workers and push) and features that confer other benefits more commonly attributed to native apps.
MVC - MDN Web Docs Glossary: Definitions of Web-related terms
however, these days, more of the logic is pushed to the client with the advent of client-side data stores, and xmlhttprequest allowing partial page updates as required.
Primitive - MDN Web Docs Glossary: Definitions of Web-related terms
javascript // using a string method doesn't mutate the string var bar = "baz"; console.log(bar); // baz bar.touppercase(); console.log(bar); // baz // using an array method mutates the array var foo = []; console.log(foo); // [] foo.push("plugh"); console.log(foo); // ["plugh"] // assignment gives the primitive a new (not a mutated) value bar = bar.touppercase(); // baz a primitive can be replaced, but it can't be directly altered.
Progressive web apps - MDN Web Docs Glossary: Definitions of Web-related terms
this involves taking standard web sites/apps that enjoy all the best parts of the web — such as discoverability via search engines, being linkable via urls, and working across multiple form factors — and supercharging them with modern apis (such as service workers and push) and features that confer other benefits more commonly attributed to native apps.
CSS and JavaScript accessibility best practices - Learn web development
simple content and functionality is arguably easy to make accessible — for example text, images, tables, forms and push button that activate functions.
Sizing items in CSS - Learn web development
for example, if you want a full-page hero section to show before the rest of your content, making that part of your page 100vh high will push the rest of the content below the viewport, meaning that it will only appear once the document is scrolled.
CSS values and units - Learn web development
play around with these values to see how you can push the image around.
Floats - Learn web development
while we can add a margin to the float to push the text away, we can't add a margin to the text to move it away from the float.
Using your new knowledge - Learn web development
use some padding to push the content away from the border.
create fancy boxes - Learn web development
it starts to get interesting when you push the properties to the limit by having negative padding and/or- margin by having border-radius larger than the actual size of the box.
How do you make sure your website works properly? - Learn web development
so correct the typo in your code editor by changing the image's src attribute: save, push to the server, and reload the page in your browser: there you go!
How do you upload your files to a web server? - Learn web development
objective: learn how to push files to a server using the various file transfer tools available.
What are browser developer tools? - Learn web development
in example.js, a breakpoint has been set on the statement listitems.push(inputnewitem.value); the final two sections only appear when the code is running.
Index - Learn web development
77 arrays arrays, article, beginner, codingscripting, javascript, join, learn, pop, push, l10n:priority, shift, split, unshift in the final article of this module, we'll look at arrays — a neat way of storing a list of data items under a single variable name.
Introducing asynchronous JavaScript - Learn web development
if we're running an operation that takes time however, like querying a database and using the results to populate templates, it is better to push this off the main thread and complete the task asynchronously.
Introduction to web APIs - Learn web development
for example, some of the more modern webapis will only work on pages served over https due to them transmitting potentially sensitive data (examples include service workers and push).
Object building practice - Learn web development
lls.length < 25) { let size = random(10,20); let ball = new ball( // ball position always drawn at least one ball width // away from the edge of the canvas, to avoid drawing errors random(0 + size,width - size), random(0 + size,height - size), random(-7,7), random(-7,7), 'rgb(' + random(0,255) + ',' + random(0,255) + ',' + random(0,255) +')', size ); balls.push(ball); } the while loop creates a new instance of our ball() using random values generated with our random() function, then push()es it onto the end of our balls array, but only while the number of balls in the array is less than 25.
Multimedia: Images - Learn web development
for example, when text gets pushed down the page by images loading.
Perceived performance - Learn web development
prevent jumping content and other reflows images or other assets causing content to be pushed down or jump to a different location, like the loading of third party advertisements, can make the page feel like it is still loading and is bad for perceived performance.
What is web performance? - Learn web development
there is overhead involved in establishing tcp and http connections, and some unavoidable latency in pushing the request and response bytes back and forth across the network, but there are certain ways to reduce latency (e.g.
Client-Server Overview - Learn web development
websites created using this style of application push a lot of computational cost from the server to the web browser, and can result in websites that appear to behave a lot more like native apps (highly responsive, etc.).
Getting started with Vue - Learn web development
select "in dedicated config files" and push enter.
Git and GitHub - Learn web development
you make changes to your own copy, and then push those changes back up to the server, where an administrator will decide whether to merge your changes with the master copy.
Understanding client-side web development tools - Learn web development
we push the code to github, deploy it using netlify, and even show you how to add a simple test into the process.
Gecko info for Windows accessibility vendors
sets state_haspopup for autocomplete textfields role_pushbutton xul: <button> html: <input type= "button"> or<button> dhtml: role="wairole:button" sets state_haspopup for buttons containing menus role_checkbutton xul: <checkbox> html: <input type="checkbox"> dhtml: role="wairole:checkbox" fires event_state_change when checkbox is togg...
Creating JavaScript callbacks in components
in fact, there is even a specific interface for this form of push callbacks, nsiobserverservice.
Creating a Login Manager storage module
getservice(ci.nsiconsoleservice); return this.__logservice; }, log: function (message) { dump("sampleloginmanager: " + message + "\n"); this._logservice.logstringmessage("sampleloginmanager: " + message); }, // logs function name and arguments for debugging stub: function(arguments) { var args = []; for (let i = 0; i < arguments.length; i++) args.push(arguments[i]) this.log("called " + arguments.callee.name + "(" + args.join(",") + ")"); }, init: function slms_init() { this.stub(arguments); }, initwithfile: function slms_initwithfile(ainputfile, aoutputfile) { this.stub(arguments); }, addlogin: function slms_addlogin(login) { this.stub(arguments); }, removelogin: function slms_removelogin(login) { this.stub...
Debugging JavaScript
in extensions you can print the callstack using components.stack like this: function getstackdump() { var lines = []; for (var frame = components.stack; frame; frame = frame.caller) { lines.push(frame.filename + " (" + frame.linenumber + ")"); } return lines.join("\n"); } see also debugging mozilla with gdb setting up an extension development environment (particularly development preferences and development extensions) original document information author(s): ben bucksch created date: september 12, 2005, last updated date: november 10, 2009 copyright information: portio...
Eclipse CDT
this is because eclipse is trying to push every subfolder in gdb's environment.
Contributing to the Mozilla code base
now that you've got your first bug fixed you should request level 1 access to the repository to push to the try server and get automated feedback about your changes on multiple platforms.
Developer guide
task-graph generation what controls the jobs that run on a push to version control?
Communicating with frame scripts
// on some event var browsermm = gbrowser.selectedbrowser.messagemanager; browsermm.loadframescript("chrome://my-addon@me.org/content/frame-script.js", false); messagemanagers.push(browsermm); console.log(messagemanagers.length); we can listen for message-manager-disconnect to update the array when the message managers disconnect (for example because the user closed the tab): function myobserver() { } myobserver.prototype = { observe: function(subject, topic, data) { var index = messagemanagers.indexof(subject); if (index != -1) { console.log("one of our ...
HTML parser threading
that method is responsible for moving back to consuming tree ops from the parser thread via the staging area.) document.write() calls to document.write() push data to the tokenizer/tree builder pair that exists on the main thread solely for parsing data from document.write().
How to implement a custom autocomplete search component
decode(searchparam); // these 2 lines above are for thunderbird < v7 // since thunderbird 3, they can be replaced more efficiently by the following line: // var searchresults = json.parse(searchparam); var results = []; var comments = []; for (i=0; i<searchresults.length; i++) { if (searchresults[i].value.indexof(searchstring) == 0) { results.push(searchresults[i].value); if (searchresults[i].comment) comments.push(searchresults[i].comment); else comments.push(null); } } var newresult = new simpleautocompleteresult(searchstring, ci.nsiautocompleteresult.result_success, 0, "", results, comments); listener.onsearchresult(this, newresult); } }, /* * stop an asyn...
Sqlite.jsm
let accounts = []; let accountid, username; let statement = "select account_id, username from accounts order by username asc"; try { const result = await conn.executecached(statement, null, function(row, cancel) { accountid = row.getresultbyname("account_id"); username = row.getresultbyname("username"); accounts.push({ accountid: accountid, username: username }); // if the cancel function is called here, the statement being executed will // be cancelled, and no more rows will be processed.
Webapps.jsm
on close(aapp) canceldownload: function canceldownload(amanifesturl, aerror) startofflinecachedownload: function(amanifest, aapp, aprofiledir, aisupdate) computemanifesthash: function(amanifest) updateapphandlers: function(aoldmanifest, anewmanifest, aapp) checkforupdate: function(adata, amm) doinstall: function doinstall(adata, amm) doinstallpackage: function doinstallpackage(adata, amm) pushcontentaction: function(windowid) popcontentaction: function(windowid) actioncancelled: function(windowid) denyinstall: function(adata) _setupapp: function(adata, aid) _cloneapp: function(adata, anewapp, alocalemanifest, amanifest, aid, alocalid) _writemanifestfile: function(aid, aispackage, ajsonmanifest) _nextlocalid: function() _appidformanifesturl: function(auri) makeappid: function()...
Localizing XLIFF files for iOS
push your commit into the github repo: git push kick up your feet, pop open a cold beer (or soda), and pat yourself on the back for doing something new, different, and exciting!
Localizing with Koala
the last step of this tutorial will be to send (or "push") the changes you just made to a remote repository.
Localization formats
but, in the download day example, when changes were made to en-us, the web-developer had to push those changes to all the repositories of all the locales.
mozilla::MutexAutoLock
important: when a mozilla::mutexautolock is the mutex raii wrapper most recently pushed on the stack, your code is guaranteed to own the underlying mozilla::mutex.
mozilla::MutexAutoUnlock
important: when a mozilla::mutexautounlock is the mutex raii wrapper most recently pushed on the stack, your code is guaranteed not to own the underlying mozilla::mutex.
browser.altClickSave
type:boolean default value: false exists by default: yes application support:firefox 13.0 status: active; last updated 2012-03-19 introduction: pushed to nightly on 2012-03-02 bugs: bug 713052 values true clicking a link while holding the alt key starts the download of that link.
browser.dom.window.dump.file
type:string default value:none exists by default: no application support: gecko 1.9.2 (firefox 3.6 / thunderbird 3.1 / fennec 1.0) status: active; last updated 2012-03-18 introduction: pushed to nightly on 2009-04-24 bugs: bug 489938 values the value holds the file system path for the file in which the content of the window.dump() calls get written, e.g.
browser.download.lastDir.savePerSite
type:boolean default value:true exists by default: no application support:firefox 11.0 status: active; last updated 2012-02-15 introduction: pushed to nightly on 2011-12-11 bugs: bug 702748 values true (default) the last used directory for the website (host) serving the file for download will be preselected in the file picker.
browser.pagethumbnails.capturing_disabled
type:boolean default value:true exists by default: no application support: firefox 14.0 status: active; last updated 2012-09-17 introduction: pushed to nightly on 2012-04-13 bugs: bug 726347 values false the application creates screenshots of visited web pages.
browser.search.context.loadInBackground
type:boolean default value:false exists by default: yes application support: firefox 13.0 status: active; last updated 2012-02-17 introduction: pushed to nightly on 2012-02-15 bugs: bug 727131 values true new tab with search results will be opened in the background, focus stays on the current tab.
browser.urlbar.formatting.enabled
type:boolean default value: true exists by default: yes application support:firefox 6.0 status: active; last updated 2012-04-03 introduction: pushed to nightly on 2011-05-03 bugs: bug 451833 values true (default) the domain name including the top level domain is highlighted in the address bar by coloring it black and the other parts grey.
browser.urlbar.trimURLs
type:boolean default value: true exists by default: yes application support:firefox 7.0 status: active; last updated 2012-04-03 introduction: pushed to nightly on 2011-06-23 bugs: bug 665580 values true (default) if the active url is exactly the domain name, the trailing slash (/) behind the top level domain will be hidden.
dom.event.clipboardevents.enabled
type:boolean default value:true exists by default: no application support: gecko 13.0 (firefox 13.0 / thunderbird 13.0 / seamonkey 2.10) status: active; last updated 2012-02-15 introduction: pushed to nightly on 2012-02-14 bugs: bug 542938 values true (default) the oncopy, oncut and onpaste events are enabled for web content.
mail.tabs.drawInTitlebar
type:boolean default value: true exists by default: yes application support:thunderbird 17.0 status: active; last updated 2012-09-17 introduction: pushed to daily on 2012-08-08 bugs: bug 771816 values true (default) the tabs are drawn in the title bar of the mail program.
reader.parse-on-load.force-enabled
type:boolean default value: false exists by default: yes application support:firefox mobile 23.0 status: active; last updated 2013-05-11 introduction: pushed to nightly on 2013-05-06 bugs: bug 867875 values true reader mode is enabled independent of memory available.
ui.SpellCheckerUnderline
type:string default value:#ff0000 exists by default: no application support: gecko 1.9.2 (firefox 3.6 / thunderbird 3.1 / fennec 1.0) status: active; last updated 2012-02-21 introduction: pushed to nightly on 2009-04-03 bugs: bug 338209 values a color code like #ff0000 for red.
ui.SpellCheckerUnderlineStyle
type:integer default value:5 exists by default: no application support: gecko 1.9.2 (firefox 3.6 / thunderbird 3.1 / fennec 1.0) status: active; last updated 2012-02-22 introduction: pushed to nightly on 2009-04-03 bugs: bug 338209 values the values are defined in nsstyleconsts.h.
ui.alertNotificationOrigin
type:integer default value:dependent on position of taskbar or equivalent exists by default: no application support: gecko 1.8.1.2 (firefox 2.0.0.2 / thunderbird 2.0.0.4 / seamonkey 1.1) status: active; last updated 2012-02-22 introduction: pushed to nightly on 2007-01-04 bugs: bug 133527 values 0 bottom right corner, vertical slide-in from the bottom 1 bottom right corner, horizontal slide-in from the right 2 bottom left corner, vertical slide-in from the bottom 3 bottom left corner, horizontal slide-in from the left 4 top right corner, vertical slide-in from the top 5 top right corner, horizontal slide-in from the right 6...
ui.textSelectBackground
type:string with rgb hex value as color code default value:#ef0fff (blue) [1] exists by default: no application support: before gecko 1.7 status: active; last updated 2015-09-21 introduction: pushed to trunk on 2000-04-13 bugs: bug 34704 [1]: nsxplookandfeel.cpp, line 628, retrieved 2015-09-21 ...
ui.textSelectForeground
type:string with rgb hex value as color code default value:#ffffff (white) [1] exists by default: no application support: before gecko 1.7 status: active; last updated 2015-09-21 introduction: pushed to trunk on 2000-04-13 bugs: bug 34704 [1]: nsxplookandfeel.cpp, line 635, retrieved 2015-09-21 ...
ui.tooltipDelay
type:integer default value:500 exists by default: no application support: gecko 11.0 (firefox 11.0 / thunderbird 11.0 / seamonkey 2.8) status: active; last updated 2012-02-21 introduction: pushed to nightly on 2011-12-15 bugs: bug 204786 values integer (milliseconds, default: 500) the time for delay between the mouse stopping over the element and the tooltip appearing is stored in milliseconds and the default value is 500ms.
NSPR release procedure
note: for nss, the script equivalent to nspr's repackage.sh is /u/robobld/bin/sbsinit/nss/push/buildbindist.sh in the "svbuild" source tree.
Atomic Operations
these functions operate on 32-bit integers: pr_atomicincrement pr_atomicdecrement pr_atomicset pr_atomicadd these functions implement a simple stack data structure: pr_createstack pr_stackpush pr_stackpop pr_destroystack ...
NSPR LOG MODULES
set nspr_log_modules=timestamp,mozstorage:5 set nspr_log_file=/tmp/foo.log logging with try server for mochitest, edit variable nspr_log_modules in testing/mochitest/runtests.py before pushing to try.
PR_CreateIOLayerStub
the caller should override appropriate contents of the file descriptor returned before pushing it onto the protocol stack.
NSPR release process
push the beta tag to mozilla-central for testing in firefox trunk builds.
PKCS11 FAQ
MozillaProjectsNSSPKCS11FAQ
will nss get the user's ca certificate via pkcs #11 and push it into the ca certificate database or is the ca certificate database expected to obtain the ca certificate by some other means?
NSPR functions
pr_getuniqueidentity pr_createiolayerstub pr_getdefaultiomethods pr_getidentitieslayer pr_getlayersidentity pr_pushiolayer pr_popiolayer wrapping a native file descriptor if your current tcp socket code uses the standard bsd socket api, a lighter-weight method than creating your own nspr i/o layer is to simply import a native file descriptor into nspr.
Garbage collection
the barrier marks the pointed-to object black, and pushes any outgoing edges onto the mark stack.
SpiderMonkey Internals
a js-to-js function call pushes a javascript stack frame without growing the c stack.
JSAPI User Guide
spidermonkey provides a few core javascript data types—numbers, strings, arrays, objects, and so on—and a few methods, such as array.push.
JS_ConvertArguments
to perform the opposite conversion, converting values of various c types to an array of jsvals, use js_pusharguments.
JS_ForgetLocalRoot
in case a native hook allocates many objects or other gc-things, but the native protects some of those gc-things by storing them as property values in an object that is itself protected, the hook can call js_forgetlocalroot to free the local root automatically pushed for the now-protected gc-thing.
JSAPI reference
js_convertarguments obsolete since jsapi 38 js_convertargumentsva obsolete since jsapi 38 js_pusharguments obsolete since javascript 1.8.5 js_pushargumentsva obsolete since javascript 1.8.5 js_poparguments obsolete since javascript 1.8.5 js_addargumentformatter obsolete since jsapi 18 js_removeargumentformatter obsolete since jsapi 18 the following functions convert js values to various types.
SpiderMonkey 1.8.5
tioncallback js_clearregexproots js_decompilescript js_destroyscript js_enterlocalrootscope js_executescriptpart js_forgetlocalroot js_getfunctionname js_getoperationlimit js_getscriptobject js_getstringbytes js_getstringchars js_isassigning js_leavelocalrootscope js_leavelocalrootscopewithresult js_newdouble js_newdoublevalue js_newscriptobject js_newstring js_poparguments js_pusharguments js_pushargumentsva js_removeroot js_removerootrt js_sealobject js_setbranchcallback js_setcallreturnvalue2 js_setcheckobjectaccesscallback js_setobjectprincipalsfinder js_setoperationlimit js_setprincipalstranscoder api changes operation callback js_setoperationcallback was introduced in js 1.8.0, replacing the branch callback, in anticipation of the addition of the tracing ji...
Using RAII classes in Mozilla
raii classes are useful when two operations (e.g., lock/unlock, addref/release, pushstate/popstate) must be paired.
Places utilities for JavaScript
ri, the traditional code to get all its annotations would be: var annotationservice = components.classes["@mozilla.org/browser/annotation-service;1"] .getservice(components.interfaces.nsiannotationservice); try { var names = annotationservice.getpageannotationnames(uri); } catch(e) { // no annotations } var annotations = new array(); for(var i in names) { try { annotations.push(annotationservice.getpageannotation(uri, names[i])); } catch(e) { // this shouldn't happen } } the code using placesutils collapses a bit to: var annotations = placesutils.getannotationsforuri(uri); saving you a bit of clumsy code and leaving mozilla to make sure everything is written correctly.
Avoiding leaks in JavaScript XPCOM components
return nodefilter.filter_accept; case "template": case "radiogroup": return nodefilter.filter_reject; default: return nodefilter.filter_skip; } } var iterator = this.ownerdocument.createtreewalker(this, nodefilter.show_element, _filterradiogroup, true); while (iterator.nextnode()) radiochildren.push(iterator.currentnode); return this.mradiochildren = radiochildren; in this example, the iterator object is an xpcom object that is wrapped so the javascript code can use it.
Components.utils.getWeakReference
var arr = []; arr.push(cu.getweakreference(window)); //now lets say this code runs in another block: for (var i=0; i<arr.length; i++) { if (arr[i].get() == window) { //found the window break; } } ...
mozIStorageAggregateFunction
var standarddeviationfunc = { _numbers: [], onstep: function(aarguments) { this._numbers.push(aarguments.getint32(0)); }, onfinal: function() { let total = 0; let ilength = this._numbers.length; this._numbers.foreach(function(elt) { total += elt }); let mean = total / this._numbers.length; let data = this._numbers.map(function(elt) { let value = elt - mean; return value * value; }); total = 0; data.foreach(function(elt) { total += elt }); ...
nsIFilePicker
var files = fp.files; var paths = []; while (files.hasmoreelements()) { var arg = files.getnext().queryinterface(components.interfaces.nsilocalfile).path; paths.push(arg); } ...
nsIINIParser
// get all sections in the ini file var sectenum = iniparser.getsections(); // save the sections in an array var sections = []; while (sectenum && sectenum.hasmore()) { var section = sectenum.getnext(); // add an array entry for each section sections.push(section); } enumerating keys this example shows how to fetch the values for all the keys in the section named "setting".
nsIStreamConverter
convertdata(in string afromtype, in string atotype, in nsistreamlistener alistener, in nsisupports actxt); nsiinputstream convert(in nsiinputstream afromstream, in string afromtype, in string atotype, in nsisupports actxt); methods asyncconvertdata() asynchronous version: converts data arriving via the converter's nsistreamlistener.ondataavailable() method from one type to another, pushing the converted data out to the caller via alistener::ondataavailable().
nsITraceableChannel
var data = istream.readbytes(acount); this.receivedchunks.push(data); ostream.writebytes(data, acount); this.originallistener.ondataavailable(arequest, acontext, sstream.newinputstream(0), aoffset, acount); }, onstartrequest: function(arequest, acontext) { this.originallistener.onstartrequest(arequest, acontext); }, onstoprequest: function(arequest, acontext, astatuscode) { this.responsebody = this.receivedchunks.join(""); delete this.receive...
nsITransaction
if true, the transaction manager will release() the new transaction instead of pushing it on the undo stack.
nsIWebProgressListener
for example, the location change is due to an anchor scroll or a pushstate/popstate/replacestate.
nsIXPConnect
this method doesn't push ajscontext on the context stack, so the caller is required to push it if the top of the context stack is not equal to ajscontext.
nsIZipWriter
//entry is instance of nsifile so here https://developer.mozilla.org/docs/xpcom_interface_reference/nsifile if (entry.path == xpi.path) { cu.reporterror('skipping entry - will not add this entry to the zip file - as this is the zip itself: "' + xpi.path + '" leafname:"' + xpi.leafname + '"'); continue; } if (entry.isdirectory()) { dirarr.push(entry); } var relpath = entry.path.replace(dirarr[0].path, ''); //need relative because we need to use this for telling addentryfile where in the zip it should create it, and because zip is a copy of the directory cu.reporterror('+' + relpath); //makes it relative to directory the parent dir (dir[0]) so it can succesfully populate files with same names but differe...
XPCOM Interface Reference
ensiprincipalnsiprinterenumeratornsiprintingpromptnsiprivatebrowsingservicensiprocessnsiprocess2nsiprocessscriptloadernsiprofilensiprofilelocknsiprofileunlockernsiprogramminglanguagensiprogresseventsinknsipromptnsipromptservicensipropertiesnsipropertynsipropertybagnsipropertybag2nsipropertyelementnsiprotocolhandlernsiprotocolproxycallbacknsiprotocolproxyfilternsiprotocolproxyservicensiproxyinfonsipushmessagensipushservicensipushsubscriptionnsiradiointerfacelayernsirandomgeneratornsirequestnsirequestobservernsiresumablechannelnsirunnablensishentrynsishistorynsishistorylistenernsisockssocketinfonsisslerrorlistenernsisslsocketcontrolnsiscreennsiscreenmanagernsiscripterrornsiscripterror2nsiscriptableionsiscriptableinputstreamnsiscriptableunescapehtmlnsiscriptableunicodeconverternsiscrollablensisea...
Storage
you can use them quite simply in your select queries, like this: var stmt = aconn.createstatement("select * from foo order by name collate locale asc"); var results = []; while (stmt.executestep()) { results.push(stmt.row.t); } stmt.finalize(); how to corrupt a database sqlite is very good about maintaining database integrity, but there are a few things you can do that can lead to database corruption.
The Thread Manager
nsithreadeventfilter this interface is used by the nsithreadinternal.pusheventqueue() method in nsithreadinternal to allow event filtering.
Working with Multiple Versions of Interfaces
edocument nsiaccessibledocument_old #include "accessibility/nsiaccessibledocument_old.h" static const nsiid ns_iaccessibledocument_iid_old = ns_iaccessibledocument_iid; #undef nsiaccessibledocument #undef __gen_nsiaccessibledocument_h__ #include "accessibility/nsiaccessibledocument.h" i even silenced my friend the compiler by enclosing both incantations within a compiler pragma: #pragma warning(push) #pragma warning(disable : 4005) ...
Mailnews and Mail code review requirements
the procedure to use these is to be sure to: include "rs=simple-orange-fix" or "rs=orange-debugging" in the first line of the commit message paste a link to the pushed commit with the rubber stamp in the bug make sure you pasted a link to any try-server pushes of the patch in the bug rs=simple-orange-fix requirements: the patch is fixing an intermittent orange test failure.
WebIDL bindings
one example of this is pushmanager.
Working with ArrayBuffers
x + 2] = b; myimgdat.data[nindex + 3] = a; } /***** or do the below which uses the .set method *****/ /** method b **/ var normalarr = []; for (var nindex = 0; nindex < cast.length; nindex = nindex + 4) { // casted.length is same as myimgdat.data.length var r = casted[nindex]; var g = casted[nindex + 1]; var b = casted[nindex + 2]; var a = casted[nindex + 3]; normalarr.push(r); normalarr.push(g); normalarr.push(b); normalarr.push(a); } myimgdat.data.set(normalarr); the preceding example, however, does not take advantage of method 1, but instead manually goes through the array and sets the imagedata array.
CData
then null term will not get hit by this loop as null term is at pos 77 and we go till `< known_len` var thisunsignedcharcode = ptrasarr.addressofelement(i).contents; if (thisunsignedcharcode == 0) { // reached null terminator, break console.log('reached null terminator, at pos: ', i); break; } charcode.push(thisunsignedcharcode); fromcharcode.push(string.fromcharcode(thisunsignedcharcode)); } console.info('charcode:', charcode); console.info('fromcharcode:', fromcharcode); var char16_val = fromcharcode.join(''); console.info('char16_val:', char16_val); return char16_val; } if (!jschar) { try { var char8_val = st...
Constants - Plugins
npvers_has_popups_enabled_state 16 the npn_pushpopupsenabledstate() and npn_poppopupsenabledstate() functions are supported.
Debugger-API - Firefox Developer Tools
you can set functions to be called when new stack frames are pushed; when new code is loaded; and so on.
AudioTrack.label - Web APIs
WebAPIAudioTracklabel
function gettracklist(el) { var tracklist = []; const wantedkinds = [ "main", "alternative", "main-desc", "translation", "commentary" ]; el.audiotracks.foreach(function(track) { if (wantedkinds.includes(track.kind)) { tracklist.push({ id: track.id, kind: track.kind, label: track.label }); } }); return tracklist; } the resulting tracklist contains an array of audio tracks whose kind is one of those in the array wantedkinds, with each entry providing the track's id, kind, and label.
AudioTrack.language - Web APIs
function getavailablelanguages(el) { var tracklist = []; const wantedkinds = [ "main", "translation" ]; el.audiotracks.foreach(function(track) { if (wantedkinds.includes(track.kind)) { tracklist.push({ id: track.id, kind: track.kind, language: track.language }); } }); return tracklist; } specifications specification status comment html living standardthe definition of 'audiotrack.language' in that specification.
AudioTrack - Web APIs
function gettracklist(el) { var tracklist = []; const wantedkinds = [ "main", "alternative", "main-desc", "translation", "commentary" ]; el.audiotracks.foreach(function(track) { if (wantedkinds.includes(track.kind)) { tracklist.push({ id: track.id, kind: track.kind, label: track.label }); } }); return tracklist; } the resulting tracklist contains an array of audio tracks whose kind is one of those in the array wantedkinds, with each entry providing the track's id, kind, and label.
BudgetService.getCost() - Web APIs
}); parameters operation must be "silent-push".
CSSRule - Web APIs
WebAPICSSRule
(document_rule has been pushed to css conditional rules level 4) document object model (dom) level 2 style specificationthe definition of 'cssrule' in that specification.
CSSStyleSheet.insertRule() - Web APIs
examples inserting a new rule this snippet pushes a new rule onto the top of my stylesheet.
CanvasRenderingContext2D.save() - Web APIs
the canvasrenderingcontext2d.save() method of the canvas 2d api saves the entire state of the canvas by pushing the current state onto a stack.
Optimizing canvas - Web APIs
however, when websites and apps push the canvas api to its limits, performance begins to suffer.
Transformations - Web APIs
every time the save() method is called, the current drawing state is pushed onto the stack.
DataTransfer.mozItemCount - Web APIs
function drop_handler(event) { var files = []; var dt = event.datatransfer; for (var i = 0; i < dt.mozitemcount; i++) files.push(dt.mozgetdataat("application/x-moz-file", i)); } specifications this property is not defined in any web standard.
DirectoryReaderSync - Web APIs
var paths = []; function getallentries(dirreader) { var entries = dirreader.readentries(); for (var i = 0, entry; entry = entries[i]; ++i) { // stash this entry's filesystem in url paths.push(entry.tourl()); // if this is a directory, traverse.
Document.createNodeIterator() - Web APIs
nodefilter.filter_accept : nodefilter.filter_reject; } } ); const pars = []; let currentnode; while (currentnode = nodeiterator.nextnode()) { pars.push(currentnode); } specifications specification status comment domthe definition of 'document.createnodeiterator' in that specification.
Element.part - Web APIs
WebAPIElementpart
let tabs = []; let children = this.shadowroot.children; for(let elem of children) { if(elem.getattribute('part')) { tabs.push(elem); } } tabs.foreach((tab) => { tab.addeventlistener('click', (e) => { tabs.foreach((tab) => { tab.part = 'tab'; }) e.target.part = 'tab active'; }) console.log(tab.part); }) specifications specification status comment shadow partsthe definition of 'element.part' in that specification.
Event.msConvertURL() - Web APIs
evt.converturl(file, "specified", url); } else { evt.msconverturl(file, "specified", url); } console.log("local file: " + file.name + " (" + file.size + ")"); bloblist.push(file); } // for } // handlepaste see also microsoft api extensions ...
EventTarget.addEventListener() - Web APIs
eof listener.handleevent != 'undefined') { listener.handleevent(e); } else { listener.call(self,e); } }; if (type=="domcontentloaded") { var wrapper2=function(e) { if (document.readystate=="complete") { wrapper(e); } }; document.attachevent("onreadystatechange",wrapper2); eventlisteners.push({object:this,type:type,listener:listener,wrapper:wrapper2}); if (document.readystate=="complete") { var e=new event(); e.srcelement=window; wrapper2(e); } } else { this.attachevent("on"+type,wrapper); eventlisteners.push({object:this,type:type,listener:listener,wrapper:wrapper}); } }; var removeeventlistener=functi...
EventTarget - Web APIs
ler(domstring type, eventhandler handler) eventhandler geteventhandler(domstring type) example simple implementation of eventtarget var eventtarget = function() { this.listeners = {}; }; eventtarget.prototype.listeners = null; eventtarget.prototype.addeventlistener = function(type, callback) { if (!(type in this.listeners)) { this.listeners[type] = []; } this.listeners[type].push(callback); }; eventtarget.prototype.removeeventlistener = function(type, callback) { if (!(type in this.listeners)) { return; } var stack = this.listeners[type]; for (var i = 0, l = stack.length; i < l; i++) { if (stack[i] === callback){ stack.splice(i, 1); return; } } }; eventtarget.prototype.dispatchevent = function(event) { if (!(event.type in this.listene...
ExtendableEvent.waitUntil() - Web APIs
the activate events in service workers use waituntil() to buffer functional events such as fetch and push until the promise passed to waituntil() settles.
FileHandle API - Web APIs
such a file object is completely desynchronized from the original file, which means any change made to that object will never be reflected to the handled file as well as any change made to the handled file will never be pushed to the file object.
HTMLCanvasElement.transferControlToOffscreen() - Web APIs
// push frames back to the original htmlcanvaselement gl.commit(); specifications specification status comment html living standardthe definition of 'htmlcanvaselement.transfercontroltooffscreen()' in that specification.
HTMLMediaElement.seekable - Web APIs
examples var video = document.queryselector("video"); var timerangesobject = video.seekable; var timeranges = []; //go through the object and output an array for (let count = 0; count < timerangesobject.length; count ++) { timeranges.push([timerangesobject.start(count), timerangesobject.end(count)]); } specifications specification status comment html living standardthe definition of 'htmlmediaelement' in that specification.
Dragging and Dropping Multiple Items - Web APIs
function ondrop(event) { var files = []; var dt = event.datatransfer; for (var i = 0; i < dt.mozitemcount; i++) files.push(dt.mozgetdataat("application/x-moz-file", i)); } you may also wish to check if the desired format exists using the moztypesat method.
History.replaceState() - Web APIs
examples suppose https://www.mozilla.org/foo.html executes the following javascript: const stateobj = { foo: 'bar' }; history.pushstate(stateobj, '', 'bar.html'); the explanation of these two lines above can be found in the example of pushstate() method section of the working with the history api article.
History - Web APIs
WebAPIHistory
pushstate() pushes the given data onto the session history stack with the specified title (and, if provided, url).
History API - Web APIs
window.onpopstate = function(event) { alert(`location: ${document.location}, state: ${json.stringify(event.state)}`) } history.pushstate({page: 1}, "title 1", "?page=1") history.pushstate({page: 2}, "title 2", "?page=2") history.replacestate({page: 3}, "title 3", "?page=3") history.back() // alerts "location: http://example.com/example.html?page=1, state: {"page":1}" history.back() // alerts "location: http://example.com/example.html, state: null" history.go(2) // alerts "location: http://example.com/example.html?page=3, sta...
IDBCursor.continuePrimaryKey() - Web APIs
{ let cursor = event.target.result; if (!cursor) { return; } let lastprimarykey = getlastiteratedarticleid(); if (lastprimarykey > cursor.primarykey) { cursor.continueprimarykey("javascript", lastprimarykey); return; } // update lastiteratedarticleid setlastiteratedarticleid(cursor.primarykey); // preload 5 articles into the unread list; unreadlist.push(cursor.value); if (++count < 5) { cursor.continue(); } }; specifications specification status comment indexed database api draftthe definition of 'continueprimarykey()' in that specification.
Using IndexedDB - Web APIs
one common pattern with cursors is to retrieve all objects in an object store and add them to an array, like this: var customers = []; objectstore.opencursor().onsuccess = function(event) { var cursor = event.target.result; if (cursor) { customers.push(cursor.value); cursor.continue(); } else { console.log("got all customers: " + customers); } }; note: alternatively, you can use getall() to handle this case (and getallkeys()) .
IntersectionObserverEntry.intersectionRect - Web APIs
function intersectioncallback(entries) { entries.foreach(function(entry) { refreshzones.push({ element: entry.target, rect: entry.intersectionrect }); }); } specifications specification status comment intersection observerthe definition of 'intersectionobserverentry.intersectionrect' in that specification.
MediaRecorder.ondataavailable - Web APIs
console.log("data available after mediarecorder.stop() called."); var audio = document.createelement('audio'); audio.controls = true; var blob = new blob(chunks, { 'type' : 'audio/ogg; codecs=opus' }); var audiourl = window.url.createobjecturl(blob); audio.src = audiourl; console.log("recorder stopped"); } mediarecorder.ondataavailable = function(e) { chunks.push(e.data); } ...
MediaRecorder.onerror - Web APIs
function recordstream(stream) { let recorder = null; let bufferlist = []; try { recorder = new mediarecorder(stream); } catch(err) { return err.name; /* return the error name */ } recorder.ondataavailable = function(event) { bufferlist.push(event.data); }; recorder.onerror = function(event) { let error = event.error; switch(error.name) { case invalidstateerror: shownotification("you can't record the video right " + "now.
MediaRecorder.onstop - Web APIs
console.log("data available after mediarecorder.stop() called."); var audio = document.createelement('audio'); audio.controls = true; var blob = new blob(chunks, { 'type' : 'audio/ogg; codecs=opus' }); var audiourl = window.url.createobjecturl(blob); audio.src = audiourl; console.log("recorder stopped"); } mediarecorder.ondataavailable = function(e) { chunks.push(e.data); } ...
MediaRecorder - Web APIs
chunks, { 'type' : 'audio/ogg; codecs=opus' }); chunks = []; var audiourl = url.createobjecturl(blob); audio.src = audiourl; console.log("recorder stopped"); deletebutton.onclick = function(e) { evttgt = e.target; evttgt.parentnode.parentnode.removechild(evttgt.parentnode); } } mediarecorder.ondataavailable = function(e) { chunks.push(e.data); } }) .catch(function(err) { console.log('the following error occurred: ' + err); }) } this code sample is inspired by the web dictaphone demo.
MediaRecorderErrorEvent.error - Web APIs
function recordstream(stream) { let recorder = null; let bufferlist = []; try { recorder = new mediarecorder(stream); } catch(err) { /* exception while trying to create the recorder; handle that */ } recorder.ondataavailable = function(event) { bufferlist.push(event.data); }; recorder.onerror = function(event) { let error = event.error; }; recorder.start(100); /* 100ms time slices per buffer */ return recorder; } specifications specification status comment mediastream recordingthe definition of 'mediarecordererrorevent.error' in that specification.
Using the MediaStream Recording API - Web APIs
we register an event handler to do this using mediarecorder.ondataavailable: let chunks = []; mediarecorder.ondataavailable = function(e) { chunks.push(e.data); } note: the browser will fire dataavailable events as needed, but if you want to intervene you can also include a timeslice when invoking the start() method — for example start(10000) — to control this interval, or call mediarecorder.requestdata() to trigger an event when you need it.
MediaStream Recording API - Web APIs
var stream = canvas.capturestream(25); var recordedchunks = []; console.log(stream); var options = { mimetype: "video/webm; codecs=vp9" }; mediarecorder = new mediarecorder(stream, options); mediarecorder.ondataavailable = handledataavailable; mediarecorder.start(); function handledataavailable(event) { console.log("data-available"); if (event.data.size > 0) { recordedchunks.push(event.data); console.log(recordedchunks); download(); } else { // ...
NDEFWriter.write() - Web APIs
WebAPINDEFWriterwrite
notsupportederror there is no nfc adapter compatible with web nfc, or the available nfc adapter does not support pushing messages, or connection can not be established.
navigator.hardwareConcurrency - Web APIs
let workerlist = []; for (let i = 0; i < window.navigator.hardwareconcurrency; i++) { let newworker = { worker: new worker('cpuworker.js'), inuse: false }; workerlist.push(newworker); } specification specification status comment html living standardthe definition of 'navigator.hardwareconcurrency' in that specification.
Using the Notifications API - Web APIs
because of abuses of push notifications in the past, web browsers and developers have begun to implement strategies to help mitigate this problem.
Page Visibility API - Web APIs
a site has an image carousel that shouldn't advance to the next slide unless the user is viewing the page an application showing a dashboard of information doesn't want to poll the server for updates when the page isn't visible a page wants to detect when it is being prerendered so it can keep accurate count of page views a site wants to switch off sounds when a device is in standby mode (user pushes power button to turn screen off) developers have historically used imperfect proxies to detect this.
ParentNode.children - Web APIs
;(function(constructor) { if (constructor && constructor.prototype && constructor.prototype.children == null) { object.defineproperty(constructor.prototype, 'children', { get: function() { let i = 0, node, nodes = this.childnodes, children = []; while (node = nodes[i++]) { if (node.nodetype === 1) { children.push(node); } } return children; } }); } })(window.node || window.element); specification specification status comment domthe definition of 'parentnode.children' in that specification.
PaymentRequest.onshippingoptionchange - Web APIs
65.00'; // shipping to elsewhere is unsupported } else { // empty array indicates rejection of the address details.shippingoptions = []; return promise.resolve(details); console.log(details.error); } // hardcode for simplicity if (details.displayitems.length === 2) { details.displayitems[2] = shippingoption; } else { details.displayitems.push(shippingoption); } details.shippingoptions = [shippingoption]; return promise.resolve(details); })(details, request.shippingaddress)); }); specifications specification status comment payment request apithe definition of 'onshippingoptionchange' in that specification.
PaymentResponse.onpayerdetailchange - Web APIs
if (oldpayername !== payername) { promisestovalidate.push(validatename(payername)); oldpayername = payername; } if (oldpayeremail !== payeremail) { promisestovalidate.push(validateemail(payeremail)); oldpayeremail = payeremail; } if (oldpayerphone !== payerphone) { promisestovalidate.push(validatephone(payerphone)); oldpayerphone = payerphone; } // as each validation promise resolves, add the results of the // validati...
PaymentResponse: payerdetailchange event - Web APIs
if (oldpayername !== payername) { promisestovalidate.push(validatename(payername)); oldpayername = payername; } if (oldpayeremail !== payeremail) { promisestovalidate.push(validateemail(payeremail)); oldpayeremail = payeremail; } if (oldpayerphone !== payerphone) { promisestovalidate.push(validatephone(payerphone)); oldpayerphone = payerphone; } // as each validation promise resolves, add the results of the // validati...
PaymentResponse.retry() - Web APIs
async function recursivevalidate(request, response) { const promisestofixthings = []; const errors = await validate(request, response); if (!errors) { return; } if (errors.shippingaddress) { // "shippingaddresschange" fired at request object const promise = fixfield(request, "shippingaddresschange", shippingvalidator); promisestofixthings.push(promise); } if (errors.payer) { // "payerdetailchange" fired at response object const promise = fixfield(response, "payerdetailchange", payervalidator); promisestofixthings.push(promise); } await promise.all([response.retry(errors), ...promisestofixthings]); await recursivevalidate(request, response); } function fixfield(requestorresponse, event, validator) { return new p...
Permissions - Web APIs
71chrome android full support 71firefox android full support 53opera android full support 50safari ios no support nosamsung internet android full support 10.0push permissionchrome full support 43edge full support 79firefox ?
Permissions API - Web APIs
notable apis that are permissions-aware include: clipboard api notifications api push api web midi api more apis will gain permissions api support over time.
Pinch zoom gestures - Web APIs
// this event is cached to support 2-finger gestures evcache.push(ev); log("pointerdown", ev); } pointer move the pointermove event handler detects if a user is invoking a two-pointer pinch/zoom gesture.
Using Pointer Events - Web APIs
function handlestart(evt) { log("pointerdown."); var el = document.getelementsbytagname("canvas")[0]; var ctx = el.getcontext("2d"); log("pointerdown: id = " + evt.pointerid); ongoingtouches.push(copytouch(evt)); var color = colorfortouch(evt); ctx.beginpath(); ctx.arc(touches[i].pagex, touches[i].pagey, 4, 0, 2 * math.pi, false); // a circle at the start ctx.arc(evt.clientx, evt.clienty, 4, 0, 2 * math.pi, false); // a circle at the start ctx.fillstyle = color; ctx.fill(); } after storing some of the event's processing in the ongoingtouches for later processing, the start...
RTCDataChannel.readyState - Web APIs
example var datachannel = peerconnection.createdatachannel("file transfer"); var sendqueue = []; function sendmessage(msg) { switch(datachannel.readystate) { case "connecting": console.log("connection not open; queueing: " + msg); sendqueue.push(msg); break; case "open": sendqueue.foreach((msg) => datachannel.send(msg)); break; case "closing": console.log("attempted to send message while closing: " + msg); break; case "closed": console.log("error!
RTCIceServers.urls - Web APIs
WebAPIRTCIceServerurls
syntax var iceserver = { urls = iceserverurl | [ url1, ..., urln ], username: "webrtc", // optional credential: "turnpassword" // optional }; iceservers.push(iceserver); the value of this property may be specified as a single url or as an array of multiple urls.
ReadableStreamDefaultController.desiredSize - Web APIs
examples the a readable stream with an underlying push source and backpressure support example in the spec provides a good example of using desiredsize to manually detect when the stream is full and apply backpressure, and also of using readablestreamdefaultcontroller.error() to manually trigger a stream error if another part of the system it relies on fails.
ReadableStreamDefaultController.error() - Web APIs
examples the a readable stream with an underlying push source and backpressure support example in the spec provides a good example of using readablestreamdefaultcontroller.desiredsize to manually detect when the stream is full and apply backpressure, and also of using error() to manually trigger a stream error if another part of the system it relies on fails.
Server-sent events - Web APIs
with server-sent events, it's possible for a server to send new data to a web page at any time, by pushing messages to the web page.
ServiceWorkerContainer.ready - Web APIs
example if ('serviceworker' in navigator) { navigator.serviceworker.ready .then(function(registration) { console.log('a service worker is active:', registration.active); // at this point, you can call methods that require an active // service worker, like registration.pushmanager.subscribe() }); } else { console.log('service workers are not supported.'); } specifications specification status comment service workersthe definition of 'serviceworkerregistration.ready' in that specification.
ServiceWorkerRegistration.navigationPreload - Web APIs
17 full support 16disabled disabled from version 16: this feature is behind the enable service workers preference.firefox full support 44notes full support 44notes notes extended support releases (esr) before firefox 78 esr do not support service workers and the push api.ie no support noopera full support 46safari full support 11.1webview android full support 59chrome android full support 59firefox android full support ...
StorageManager.estimate() - Web APIs
this variance is based on factors such as: how often the user visits public site popularity data user engagement signals like bookmarking, adding to homescreen, or accepting push notifications example in this example, we obtain the usage estimates and present the percentage of storage capacity currently used to the user.
Storage API - Web APIs
site storage—the data stored for a web site which is managed by the storage standard—includes: indexeddb databases cache api data service worker registrations web storage api data managed using window.localstorage history state information saved using history.pushstate() application caches notification data other kinds of site-accessible, site-specific data that may be maintained site storage units the site storage system described by the storage standard and interacted with using the storage api consists of a single site storage unit for each origin.
Streams API concepts - Web APIs
there are two types of underlying source: push sources constantly push data at you when you’ve accessed them, and it is up to you to start, pause, or cancel access to the stream.
Multi-touch interaction - Web APIs
ev.preventdefault(); // cache the touch points for later processing of 2-touch pinch/zoom if (ev.targettouches.length == 2) { for (var i=0; i < ev.targettouches.length; i++) { tpcache.push(ev.targettouches[i]); } } if (logevents) log("touchstart", ev, true); update_background(ev); } touch move handler the touchmove handler calls preventdefault() for the same reason mentioned above, and invokes the pinch/zoom handler.
VideoTrack.label - Web APIs
WebAPIVideoTracklabel
function gettracklist(el) { var tracklist = []; const wantedkinds = [ "main", "alternative", "commentary" ]; el.videotracks.foreach(function(track) { if (wantedkinds.includes(track.kind)) { tracklist.push({ id: track.id, kind: track.kind, label: track.label }); } }); return tracklist; } the resulting tracklist contains an array of video tracks whose kind is one of those in the array wantedkinds, with each entry providing the track's id, kind, and label.
WebGLRenderingContext - Web APIs
webglrenderingcontext.commit() pushes frames back to the original htmlcanvaselement, if the context is not directly fixed to a specific canvas.
WebGL best practices - Web APIs
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.
Viewpoints and viewers: Simulating cameras in WebXR - Web APIs
for example: const transform = createperspectivematrix(viewport, 130, 1, 100); const translatevec = vec3.fromvalues(-trackdistance, -cranedistance, pushdistance); mat4.translate(transform, transform, translatevec); this starts with the perspective matrix representing a 130° vertical field of view, then applies a translation that moves the camera in a manner that includes track, crane, and push movements.
Migrating from webkitAudioContext - Web APIs
function startsource() { var src = arguments[0]; var startargs = array.prototype.slice.call(arguments, 1); src.onended = function() { sources.splice(sources.indexof(src), 1); } sources.push(src); src.start.apply(src, startargs); } function activesources() { return sources.length; } var src0 = context.createbuffersource(); var src0 = context.createbuffersource(); // set buffers and other parameters...
Functions and classes available to Web Workers - Web APIs
28 (28) (yes) (yes) (yes) server-sent events allows a server to push data to a web page at any point, after a connection has been opened to it.
Web Workers API - Web APIs
they will also allow access to push notifications and background sync apis.
Window.history - Web APIs
WebAPIWindowhistory
in particular, that article explains security features of the pushstate() and replacestate() methods that you should be aware of before using them.
window.location - Web APIs
WebAPIWindowlocation
the hash: function reloadpagewithhash() { var initialpage = location.pathname; location.replace('http://example.com/#' + initialpage); } example #4: display the properties of the current url in an alert dialog: function showloc() { var olocation = location, alog = ["property (typeof): value", "location (" + (typeof olocation) + "): " + olocation ]; for (var sprop in olocation){ alog.push(sprop + " (" + (typeof olocation[sprop]) + "): " + (olocation[sprop] || "n/a")); } alert(alog.join("\n")); } // in html: <button onclick="showloc();">show location properties</button> example #5: send a string of data to the server by modifying the search property: function senddata (sdata) { location.search = sdata; } // in html: <button onclick="senddata('some data');">send data</but...
XMLHttpRequest.multipart - Web APIs
this enables support for server push; for each xml document that's written to this request, a new xml dom document is created and the onload handler is called between documents.
XPathResult.iterateNext() - Web APIs
html <div>xpath example</div> <div>tag names of the matched nodes: <output></output></div> javascript var xpath = "//div"; var result = document.evaluate(xpath, document, null, xpathresult.any_type, null); var node = null; var tagnames = []; while(node = result.iteratenext()) { tagnames.push(node.localname); } document.queryselector("output").textcontent = tagnames.join(", "); result specifications specification status comment document object model (dom) level 3 xpath specificationthe definition of 'xpathresult.iteratenext()' in that specification.
XPathResult.snapshotItem() - Web APIs
html <div>xpath example</div> <div>tag names of the matched nodes: <output></output></div> javascript var xpath = "//div"; var result = document.evaluate(xpath, document, null, xpathresult.ordered_node_snapshot_type, null); var node = null; var tagnames = []; for(var i = 0; i < result.snapshotlength; i++) { var node = result.snapshotitem(i); tagnames.push(node.localname); } document.queryselector("output").textcontent = tagnames.join(", "); result specifications specification status comment document object model (dom) level 3 xpath specificationthe definition of 'xpathresult.snapshotitem()' in that specification.
XSL Transformations in Mozilla FAQ - Web APIs
a known workaround is to add a sufficiently long xml comment to the beginning of your xml file in order to "push" the <feed> or <rss> tag out of the first 512 bytes, which is analyzed by firefox to determine if it's a feed or not.
Implementing a Microsoft Active Accessibility (MSAA) Server - Accessibility
role_row role_cell [important] role_link [important] role_helpballoon role_character role_list [important] role_listitem [important] role_outline [important] role_outlineitem [important] role_pagetab [important] role_propertypage [important] role_indicator role_graphic [important] role_statictext [important] role_text [important] role_pushbutton [important] role_checkbutton [important] role_radiobutton [important] role_combobox [important] role_droplist [important] role_progressbar [important] role_dial role_hotkeyfield role_slider role_spinbutton role_diagram role_animation role_equation role_buttondropdown role_buttonmenu role_buttondropdowngrid role_whitespace r...
Box alignment for block, absolutely positioned and table layout - CSS: Cascading Style Sheets
a margin of auto will absorb all available space in that dimension, therefore setting a left and right margin of auto, you can push a block into the center: .container { width: 20em; margin-left: auto; margin-right: auto; } in table layout, you have access to the vertical-align property to align the contents of a cell inside that cell.
Box alignment in Flexbox - CSS: Cascading Style Sheets
by setting the left and right margin to auto, both sides of our block try to take up all of the available space and so push the box into the center.
Basic Concepts of Multicol - CSS: Cascading Style Sheets
you can see how this margin causes the first line of text to be pushed down.
Styling Columns - CSS: Cascading Style Sheets
note that the rule itself does not take up any space: a wide rule will not push the columns apart to make space for the rule.
Line-based placement with CSS Grid - CSS: Cascading Style Sheets
one of the very nice things about grid layout is this ability to have white space in our designs without having to push things around using margins to prevent floats from rising up into the space we have left.
Consistent list indentation - CSS: Cascading Style Sheets
one of the most common style changes made to lists is a change in the indentation distance—that is, how far the list items are pushed over to the right.
Recipe: Media objects - CSS: Cascading Style Sheets
this means that when we have a footer, with short content above, the footer can be pushed down to the bottom of the media object.
<color> - CSS: Cascading Style Sheets
activetext text of active links buttonface background of push buttons buttontext text of push buttons canvas background of application content or documents canvastext text in application content or documents field background of input fields fieldtext text in input fields graytext text that is disabled highlight background of items that are selected in a control highlighttext text of items that are selected in ...
Adapting to the new two-value syntax of display - CSS: Cascading Style Sheets
the reason we tend to use it is to allow padding to push inline items away from an element, when creating navigation items for example, or when wanting to add a background with padding to an inline element as in the example below.
pointer-events - CSS: Cascading Style Sheets
recommendation initial definition its extension to html elements, though present in early drafts of css basic user interface module level 3, has been pushed to its level 4.
Ajax - Developer guides
WebGuideAJAX
with server-sent events, it's possible for a server to send new data to a web page at any time, by pushing messages to the web page.
Guide to Web APIs - Developer guides
WebGuideAPI
apihigh resolution timehistory apiiimage capture apiindexeddbintersection observer apillong tasks api mmedia capabilities api media capture and streamsmedia session apimedia source extensions mediastream recordingnnavigation timingnetwork information api ppage visibility apipayment request apiperformance apiperformance timeline apipermissions apipointer eventspointer lock apiproximity events push api rresize observer apiresource timing apisserver sent eventsservice workers apistoragestorage access apistreams ttouch eventsuurl apivvibration apivisual viewport wweb animationsweb audio apiweb authentication apiweb crypto apiweb notificationsweb storage apiweb workers apiwebglwebrtcwebvttwebxr device apiwebsockets api ...
Adding captions and subtitles to HTML5 video - Developer guides
the first condition will never match so all will subtitles be turned off if (video.texttracks[i].language == lang) { video.texttracks[i].mode = 'showing'; this.setattribute('data-state', 'active'); } else { video.texttracks[i].mode = 'hidden'; } } subtitlesmenu.style.display = 'none'; }); subtitlemenubuttons.push(button); return listitem; } this function builds the required <li> and <button> elements, and returns them so they can be added to the subtitles menu list.
Video player styling basics - Developer guides
in addition, the buttons need to be pushed below the progress container so that they are visible.
Audio and Video Delivery - Developer guides
the main mechanism is outlined below: navigator.mediadevices.getusermedia({audio:true}) .then(function onsuccess(stream) { var recorder = new mediarecorder(stream); var data = []; recorder.ondataavailable = function(e) { data.push(e.data); }; recorder.start(); recorder.onerror = function(e) { throw e.error || new error(e.name); // e.name is ff non-spec } recorder.onstop = function(e) { var audio = document.createelement('audio'); audio.src = window.url.createobjecturl(new blob(data)); } settimeout(function() { rec.stop(); }, 5000); }) .catch(function onerror(error...
HTML5 - Developer guides
WebGuideHTMLHTML5
server-sent events allows a server to push events to a client, rather than the classical paradigm where the server could send data only in response to a client's request.
<input type="button"> - HTML: Hypertext Markup Language
WebHTMLElementinputbutton
<input> elements of type button are rendered as simple push buttons, which can be programmed to control custom functionality anywhere on a webpage as required when assigned an event handler function (typically for the click event).
<input type="radio"> - HTML: Hypertext Markup Language
WebHTMLElementinputradio
they are called radio buttons because they look and operate in a similar manner to the push buttons on old-fashioned radios, such as the one shown below.
<input>: The Input (Form Input) element - HTML: Hypertext Markup Language
WebHTMLElementinput
the available types are as follows: type description basic examples spec button a push button with no default behavior displaying the value of the value attribute, empty by default.
<isindex> - HTML: Hypertext Markup Language
WebHTMLElementisindex
on november 1992, indexes as links rather than documents started by dan connolly who is pushing the idea that indexes are more links than documents.
HTML documentation index - HTML: Hypertext Markup Language
WebHTMLIndex
119 <input type="button"> element, forms, html, html forms, input, input element, input type, reference, button <input> elements of type button are rendered as simple push buttons, which can be programmed to control custom functionality anywhere on a webpage as required when assigned an event handler function (typically for the click event).
Browser detection using the user agent - HTTP
function(mq, f) { if(/height|width/.test(mq.media)) mql.push([mq, f]); mq.addlistener(f), mq.addlistener(whenmediachanges); } : function(){}; var destroymediaquery = iswebkit ?
Save-Data - HTTP
note: disabling http/2 server push (rfc 7540, section 8.2: server push) might be desirable too for reducing data downloads.
HTTP Messages - HTTP
WebHTTPMessages
for example, get indicates that a resource should be fetched or post means that data is pushed to the server (creating or modifying a resource, or generating a temporary document to send back).
JavaScript data types and data structures - JavaScript
for example, indexof (searching a value in the array) or push (adding an element to the array), and so on.
Enumerability and ownership of properties - JavaScript
verflow.com/a/8024294/271577 _getpropertynames: function getallpropertynames(obj, iterateselfbool, iterateprototypebool, includepropcb) { var props = []; do { if (iterateselfbool) { object.getownpropertynames(obj).foreach(function(prop) { if (props.indexof(prop) === -1 && includepropcb(obj, prop)) { props.push(prop); } }); } if (!iterateprototypebool) { break; } iterateselfbool = true; } while (obj = object.getprototypeof(obj)); return props; } }; detection table in for..in obj.hasownproperty obj.propertyisenumerable object.keys object.getownpropertynam...
Grammar and types - JavaScript
const my_array = ['html','css']; my_array.push('javascript'); console.log(my_array); //logs ['html','css','javascript']; data structures and types data types the latest ecmascript standard defines eight data types: seven data types that are primitives: boolean.
Inheritance and the prototype chain - JavaScript
function graph() { this.vertices = []; this.edges = []; } graph.prototype = { addvertex: function(v) { this.vertices.push(v); } }; var g = new graph(); // g is an object with own properties 'vertices' and 'edges'.
TypeError: setting getter-only property "x" - JavaScript
is an attempt to set the temperature property, or you will need to implement a setter for it, for example like this: "use strict"; function archiver() { var temperature = null; var archive = []; object.defineproperty(this, 'temperature', { get: function() { console.log('get!'); return temperature; }, set: function(value) { temperature = value; archive.push({ val: temperature }); } }); this.getarchive = function() { return archive; }; } var arc = new archiver(); arc.temperature; // 'get!' arc.temperature = 11; arc.temperature = 13; arc.getarchive(); // [{ val: 11 }, { val: 13 }] ...
TypeError: "x" is not a function - JavaScript
an example helpers library (helpers.js) let helpers = function () { }; helpers.groupby = function (objectarray, property) { return objectarray.reduce(function (acc, obj) { var key = obj[property]; if (!acc[key]) { acc[key] = []; } acc[key].push(obj); return acc; }, {}); } export default helpers; the correct import usage (app.js): import helpers from './helpers' ...
Default parameters - JavaScript
function append(value, array = []) { array.push(value) return array } append(1) // [1] append(2) // [2], not [1, 2] this even applies to functions and variables: function callsomething(thing = something()) { return thing } let numberoftimescalled = 0 function something() { numberoftimescalled += 1 return numberoftimescalled } callsomething() // 1 callsomething() // 2 earlier parameters are available to later default paramet...
setter - JavaScript
when current is assigned a value, it updates log with that value: const language = { set current(name) { this.log.push(name); }, log: [] } language.current = 'en'; console.log(language.log); // ['en'] language.current = 'fa'; console.log(language.log); // ['en', 'fa'] note that current is not defined, and any attempts to access it will result in undefined.
Array.prototype[@@unscopables] - JavaScript
var keys = []; with (array.prototype) { keys.push('something'); } object.keys(array.prototype[symbol.unscopables]); // ["copywithin", "entries", "fill", "find", "findindex", // "includes", "keys", "values"] specifications specification ecmascript (ecma-262)the definition of 'array.prototype[@@unscopables]' in that specification.
Array.prototype.concat() - JavaScript
anumeric = letters.concat(1, [2, 3]); console.log(alphanumeric); // results in ['a', 'b', 'c', 1, 2, 3] concatenating nested arrays the following code concatenates nested arrays and demonstrates retention of references: const num1 = [[1]]; const num2 = [2, [3]]; const numbers = num1.concat(num2); console.log(numbers); // results in [[1], 2, [3]] // modify the first element of num1 num1[0].push(4); console.log(numbers); // results in [[1, 4], 2, [3]] specifications specification ecmascript (ecma-262)the definition of 'array.prototype.concat' in that specification.
Array.prototype.every() - JavaScript
ndex+1] -= 1 console.log(`[${arr}][${index}] -> ${elem}`) return elem < 2 }) // loop runs for 3 iterations, but would // have run 2 iterations without any modification // // 1st iteration: [1,1,3,4][0] -> 1 // 2nd iteration: [1,1,2,4][1] -> 1 // 3rd iteration: [1,1,2,3][2] -> 2 // --------------- // appending items // --------------- arr = [1, 2, 3]; arr.every( (elem, index, arr) => { arr.push('new') console.log(`[${arr}][${index}] -> ${elem}`) return elem < 4 }) // loop runs for 3 iterations, even after appending new items // // 1st iteration: [1, 2, 3, new][0] -> 1 // 2nd iteration: [1, 2, 3, new, new][1] -> 2 // 3rd iteration: [1, 2, 3, new, new, new][2] -> 3 // --------------- // deleting items // --------------- arr = [1, 2, 3, 4]; arr.every( (elem, index, arr) => { arr.po...
Array.prototype.flat() - JavaScript
using a stack // note that depth control is hard/inefficient as we will need to tag each value with its own depth // also possible w/o reversing on shift/unshift, but array ops on the end tends to be faster function flatten(input) { const stack = [...input]; const res = []; while(stack.length) { // pop value from stack const next = stack.pop(); if(array.isarray(next)) { // push back array items, won't modify the original input stack.push(...next); } else { res.push(next); } } // reverse to restore input order return res.reverse(); } const arr = [1, 2, [3, 4, [5, 6]]]; flatten(arr); // [1, 2, 3, 4, 5, 6] use generator function function* flatten(array, depth) { if(depth === undefined) { depth = 1; } for(const item of array) ...
Array.prototype.indexOf() - JavaScript
var array = [2, 9, 9]; array.indexof(2); // 0 array.indexof(7); // -1 array.indexof(9, 2); // 2 array.indexof(2, -1); // -1 array.indexof(2, -3); // 0 finding all the occurrences of an element var indices = []; var array = ['a', 'b', 'a', 'c', 'a', 'd']; var element = 'a'; var idx = array.indexof(element); while (idx != -1) { indices.push(idx); idx = array.indexof(element, idx + 1); } console.log(indices); // [0, 2, 4] finding if an element exists in the array or not and updating the array function updatevegetablescollection (veggies, veggie) { if (veggies.indexof(veggie) === -1) { veggies.push(veggie); console.log('new veggies collection is : ' + veggies); } else if (veggies.indexof(veggie) > -1) { ...
Array.of() - JavaScript
if (!array.of) { array.of = function() { return array.prototype.slice.call(arguments); // or let vals = []; for(let prop in arguments){ vals.push(arguments[prop]); } return vals; } } examples using array.of array.of(1); // [1] array.of(1, 2, 3); // [1, 2, 3] array.of(undefined); // [undefined] specifications specification ecmascript (ecma-262)the definition of 'array.of' in that specification.
Function.prototype.bind() - JavaScript
unction throw new typeerror('function.prototype.bind - what is trying to be bound is not callable'); } var baseargs= arrayprototypeslice.call(arguments, 1), baseargslength = baseargs.length, ftobind = this, fnop = function() {}, fbound = function() { baseargs.length = baseargslength; // reset to default base arguments baseargs.push.apply(baseargs, arguments); return ftobind.apply( fnop.prototype.isprototypeof(this) ?
Generator.prototype.next() - JavaScript
// "object { value: 2, done: false }" g.next(); // "object { value: 3, done: false }" g.next(); // "object { value: undefined, done: true }" using next() with a list function* getpage(pagesize = 1, list) { let output = []; let index = 0; while (index < list.length) { output = []; for (let i = index; i < index + pagesize; i++) { if (list[i]) { output.push(list[i]); } } yield output; index += pagesize; } } list = [1, 2, 3, 4, 5, 6, 7, 8] var page = getpage(3, list); // generator { } page.next(); // object {value: (3) [1, 2, 3], done: false} page.next(); // object {value: (3) [4, 5, 6], done: false} page.next(); // object {value...
JSON.stringify() - JavaScript
ering the same object like above example of using json.stringify() with localstorage in a case where you want to store an object created by your user and allowing it to be restored even after the browser has been closed, the following example is a model for the applicability of json.stringify(): // creating an example of json var session = { 'screens': [], 'state': true }; session.screens.push({ 'name': 'screena', 'width': 450, 'height': 250 }); session.screens.push({ 'name': 'screenb', 'width': 650, 'height': 350 }); session.screens.push({ 'name': 'screenc', 'width': 750, 'height': 120 }); session.screens.push({ 'name': 'screend', 'width': 250, 'height': 60 }); session.screens.push({ 'name': 'screene', 'width': 390, 'height': 120 }); session.screens.push({ 'name': 'screenf', 'width': ...
Object.defineProperties() - JavaScript
d.set = s; } if (('get' in d || 'set' in d) && ('value' in d || 'writable' in d)) throw new typeerror('identity-confused descriptor'); return d; } if (typeof obj !== 'object' || obj === null) throw new typeerror('bad obj'); properties = object(properties); var keys = object.keys(properties); var descs = []; for (var i = 0; i < keys.length; i++) descs.push([keys[i], converttodescriptor(properties[keys[i]])]); for (var i = 0; i < descs.length; i++) object.defineproperty(obj, descs[i][0], descs[i][1]); return obj; } examples using object.defineproperties var obj = {}; object.defineproperties(obj, { 'property1': { value: true, writable: true }, 'property2': { value: 'hello', writable: false } // etc.
Object.defineProperty() - JavaScript
function archiver() { var temperature = null; var archive = []; object.defineproperty(this, 'temperature', { get() { console.log('get!'); return temperature; }, set(value) { temperature = value; archive.push({ val: temperature }); } }); this.getarchive = function() { return archive; }; } var arc = new archiver(); arc.temperature; // 'get!' arc.temperature = 11; arc.temperature = 13; arc.getarchive(); // [{ val: 11 }, { val: 13 }] in this example, a getter always returns the same value.
Object.freeze() - JavaScript
a[0] = 1; // fails silently // in strict mode such attempt will throw a typeerror function fail() { "use strict" a[0] = 1; } fail(); // attempted to push a.push(2); // throws a typeerror the object being frozen is immutable.
Object.keys() - JavaScript
enumerable', 'constructor' ], dontenumslength = dontenums.length; return function(obj) { if (typeof obj !== 'function' && (typeof obj !== 'object' || obj === null)) { throw new typeerror('object.keys called on non-object'); } var result = [], prop, i; for (prop in obj) { if (hasownproperty.call(obj, prop)) { result.push(prop); } } if (hasdontenumbug) { for (i = 0; i < dontenumslength; i++) { if (hasownproperty.call(obj, dontenums[i])) { result.push(dontenums[i]); } } } return result; }; }()); } please note that the above code includes non-enumerable keys in ie7 (and maybe ie8), when passing in an object from a different wind...
Promise - JavaScript
the return causes a promise to be popped, but the nextvalue promise is pushed into its place.
String.fromCodePoint() - JavaScript
inity`, `+infinity` // the surrounding `!(...)` is required to correctly handle `nan` cases // the (codepoint>>>0) === codepoint clause handles decimals and negatives if (!(codepoint < 0x10ffff && (codepoint>>>0) === codepoint)) throw rangeerror("invalid code point: " + codepoint); if (codepoint <= 0xffff) { // bmp code point codelen = codeunits.push(codepoint); } else { // astral code point; split in surrogate halves // https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae codepoint -= 0x10000; codelen = codeunits.push( (codepoint >> 10) + 0xd800, // highsurrogate (codepoint % 0x400) + 0xdc00 // lowsurrogate ); } if (codelen >= 0x3fff) { ...
String - JavaScript
for example: let outputstrings = [] for (let i = 0, n = inputvalues.length; i < n; ++i) { outputstrings.push(string(inputvalues[i])); } specifications specification ecmascript (ecma-262)the definition of 'string' in that specification.
Symbol.unscopables - JavaScript
var keys = []; with (array.prototype) { keys.push('something'); } object.keys(array.prototype[symbol.unscopables]); // ["copywithin", "entries", "fill", "find", "findindex", // "includes", "keys", "values"] unscopables in objects you can also set unscopables for your own objects.
TypedArray.from() - JavaScript
return elem; }; if (typeof func !== 'function') { throw new typeerror('specified argument is not a function'); } obj = object(obj); if (!obj['length']) { return new this(0); } var copy_data = []; for(var i = 0; i < obj.length; i++) { copy_data.push(obj[i]); } copy_data = copy_data.map(func, thisobj); var typed_array = new this(copy_data.length); for(var i = 0; i < typed_array.length; i++) { typed_array[i] = copy_data[i]; } return typed_array; } })(); } examples from an iterable object (set) const s = new set([1, 2, 3]); uint8array.from(s...
WeakMap - JavaScript
setting elements on this map would involve pushing a key and value onto the end of each of those arrays simultaneously.
const - JavaScript
my_object = {'other_key': 'value'}; // however, object keys are not protected, // so the following statement is executed without problem my_object.key = 'othervalue'; // use object.freeze() to make object immutable // the same applies to arrays const my_array = []; // it's possible to push items into the array my_array.push('a'); // ["a"] // however, assigning a new array to the variable throws an error // uncaught typeerror: assignment to constant variable.
Template literals (Template strings) - JavaScript
values[key] : dict[key]; result.push(value, strings[i + 1]); }); return result.join(''); }); } let t1closure = template`${0}${1}${0}!`; //let t1closure = template(["","","","!"],0,1,0); t1closure('y', 'a'); // "yay!" let t2closure = template`${0} ${'foo'}!`; //let t2closure = template([""," ","!"],0,"foo"); t2closure('hello', {foo: 'world'}); // "hello world!" let t3closure = template`i'm ${'name'}.
JavaScript typed arrays - JavaScript
push and pop).
Codecs used by WebRTC - Web media technologies
the prefercodec() function called by the code above looks like this to move a specified codec to the top of the list (to be prioritized during negotiation): function prefercodec(codecs, mimetype) { let othercodecs = []; let sortedcodecs = []; let count = codecs.length; codecs.foreach(codec => { if (codec.mimetype === mimetype) { sortedcodecs.push(codec); } else { othercodecs.push(codec); } }); return sortedcodecs.concat(othercodecs); } this code is just splitting the codec list into two arrays: one containing codecs whose mime type matches the one specified by the mimetype parameter, and the other with all the other codecs.
CSS and JavaScript animation performance - Web Performance
developers can create an animation by simply changing an element's style each time the loop is called (or updating the canvas draw, or whatever.) note: like css transitions and animations, requestanimationframe() pauses when the current tab is pushed into the background.
Performance fundamentals - Web Performance
but often trading some generality and quality for speed, such as using a static rendering instead of a css radial gradient, can push scrolling framerate over a target.
Optimizing startup performance - Web Performance
emscripten provides an api to help with this refactoring; for example, you can use emscripten_push_main_loop_blocker() to establish a function to be executed before the main thread is allowed to continue.
Performance budgets - Web Performance
the sooner that you can identify a potential addition pushing the budget, the better you can analyze the current state of your site, and pinpoint optimizations or unnecessary code.
Performance Monitoring: RUM vs synthetic monitoring - Web Performance
changes from baseline performance as part of continuous integration should fail a push.
PWA developer guide - Progressive web apps (PWAs)
using service workers to run offline description alerting the user using notifications description creating a web app from an existing site description advanced topics pushing data from the server to your web application some description resource management description integration with the host device description security and privacy description gaming topics for web app developers description polishing web apps web api equivalents for common native apis some description platform-specific tips and issues description web application performance gu...
How to make PWAs installable - Progressive web apps (PWAs)
now let's move to the last piece of the pwa puzzle: using push notifications to share announcements with the user, and to help the user re-engage with your app.
stroke-dashoffset - SVG: Scalable Vector Graphics
30" y2="1" stroke="black" /> <!-- no dash offset --> <line x1="0" y1="3" x2="30" y2="3" stroke="black" stroke-dasharray="3 1" /> <!-- the start of the dash array computation is pulled by 3 user units --> <line x1="0" y1="5" x2="30" y2="5" stroke="black" stroke-dasharray="3 1" stroke-dashoffset="3" /> <!-- the start of the dash array computation is pushed by 3 user units --> <line x1="0" y1="7" x2="30" y2="7" stroke="black" stroke-dasharray="3 1" stroke-dashoffset="-3" /> <!-- the start of the dash array computation is pulled by 1 user units which ends up in the same rendering as the previous example --> <line x1="0" y1="9" x2="30" y2="9" stroke="black" stroke-dasharray="3 1" stroke-dashoffset="1...
Example - SVG: Scalable Vector Graphics
while( motes.length < num ) motes.push( new mote() ); // or too many?
Features restricted to secure contexts - Web security
push api 42 17 not supported 44 reporting api supported not supported not supported behind flag since fx 65 service workers 40 17 11.1 44 storage api 55 not supported not supported 51 web authentication api 65 in preview (17) in development 60 web bluetooth 56 not supported not supported ...
XPath snippets - XPath
anode.documentelement : anode.ownerdocument.documentelement); var result = xpe.evaluate(aexpr, anode, nsresolver, 0, null); var found = []; var res; while (res = result.iteratenext()) found.push(res); return found; } this function uses the new xpathevaluator() constructor, which is supported in firefox, chrome, opera and safari, but not in edge or internet explorer.